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
968ad7fe2efbdcf9bfcd77be1b8b47d340aee99e
0
milleruntime/accumulo,adamjshook/accumulo,ctubbsii/accumulo,mjwall/accumulo,dhutchis/accumulo,phrocker/accumulo,joshelser/accumulo,keith-turner/accumulo,apache/accumulo,ctubbsii/accumulo,wjsl/jaredcumulo,ivakegg/accumulo,wjsl/jaredcumulo,mikewalch/accumulo,adamjshook/accumulo,wjsl/jaredcumulo,lstav/accumulo,dhutchis/accumulo,adamjshook/accumulo,apache/accumulo,phrocker/accumulo,dhutchis/accumulo,adamjshook/accumulo,milleruntime/accumulo,dhutchis/accumulo,ivakegg/accumulo,milleruntime/accumulo,mjwall/accumulo,ivakegg/accumulo,joshelser/accumulo,wjsl/jaredcumulo,keith-turner/accumulo,mikewalch/accumulo,mjwall/accumulo,apache/accumulo,ctubbsii/accumulo,adamjshook/accumulo,milleruntime/accumulo,phrocker/accumulo,wjsl/jaredcumulo,wjsl/jaredcumulo,apache/accumulo,adamjshook/accumulo,keith-turner/accumulo,phrocker/accumulo-1,adamjshook/accumulo,adamjshook/accumulo,apache/accumulo,phrocker/accumulo-1,phrocker/accumulo,keith-turner/accumulo,wjsl/jaredcumulo,joshelser/accumulo,keith-turner/accumulo,dhutchis/accumulo,phrocker/accumulo-1,mjwall/accumulo,keith-turner/accumulo,ctubbsii/accumulo,mikewalch/accumulo,milleruntime/accumulo,phrocker/accumulo,dhutchis/accumulo,lstav/accumulo,dhutchis/accumulo,ivakegg/accumulo,joshelser/accumulo,wjsl/jaredcumulo,phrocker/accumulo,dhutchis/accumulo,mikewalch/accumulo,ivakegg/accumulo,phrocker/accumulo,phrocker/accumulo-1,phrocker/accumulo,mikewalch/accumulo,lstav/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,dhutchis/accumulo,apache/accumulo,keith-turner/accumulo,apache/accumulo,lstav/accumulo,mikewalch/accumulo,ctubbsii/accumulo,joshelser/accumulo,joshelser/accumulo,mjwall/accumulo,mikewalch/accumulo,ivakegg/accumulo,lstav/accumulo,milleruntime/accumulo,lstav/accumulo,joshelser/accumulo,mikewalch/accumulo,ivakegg/accumulo,mjwall/accumulo,adamjshook/accumulo,phrocker/accumulo,joshelser/accumulo,lstav/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,milleruntime/accumulo,phrocker/accumulo-1,mjwall/accumulo
/* * 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.accumulo.server.tabletserver; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.UUID; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.ColumnUpdate; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.file.FileSKVIterator; import org.apache.accumulo.core.file.FileSKVWriter; import org.apache.accumulo.core.file.rfile.RFile; import org.apache.accumulo.core.file.rfile.RFileOperations; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SkippingIterator; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.iterators.SortedMapIterator; import org.apache.accumulo.core.iterators.WrappingIterator; import org.apache.accumulo.core.iterators.system.ColumnFamilySkippingIterator; import org.apache.accumulo.core.iterators.system.InterruptibleIterator; import org.apache.accumulo.core.iterators.system.SourceSwitchingIterator; import org.apache.accumulo.core.iterators.system.SourceSwitchingIterator.DataSource; import org.apache.accumulo.core.util.CachedConfiguration; import org.apache.accumulo.core.util.LocalityGroupUtil; import org.apache.accumulo.core.util.UtilWaitThread; import org.apache.accumulo.server.conf.ServerConfiguration; import org.apache.accumulo.server.trace.TraceFileSystem; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.Logger; class MemKeyComparator implements Comparator<Key> { @Override public int compare(Key k1, Key k2) { int cmp = k1.compareTo(k2); if (cmp == 0) { if (k1 instanceof MemKey) if (k2 instanceof MemKey) cmp = ((MemKey) k2).kvCount - ((MemKey) k1).kvCount; else cmp = 1; else if (k2 instanceof MemKey) cmp = -1; } return cmp; } } class PartialMutationSkippingIterator extends SkippingIterator implements InterruptibleIterator { int kvCount; public PartialMutationSkippingIterator(SortedKeyValueIterator<Key,Value> source, int maxKVCount) { setSource(source); this.kvCount = maxKVCount; } @Override protected void consume() throws IOException { while (getSource().hasTop() && ((MemKey) getSource().getTopKey()).kvCount > kvCount) getSource().next(); } @Override public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new PartialMutationSkippingIterator(getSource().deepCopy(env), kvCount); } @Override public void setInterruptFlag(AtomicBoolean flag) { ((InterruptibleIterator) getSource()).setInterruptFlag(flag); } } class MemKeyConversionIterator extends SkippingIterator implements InterruptibleIterator { MemKey currKey = null; Value currVal = null; public MemKeyConversionIterator(SortedKeyValueIterator<Key,Value> source) { super(); setSource(source); } public MemKeyConversionIterator(SortedKeyValueIterator<Key,Value> source, MemKey startKey) { this(source); try { if (currKey != null) currKey = (MemKey) startKey.clone(); } catch (CloneNotSupportedException e) { // MemKey is supported } } @Override public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new MemKeyConversionIterator(getSource().deepCopy(env), currKey); } @Override public Key getTopKey() { return currKey; } @Override public Value getTopValue() { return currVal; } private void getTopKeyVal() { Key k = super.getTopKey(); Value v = super.getTopValue(); if (k instanceof MemKey || k == null) { currKey = (MemKey) k; currVal = v; return; } currVal = new Value(v); int mc = MemValue.splitKVCount(currVal); currKey = new MemKey(k, mc); } public void next() throws IOException { super.next(); getTopKeyVal(); } @Override protected void consume() throws IOException { MemKey stopPoint = currKey; if (hasTop()) getTopKeyVal(); if (stopPoint == null) return; while (getSource().hasTop() && currKey.compareTo(stopPoint) <= 0) next(); } @Override public void setInterruptFlag(AtomicBoolean flag) { ((InterruptibleIterator) getSource()).setInterruptFlag(flag); } } public class InMemoryMap { MutationLog mutationLog; private SimpleMap map = null; private static final Logger log = Logger.getLogger(InMemoryMap.class); private volatile String memDumpFile = null; private final String memDumpDir; public InMemoryMap(boolean useNativeMap, String memDumpDir) { this.memDumpDir = memDumpDir; if (useNativeMap && NativeMap.loadedNativeLibraries()) { try { map = new NativeMapWrapper(); } catch (Throwable t) { log.error("Failed to create native map", t); } } if (map == null) { map = new DefaultMap(); } } public InMemoryMap() { this(ServerConfiguration.getSystemConfiguration().getBoolean(Property.TSERV_NATIVEMAP_ENABLED), ServerConfiguration.getSystemConfiguration().get( Property.TSERV_MEMDUMP_DIR)); } private interface SimpleMap { public Value get(Key key); public Iterator<Entry<Key,Value>> iterator(Key startKey); public int size(); public InterruptibleIterator skvIterator(); public void delete(); public long getMemoryUsed(); public void mutate(List<Mutation> mutations, int kvCount); } private static class DefaultMap implements SimpleMap { private ConcurrentSkipListMap<Key,Value> map = new ConcurrentSkipListMap<Key,Value>(new MemKeyComparator()); private AtomicLong bytesInMemory = new AtomicLong(); private AtomicInteger size = new AtomicInteger(); public void put(Key key, Value value) { // Always a MemKey, so account for the kvCount int bytesInMemory.addAndGet(key.getLength() + 4); bytesInMemory.addAndGet(value.getSize()); if (map.put(key, value) == null) size.incrementAndGet(); } public Value get(Key key) { return map.get(key); } public Iterator<Entry<Key,Value>> iterator(Key startKey) { Key lk = new Key(startKey); SortedMap<Key,Value> tm = map.tailMap(lk); return tm.entrySet().iterator(); } public int size() { return size.get(); } public synchronized InterruptibleIterator skvIterator() { if (map == null) throw new IllegalStateException(); return new SortedMapIterator(map); } public synchronized void delete() { map = null; } public long getOverheadPerEntry() { // all of the java objects that are used to hold the // data and make it searchable have overhead... this // overhead is estimated using test.EstimateInMemMapOverhead // and is in bytes.. the estimates were obtained by running // java 6_16 in 64 bit server mode return 270; } @Override public void mutate(List<Mutation> mutations, int kvCount) { for (Mutation m : mutations) { for (ColumnUpdate cvp : m.getUpdates()) { Key newKey = new MemKey(m.getRow(), cvp.getColumnFamily(), cvp.getColumnQualifier(), cvp.getColumnVisibility(), cvp.getTimestamp(), cvp.isDeleted(), false, kvCount++); Value value = new Value(cvp.getValue()); put(newKey, value); } } } @Override public long getMemoryUsed() { return bytesInMemory.get() + (size() * getOverheadPerEntry()); } } private static class NativeMapWrapper implements SimpleMap { private NativeMap nativeMap; NativeMapWrapper() { nativeMap = new NativeMap(); } public Value get(Key key) { return nativeMap.get(key); } public Iterator<Entry<Key,Value>> iterator(Key startKey) { return nativeMap.iterator(startKey); } public int size() { return nativeMap.size(); } public InterruptibleIterator skvIterator() { return (InterruptibleIterator) nativeMap.skvIterator(); } public void delete() { nativeMap.delete(); } public long getMemoryUsed() { return nativeMap.getMemoryUsed(); } @Override public void mutate(List<Mutation> mutations, int kvCount) { nativeMap.mutate(mutations, kvCount); } } private AtomicInteger nextKVCount = new AtomicInteger(1); private AtomicInteger kvCount = new AtomicInteger(0); /** * Applies changes to a row in the InMemoryMap * */ public void mutate(List<Mutation> mutations) { int numKVs = 0; for (int i = 0; i < mutations.size(); i++) numKVs += mutations.get(i).size(); int kv = nextKVCount.getAndAdd(numKVs); try { map.mutate(mutations, kv); } finally { synchronized (this) { // Can not update mutationCount while writes that started before // are in progress, this would cause partial mutations to be seen. // Also, can not continue until mutation count is updated, because // a read may not see a successful write. Therefore writes must // wait for writes that started before to finish. while (kvCount.get() != kv - 1) { try { wait(); } catch (InterruptedException ex) { // ignored } } kvCount.set(kv + numKVs - 1); notifyAll(); } } } /** * Returns a long representing the size of the InMemoryMap * * @return bytesInMemory */ public synchronized long estimatedSizeInBytes() { if (map == null) return 0; return map.getMemoryUsed(); } Iterator<Map.Entry<Key,Value>> iterator(Key startKey) { return map.iterator(startKey); } public long getNumEntries() { return map.size(); } private Set<MemoryIterator> activeIters = Collections.synchronizedSet(new HashSet<MemoryIterator>()); class MemoryDataSource implements DataSource { boolean switched = false; private InterruptibleIterator iter; private List<FileSKVIterator> readers; MemoryDataSource() { this(new ArrayList<FileSKVIterator>()); } public MemoryDataSource(List<FileSKVIterator> readers) { this.readers = readers; } @Override public boolean isCurrent() { if (switched) return true; else return memDumpFile == null; } @Override public DataSource getNewDataSource() { if (switched) throw new IllegalStateException(); if (!isCurrent()) { switched = true; iter = null; } return this; } @Override public SortedKeyValueIterator<Key,Value> iterator() throws IOException { if (iter == null) if (!switched) iter = map.skvIterator(); else { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = TraceFileSystem.wrap(FileSystem.getLocal(conf)); FileSKVIterator reader = new RFileOperations().openReader(memDumpFile, true, fs, conf, ServerConfiguration.getSiteConfiguration()); readers.add(reader); iter = reader; } return iter; } @Override public DataSource getDeepCopyDataSource(IteratorEnvironment env) { return new MemoryDataSource(readers); } } class MemoryIterator extends WrappingIterator implements InterruptibleIterator { private AtomicBoolean closed; private SourceSwitchingIterator ssi; private MemoryDataSource mds; protected SortedKeyValueIterator<Key,Value> getSource() { if (closed.get()) throw new IllegalStateException("Memory iterator is closed"); return super.getSource(); } private MemoryIterator(InterruptibleIterator source) { this(source, new AtomicBoolean(false)); } private MemoryIterator(SortedKeyValueIterator<Key,Value> source, AtomicBoolean closed) { setSource(source); this.closed = closed; } public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new MemoryIterator(getSource().deepCopy(env), closed); } public void close() { synchronized (this) { if (closed.compareAndSet(false, true)) { for (FileSKVIterator reader : mds.readers) try { reader.close(); } catch (IOException e) { log.warn(e, e); } } } // remove outside of sync to avoid deadlock activeIters.remove(this); } private synchronized boolean switchNow() throws IOException { if (closed.get()) return false; ssi.switchNow(); return true; } @Override public void setInterruptFlag(AtomicBoolean flag) { ((InterruptibleIterator) getSource()).setInterruptFlag(flag); } private void setSSI(SourceSwitchingIterator ssi) { this.ssi = ssi; } public void setMDS(MemoryDataSource mds) { this.mds = mds; } } public synchronized MemoryIterator skvIterator() { if (map == null) throw new NullPointerException(); if (deleted) throw new IllegalStateException("Can not obtain iterator after map deleted"); int mc = kvCount.get(); MemoryDataSource mds = new MemoryDataSource(); SourceSwitchingIterator ssi = new SourceSwitchingIterator(new MemoryDataSource()); MemoryIterator mi = new MemoryIterator(new ColumnFamilySkippingIterator(new PartialMutationSkippingIterator(new MemKeyConversionIterator(ssi), mc))); mi.setSSI(ssi); mi.setMDS(mds); activeIters.add(mi); return mi; } public SortedKeyValueIterator<Key,Value> compactionIterator() { if (nextKVCount.get() - 1 != kvCount.get()) throw new IllegalStateException("Memory map in unexpected state : nextKVCount = " + nextKVCount.get() + " kvCount = " + kvCount.get()); return new ColumnFamilySkippingIterator(map.skvIterator()); } private boolean deleted = false; public void delete(long waitTime) { synchronized (this) { if (deleted) throw new IllegalStateException("Double delete"); deleted = true; } long t1 = System.currentTimeMillis(); while (activeIters.size() > 0 && System.currentTimeMillis() - t1 < waitTime) { UtilWaitThread.sleep(50); } if (activeIters.size() > 0) { // dump memmap exactly as is to a tmp file on disk, and switch scans to that temp file try { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = TraceFileSystem.wrap(FileSystem.getLocal(conf)); String tmpFile = memDumpDir + "/memDump" + UUID.randomUUID() + "." + RFile.EXTENSION; Configuration newConf = new Configuration(conf); newConf.setInt("io.seqfile.compress.blocksize", 100000); FileSKVWriter out = new RFileOperations().openWriter(tmpFile, fs, newConf, ServerConfiguration.getSiteConfiguration()); out.startDefaultLocalityGroup(); InterruptibleIterator iter = map.skvIterator(); iter.seek(new Range(), LocalityGroupUtil.EMPTY_CF_SET, false); while (iter.hasTop() && activeIters.size() > 0) { // RFile does not support MemKey, so we move the kv count into the value only for the RFile. // There is no need to change the MemKey to a normal key because the kvCount info gets lost when it is written Value newValue = new MemValue(iter.getTopValue(), ((MemKey) iter.getTopKey()).kvCount); out.append(iter.getTopKey(), newValue); iter.next(); } out.close(); log.debug("Created mem dump file " + tmpFile); memDumpFile = tmpFile; synchronized (activeIters) { for (MemoryIterator mi : activeIters) { mi.switchNow(); } } // rely on unix behavior that file will be deleted when last // reader closes it fs.delete(new Path(memDumpFile), true); } catch (IOException ioe) { log.error("Failed to create mem dump file ", ioe); while (activeIters.size() > 0) { UtilWaitThread.sleep(100); } } } SimpleMap tmpMap = map; synchronized (this) { map = null; } tmpMap.delete(); } }
src/server/src/main/java/org/apache/accumulo/server/tabletserver/InMemoryMap.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.accumulo.server.tabletserver; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.UUID; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.ColumnUpdate; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.file.FileSKVIterator; import org.apache.accumulo.core.file.FileSKVWriter; import org.apache.accumulo.core.file.rfile.RFile; import org.apache.accumulo.core.file.rfile.RFileOperations; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SkippingIterator; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.iterators.SortedMapIterator; import org.apache.accumulo.core.iterators.WrappingIterator; import org.apache.accumulo.core.iterators.system.ColumnFamilySkippingIterator; import org.apache.accumulo.core.iterators.system.InterruptibleIterator; import org.apache.accumulo.core.iterators.system.SourceSwitchingIterator; import org.apache.accumulo.core.iterators.system.SourceSwitchingIterator.DataSource; import org.apache.accumulo.core.util.CachedConfiguration; import org.apache.accumulo.core.util.LocalityGroupUtil; import org.apache.accumulo.core.util.UtilWaitThread; import org.apache.accumulo.server.conf.ServerConfiguration; import org.apache.accumulo.server.trace.TraceFileSystem; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.Logger; class MemKeyComparator implements Comparator<Key> { @Override public int compare(Key k1, Key k2) { int cmp = k1.compareTo(k2); if (cmp == 0) { if (k1 instanceof MemKey) if (k2 instanceof MemKey) cmp = ((MemKey) k2).kvCount - ((MemKey) k1).kvCount; else cmp = 1; else if (k2 instanceof MemKey) cmp = -1; } return cmp; } } class PartialMutationSkippingIterator extends SkippingIterator implements InterruptibleIterator { int kvCount; public PartialMutationSkippingIterator(SortedKeyValueIterator<Key,Value> source, int maxKVCount) { setSource(source); this.kvCount = maxKVCount; } @Override protected void consume() throws IOException { while (getSource().hasTop() && ((MemKey) getSource().getTopKey()).kvCount > kvCount) getSource().next(); } @Override public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new PartialMutationSkippingIterator(getSource().deepCopy(env), kvCount); } @Override public void setInterruptFlag(AtomicBoolean flag) { ((InterruptibleIterator) getSource()).setInterruptFlag(flag); } } class MemKeyConversionIterator extends SkippingIterator implements InterruptibleIterator { MemKey currKey = null; Value currVal = null; public MemKeyConversionIterator(SortedKeyValueIterator<Key,Value> source) { super(); setSource(source); } public MemKeyConversionIterator(SortedKeyValueIterator<Key,Value> source, MemKey startKey) { this(source); try { if (currKey != null) currKey = (MemKey) startKey.clone(); } catch (CloneNotSupportedException e) { // MemKey is supported } } @Override public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new MemKeyConversionIterator(getSource().deepCopy(env), currKey); } @Override public Key getTopKey() { return currKey; } @Override public Value getTopValue() { return currVal; } private void getTopKeyVal() { Key k = super.getTopKey(); Value v = super.getTopValue(); if (k instanceof MemKey || k == null) { currKey = (MemKey) k; currVal = v; return; } currVal = new Value(v); int mc = MemValue.splitKVCount(currVal); currKey = new MemKey(k, mc); } public void next() throws IOException { super.next(); getTopKeyVal(); } @Override protected void consume() throws IOException { MemKey stopPoint = currKey; if (hasTop()) getTopKeyVal(); if (stopPoint == null) return; while (getSource().hasTop() && currKey.compareTo(stopPoint) <= 0) next(); } @Override public void setInterruptFlag(AtomicBoolean flag) { ((InterruptibleIterator) getSource()).setInterruptFlag(flag); } } public class InMemoryMap { MutationLog mutationLog; private SimpleMap map = null; private static final Logger log = Logger.getLogger(InMemoryMap.class); private volatile String memDumpFile = null; private final String memDumpDir; public InMemoryMap(boolean useNativeMap, String memDumpDir) { this.memDumpDir = memDumpDir; if (useNativeMap && NativeMap.loadedNativeLibraries()) { try { map = new NativeMapWrapper(); } catch (Throwable t) { log.error("Failed to create native map", t); } } if (map == null) { map = new DefaultMap(); } } public InMemoryMap() { this(ServerConfiguration.getSystemConfiguration().getBoolean(Property.TSERV_NATIVEMAP_ENABLED), ServerConfiguration.getSystemConfiguration().get( Property.TSERV_MEMDUMP_DIR)); } private interface SimpleMap { public Value get(Key key); public Iterator<Entry<Key,Value>> iterator(Key startKey); public int size(); public InterruptibleIterator skvIterator(); public void delete(); public long getMemoryUsed(); public void mutate(List<Mutation> mutations, int kvCount); } private static class DefaultMap implements SimpleMap { private ConcurrentSkipListMap<Key,Value> map = new ConcurrentSkipListMap<Key,Value>(new MemKeyComparator()); private AtomicLong bytesInMemory = new AtomicLong(); private AtomicInteger size = new AtomicInteger(); public void put(Key key, Value value) { bytesInMemory.addAndGet(key.getLength()); bytesInMemory.addAndGet(value.getSize()); if (map.put(key, value) == null) size.incrementAndGet(); } public Value get(Key key) { return map.get(key); } public Iterator<Entry<Key,Value>> iterator(Key startKey) { Key lk = new Key(startKey); SortedMap<Key,Value> tm = map.tailMap(lk); return tm.entrySet().iterator(); } public int size() { return size.get(); } public synchronized InterruptibleIterator skvIterator() { if (map == null) throw new IllegalStateException(); return new SortedMapIterator(map); } public synchronized void delete() { map = null; } public long getOverheadPerEntry() { // all of the java objects that are used to hold the // data and make it searchable have overhead... this // overhead is estimated using test.EstimateInMemMapOverhead // and is in bytes.. the estimates were obtained by running // java 6_16 in 64 bit server mode return 270; } @Override public void mutate(List<Mutation> mutations, int kvCount) { for (Mutation m : mutations) { for (ColumnUpdate cvp : m.getUpdates()) { Key newKey = new MemKey(m.getRow(), cvp.getColumnFamily(), cvp.getColumnQualifier(), cvp.getColumnVisibility(), cvp.getTimestamp(), cvp.isDeleted(), false, kvCount++); Value value = new Value(cvp.getValue()); put(newKey, value); } } } @Override public long getMemoryUsed() { return bytesInMemory.get() + (size() * getOverheadPerEntry()); } } private static class NativeMapWrapper implements SimpleMap { private NativeMap nativeMap; NativeMapWrapper() { nativeMap = new NativeMap(); } public Value get(Key key) { return nativeMap.get(key); } public Iterator<Entry<Key,Value>> iterator(Key startKey) { return nativeMap.iterator(startKey); } public int size() { return nativeMap.size(); } public InterruptibleIterator skvIterator() { return (InterruptibleIterator) nativeMap.skvIterator(); } public void delete() { nativeMap.delete(); } public long getMemoryUsed() { return nativeMap.getMemoryUsed(); } @Override public void mutate(List<Mutation> mutations, int kvCount) { nativeMap.mutate(mutations, kvCount); } } private AtomicInteger nextKVCount = new AtomicInteger(1); private AtomicInteger kvCount = new AtomicInteger(0); /** * Applies changes to a row in the InMemoryMap * */ public void mutate(List<Mutation> mutations) { int numKVs = 0; for (int i = 0; i < mutations.size(); i++) numKVs += mutations.get(i).size(); int kv = nextKVCount.getAndAdd(numKVs); try { map.mutate(mutations, kv); } finally { synchronized (this) { // Can not update mutationCount while writes that started before // are in progress, this would cause partial mutations to be seen. // Also, can not continue until mutation count is updated, because // a read may not see a successful write. Therefore writes must // wait for writes that started before to finish. while (kvCount.get() != kv - 1) { try { wait(); } catch (InterruptedException ex) { // ignored } } kvCount.set(kv + numKVs - 1); notifyAll(); } } } /** * Returns a long representing the size of the InMemoryMap * * @return bytesInMemory */ public synchronized long estimatedSizeInBytes() { if (map == null) return 0; return map.getMemoryUsed(); } Iterator<Map.Entry<Key,Value>> iterator(Key startKey) { return map.iterator(startKey); } public long getNumEntries() { return map.size(); } private Set<MemoryIterator> activeIters = Collections.synchronizedSet(new HashSet<MemoryIterator>()); class MemoryDataSource implements DataSource { boolean switched = false; private InterruptibleIterator iter; private List<FileSKVIterator> readers; MemoryDataSource() { this(new ArrayList<FileSKVIterator>()); } public MemoryDataSource(List<FileSKVIterator> readers) { this.readers = readers; } @Override public boolean isCurrent() { if (switched) return true; else return memDumpFile == null; } @Override public DataSource getNewDataSource() { if (switched) throw new IllegalStateException(); if (!isCurrent()) { switched = true; iter = null; } return this; } @Override public SortedKeyValueIterator<Key,Value> iterator() throws IOException { if (iter == null) if (!switched) iter = map.skvIterator(); else { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = TraceFileSystem.wrap(FileSystem.getLocal(conf)); FileSKVIterator reader = new RFileOperations().openReader(memDumpFile, true, fs, conf, ServerConfiguration.getSiteConfiguration()); readers.add(reader); iter = reader; } return iter; } @Override public DataSource getDeepCopyDataSource(IteratorEnvironment env) { return new MemoryDataSource(readers); } } class MemoryIterator extends WrappingIterator implements InterruptibleIterator { private AtomicBoolean closed; private SourceSwitchingIterator ssi; private MemoryDataSource mds; protected SortedKeyValueIterator<Key,Value> getSource() { if (closed.get()) throw new IllegalStateException("Memory iterator is closed"); return super.getSource(); } private MemoryIterator(InterruptibleIterator source) { this(source, new AtomicBoolean(false)); } private MemoryIterator(SortedKeyValueIterator<Key,Value> source, AtomicBoolean closed) { setSource(source); this.closed = closed; } public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new MemoryIterator(getSource().deepCopy(env), closed); } public void close() { synchronized (this) { if (closed.compareAndSet(false, true)) { for (FileSKVIterator reader : mds.readers) try { reader.close(); } catch (IOException e) { log.warn(e, e); } } } // remove outside of sync to avoid deadlock activeIters.remove(this); } private synchronized boolean switchNow() throws IOException { if (closed.get()) return false; ssi.switchNow(); return true; } @Override public void setInterruptFlag(AtomicBoolean flag) { ((InterruptibleIterator) getSource()).setInterruptFlag(flag); } private void setSSI(SourceSwitchingIterator ssi) { this.ssi = ssi; } public void setMDS(MemoryDataSource mds) { this.mds = mds; } } public synchronized MemoryIterator skvIterator() { if (map == null) throw new NullPointerException(); if (deleted) throw new IllegalStateException("Can not obtain iterator after map deleted"); int mc = kvCount.get(); MemoryDataSource mds = new MemoryDataSource(); SourceSwitchingIterator ssi = new SourceSwitchingIterator(new MemoryDataSource()); MemoryIterator mi = new MemoryIterator(new ColumnFamilySkippingIterator(new PartialMutationSkippingIterator(new MemKeyConversionIterator(ssi), mc))); mi.setSSI(ssi); mi.setMDS(mds); activeIters.add(mi); return mi; } public SortedKeyValueIterator<Key,Value> compactionIterator() { if (nextKVCount.get() - 1 != kvCount.get()) throw new IllegalStateException("Memory map in unexpected state : nextKVCount = " + nextKVCount.get() + " kvCount = " + kvCount.get()); return new ColumnFamilySkippingIterator(map.skvIterator()); } private boolean deleted = false; public void delete(long waitTime) { synchronized (this) { if (deleted) throw new IllegalStateException("Double delete"); deleted = true; } long t1 = System.currentTimeMillis(); while (activeIters.size() > 0 && System.currentTimeMillis() - t1 < waitTime) { UtilWaitThread.sleep(50); } if (activeIters.size() > 0) { // dump memmap exactly as is to a tmp file on disk, and switch scans to that temp file try { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = TraceFileSystem.wrap(FileSystem.getLocal(conf)); String tmpFile = memDumpDir + "/memDump" + UUID.randomUUID() + "." + RFile.EXTENSION; Configuration newConf = new Configuration(conf); newConf.setInt("io.seqfile.compress.blocksize", 100000); FileSKVWriter out = new RFileOperations().openWriter(tmpFile, fs, newConf, ServerConfiguration.getSiteConfiguration()); out.startDefaultLocalityGroup(); InterruptibleIterator iter = map.skvIterator(); iter.seek(new Range(), LocalityGroupUtil.EMPTY_CF_SET, false); while (iter.hasTop() && activeIters.size() > 0) { // RFile does not support MemKey, so we move the kv count into the value only for the RFile. // There is no need to change the MemKey to a normal key because the kvCount info gets lost when it is written Value newValue = new MemValue(iter.getTopValue(), ((MemKey) iter.getTopKey()).kvCount); out.append(iter.getTopKey(), newValue); iter.next(); } out.close(); log.debug("Created mem dump file " + tmpFile); memDumpFile = tmpFile; synchronized (activeIters) { for (MemoryIterator mi : activeIters) { mi.switchNow(); } } // rely on unix behavior that file will be deleted when last // reader closes it fs.delete(new Path(memDumpFile), true); } catch (IOException ioe) { log.error("Failed to create mem dump file ", ioe); while (activeIters.size() > 0) { UtilWaitThread.sleep(100); } } } SimpleMap tmpMap = map; synchronized (this) { map = null; } tmpMap.delete(); } }
Accumulo-228 - add 4 bytes. Need ot reEvaluate getOverheadPerEntry git-svn-id: ee25ee0bfe882ec55abc48667331b454c011093e@1222767 13f79535-47bb-0310-9956-ffa450edef68
src/server/src/main/java/org/apache/accumulo/server/tabletserver/InMemoryMap.java
Accumulo-228 - add 4 bytes. Need ot reEvaluate getOverheadPerEntry
<ide><path>rc/server/src/main/java/org/apache/accumulo/server/tabletserver/InMemoryMap.java <ide> private AtomicInteger size = new AtomicInteger(); <ide> <ide> public void put(Key key, Value value) { <del> bytesInMemory.addAndGet(key.getLength()); <add> // Always a MemKey, so account for the kvCount int <add> bytesInMemory.addAndGet(key.getLength() + 4); <ide> bytesInMemory.addAndGet(value.getSize()); <ide> if (map.put(key, value) == null) <ide> size.incrementAndGet();
Java
apache-2.0
c6dd4c582d9f33d9d90f2a19ceb9e1ad3af37d5e
0
lkastler/koldfish-dam,lkastler/koldfish-dam
/** * */ package de.unikoblenz.west.koldfish.dam.impl; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.apache.jena.iri.IRI; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import de.unikoblenz.west.koldfish.dam.DataAccessModule; import de.unikoblenz.west.koldfish.dam.DataAccessModuleException; import de.unikoblenz.west.koldfish.dam.DataAccessModuleListener; import de.unikoblenz.west.koldfish.dam.DerefResponse; /** * This is a dummy implementation for the DataAccessModule interface. Can be configured to create * random outputs or does nothing. * * @author lkastler */ public class DummyDataAccessModule implements DataAccessModule { private static final Logger log = LogManager.getLogger(DummyDataAccessModule.class); private final Random random; private Thread t; private volatile boolean running = false; private final List<DataAccessModuleListener> listeners = new LinkedList<DataAccessModuleListener>(); private List<Long> iris = Collections.synchronizedList(new LinkedList<Long>()); public DummyDataAccessModule() { this(null); } public DummyDataAccessModule(Random random) { this.random = random; log.debug("created"); } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.LifeCycle#isStarted() */ @Override public boolean isStarted() { return running; } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.DataAccessModule#deref(org.apache.jena .iri.IRI) */ @Override public void deref(IRI iri) throws DataAccessModuleException { if (!running) { throw new DataAccessModuleException("DataAccessModule is not running!"); } log.debug("deref: " + iri.toString()); deref(0); } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.DataAccessModule#deref(long) */ @Override public void deref(long encodedIri) throws DataAccessModuleException { if (!running) { throw new DataAccessModuleException("DataAccessModule is not running!"); } log.debug("deref: " + Long.toString(encodedIri)); iris.add(encodedIri); } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.LifeCycle#start() */ @Override public void start() throws Exception { if (random != null) { t = new Thread(createRandomRunnable(random)); } else { t = new Thread(createNoopRunnable()); } t.start(); running = true; log.debug("start"); } /** * creates a dummy runnable that creates random data in random time. * * @param random - random number generator for all things random. * @return a dummy runnable that creates random data in random time. */ private Runnable createRandomRunnable(Random random) { return new Runnable() { @Override public void run() { log.debug("started"); while (!t.isInterrupted() && running) { synchronized (iris) { if (!iris.isEmpty()) { try { long iri = iris.remove(0); int size = random.nextInt(100) + 30; List<long[]> data = new LinkedList<long[]>(); for (int i = 0; i < size; ++i) { data.add(new long[] {iri, nextLong(random, Long.MAX_VALUE), nextLong(random, Long.MAX_VALUE)}); } DerefResponse res = new DerefResponse() { private static final long serialVersionUID = 1L; @Override public Iterator<long[]> iterator() { return data.iterator(); } @Override public long getEncodedDerefIri() { return iri; } }; log.debug("send: " + res); // inform listeners for (DataAccessModuleListener listener : listeners) { listener.onDerefResponse(res); } Thread.sleep((random.nextInt(10) + 1) * 100); } catch (InterruptedException e) { log.debug(e); } } } } log.debug("finished"); } }; } /** * creates a no operation dummy runnable. * * @return a no operation dummy runnable. */ private Runnable createNoopRunnable() { return new Runnable() { @Override public void run() { log.debug("started"); while (!t.isInterrupted() && running) { try { Thread.sleep(1000); } catch (InterruptedException e) { log.debug(e); } } log.debug("finished"); } }; } /** * generates a random Long value within the given range 0 to n-1. * * @param rng - Random number generator. * @param n - upper boundary for the generated long. * @return a random long between 0 and n-1. */ private long nextLong(Random rng, long n) { // see also: http://stackoverflow.com/a/2546186 long bits, val; do { bits = (rng.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0L); return val; } @Override public String toString() { return "DummyDataAccessModule [running=" + running + ", mode=" + ((random != null) ? "random" : "no-op") + "]"; } @Override public void stop() throws Exception { running = false; if (t != null) { t.interrupt(); log.debug("close"); t.join(); } } /* * (non-Javadoc) * * @see * de.unikoblenz.west.koldfish.dam.DataAccessModule#addListener(de.unikoblenz.west.koldfish.dam * .DataAccessModuleListener) */ @Override public void addListener(DataAccessModuleListener listener) { listeners.add(listener); } /* * (non-Javadoc) * * @see * de.unikoblenz.west.koldfish.dam.DataAccessModule#removeListener(de.unikoblenz.west.koldfish * .dam.DataAccessModuleListener) */ @Override public void removeListener(DataAccessModuleListener listener) { listeners.remove(listener); } }
koldfish-dam-client/src/main/java/de/unikoblenz/west/koldfish/dam/impl/DummyDataAccessModule.java
/** * */ package de.unikoblenz.west.koldfish.dam.impl; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.apache.jena.iri.IRI; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import de.unikoblenz.west.koldfish.dam.DataAccessModule; import de.unikoblenz.west.koldfish.dam.DataAccessModuleException; import de.unikoblenz.west.koldfish.dam.DataAccessModuleListener; import de.unikoblenz.west.koldfish.dam.DerefResponse; /** * This is a dummy implementation for the DataAccessModule interface. Can be configured to create * random outputs or does nothing. * * @author lkastler */ public class DummyDataAccessModule implements DataAccessModule { private static final Logger log = LogManager.getLogger(DummyDataAccessModule.class); private final Random random; private Thread t; private volatile boolean running = false; private final List<DataAccessModuleListener> listeners = new LinkedList<DataAccessModuleListener>(); private List<Long> iris = Collections.synchronizedList(new LinkedList<Long>()); public DummyDataAccessModule() { this(null); } public DummyDataAccessModule(Random random) { this.random = random; log.debug("created"); } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.LifeCycle#isStarted() */ @Override public boolean isStarted() { return running; } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.DataAccessModule#deref(org.apache.jena .iri.IRI) */ @Override public void deref(IRI iri) throws DataAccessModuleException { if (!running) { throw new DataAccessModuleException("DataAccessModule is not running!"); } log.debug("deref: " + iri.toString()); deref(0); } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.DataAccessModule#deref(long) */ @Override public void deref(long encodedIri) throws DataAccessModuleException { if (!running) { throw new DataAccessModuleException("DataAccessModule is not running!"); } log.debug("deref: " + Long.toString(encodedIri)); iris.add(encodedIri); } /* * (non-Javadoc) * * @see de.unikoblenz.west.koldfish.dam.LifeCycle#start() */ @Override public void start() throws Exception { if (random != null) { t = new Thread(createRandomRunnable(random)); } else { t = new Thread(createNoopRunnable()); } t.start(); running = true; log.debug("start"); } /** * creates a dummy runnable that creates random data in random time. * * @param random - random number generator for all things random. * @return a dummy runnable that creates random data in random time. */ private Runnable createRandomRunnable(Random random) { return new Runnable() { @Override public void run() { log.debug("started"); while (!t.isInterrupted() && running) { synchronized (iris) { if (!iris.isEmpty()) { try { long iri = iris.remove(0); int size = random.nextInt(100) + 30; List<long[]> data = new LinkedList<long[]>(); for (int i = 0; i < size; ++i) { data.add(new long[] {nextLong(random, Long.MAX_VALUE), nextLong(random, Long.MAX_VALUE), nextLong(random, Long.MAX_VALUE)}); } DerefResponse res = new DerefResponse() { private static final long serialVersionUID = 1L; @Override public Iterator<long[]> iterator() { return data.iterator(); } @Override public long getEncodedDerefIri() { return iri; } }; log.debug("send: " + res); // inform listeners for (DataAccessModuleListener listener : listeners) { listener.onDerefResponse(res); } Thread.sleep((random.nextInt(10) + 1) * 100); } catch (InterruptedException e) { log.debug(e); } } } } log.debug("finished"); } }; } /** * creates a no operation dummy runnable. * * @return a no operation dummy runnable. */ private Runnable createNoopRunnable() { return new Runnable() { @Override public void run() { log.debug("started"); while (!t.isInterrupted() && running) { try { Thread.sleep(1000); } catch (InterruptedException e) { log.debug(e); } } log.debug("finished"); } }; } /** * generates a random Long value within the given range 0 to n-1. * * @param rng - Random number generator. * @param n - upper boundary for the generated long. * @return a random long between 0 and n-1. */ private long nextLong(Random rng, long n) { // see also: http://stackoverflow.com/a/2546186 long bits, val; do { bits = (rng.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0L); return val; } @Override public String toString() { return "DummyDataAccessModule [running=" + running + ", mode=" + ((random != null) ? "random" : "no-op") + "]"; } @Override public void stop() throws Exception { running = false; if (t != null) { t.interrupt(); log.debug("close"); t.join(); } } /* * (non-Javadoc) * * @see * de.unikoblenz.west.koldfish.dam.DataAccessModule#addListener(de.unikoblenz.west.koldfish.dam * .DataAccessModuleListener) */ @Override public void addListener(DataAccessModuleListener listener) { listeners.add(listener); } /* * (non-Javadoc) * * @see * de.unikoblenz.west.koldfish.dam.DataAccessModule#removeListener(de.unikoblenz.west.koldfish * .dam.DataAccessModuleListener) */ @Override public void removeListener(DataAccessModuleListener listener) { listeners.remove(listener); } }
dummy now sets in generated triples the derefed encoded IRI on subject position
koldfish-dam-client/src/main/java/de/unikoblenz/west/koldfish/dam/impl/DummyDataAccessModule.java
dummy now sets in generated triples the derefed encoded IRI on subject position
<ide><path>oldfish-dam-client/src/main/java/de/unikoblenz/west/koldfish/dam/impl/DummyDataAccessModule.java <ide> List<long[]> data = new LinkedList<long[]>(); <ide> <ide> for (int i = 0; i < size; ++i) { <del> data.add(new long[] {nextLong(random, Long.MAX_VALUE), <del> nextLong(random, Long.MAX_VALUE), nextLong(random, Long.MAX_VALUE)}); <add> data.add(new long[] {iri, nextLong(random, Long.MAX_VALUE), <add> nextLong(random, Long.MAX_VALUE)}); <ide> } <ide> <ide> DerefResponse res = new DerefResponse() {
JavaScript
mit
ab9d4a4b62bc7bbc359dcf09a983f0b49618da61
0
ligoj/ligoj,ligoj/ligoj,ligoj/ligoj,ligoj/ligoj
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ define([ 'jquery', 'cascade', 'bootstrap', 'form' ], function ($, $cascade) { // Global handler for better bootstrap implicit experience $('body').popover({selector: '[data-toggle="popover"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body'}); $('body').tooltip({selector: '[data-toggle="tooltip"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body', animation: false}); var closeTooltips = function() { $('[data-toggle="tooltip"][aria-describedby]').each(function() { $(this).tooltip('hide'); }); // Destroy orphan previous tooltips $('.tooltip.in').empty().remove(); }; $(document).on('click', '.toggle-visibility', function () { $(this).toggleClass('active'); }).on('click', '.disabled,[disabled]', function (event) { event.preventDefault(); }).on('click', '[data-toggle="popover"][data-trigger="manual"]', function () { $(this).popover('toggle'); }).on('mousedown', function (e) { // Auto hide popover on click if ($('.popover.in').length && $(e.target).closest('[data-toggle="popover"],.popover').length === 0) { $('.popover.in').each(function () { $('[aria-describedby="' + $(this).attr('id') + '"]').popover('hide'); }); } }).on('show.bs.tooltip', null, function() { // Close nicely previous tooltips when a new one is displayed closeTooltips(); }).on('show.bs.dropdown', null, function(e) { // Close previous dropdowns $('.dropdown-menu.detached').closeDropdown(); // Handle the dropdown inside an absolute/overflow-hidden container, move the dropdown to body var $trigger = $(e.relatedTarget); if (!$trigger.hasClass('detached') && $trigger.closest('.dropdown-overflow').length && $trigger.closest('.dropdown').length) { var flag = 'dropdown-' + Math.random(); var $dropdown = $trigger.closest('.dropdown'); var $menu = $dropdown.find('.dropdown-menu').addClass('detached').attr('data-previous-container',flag); $trigger.addClass('detached').attr('data-dropdown-container',flag); $('body').append($menu.css({ position: 'absolute', display: 'initial', left: $menu.offset().left + 'px', width : $menu.width() + 'px', top: ($menu.offset().top + $(e.target).outerHeight()) + 'px' }).data('open', true).detach()); } }).on('hidden.bs.dropdown', null, function(e) { var $trigger = $(e.relatedTarget); if ($trigger.hasClass('detached')) { $('[data-previous-container="' + $trigger.attr('data-dropdown-container') + '"]').closeDropdown(); } }).on('change', '.btn-file :file', function () { var $input = $(this); var label = $input.val().replace(/\\/g, '/').replace(/.*\//, ''); $input.parents('.input-group').find(':text').val(label); // FIX : #19192 -> }).off('click.bs.button.data-api', '[data-toggle^="button"]').on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target).closest('.btn').button('toggle'); if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) { // Prevent double click on radios, and the double selections (so cancellation) on checkboxes e.preventDefault(); // The target component still receive the focus if ($btn.is('input,button')) { $btn.trigger('focus'); } else { $btn.find('input:visible,button:visible').first().trigger('focus'); } } }).on('click', '.retract', function () { var $retractable = $(this).closest('.retractable'); $retractable.toggleClass('retracted').trigger('retract:' + ($retractable.hasClass('.retracted') ? 'retracted' : 'expended')); }).on('keypress', 'form:not([method]),[method="get"],form[method="GET"]', function (e) { // Some browser (like Chrome) the first submit is used (hidden or not) and receive a click if ((e.which === 13 || e.keyCode === 13) && !$(e.target).is('textarea')) { // Determines the right input var $button = $(this).find('input:visible[type=submit]:not(.disabled):not(.hide):not(.hidden):not([disabled]),button:visible[type=submit]:not(.disabled):not(.hide):not(.hidden):not([disabled])').first(); if ($button.length) { $button.trigger('click'); e.preventDefault(); return false; } } }).on('submit', 'form:not([method]),[method="get"],form[method="GET"]', function (e) { e.preventDefault(); }).on('show.bs.tab', 'a[data-toggle="tab"]', function () { // Load active partials for tab var $target = $($(this).attr('href')); if ($target.is('[data-ajax]')) { $.proxy($cascade.loadPartial, $target)(); } }) // Load active partials for collapse .on('show.bs.collapse', '.collapse[data-ajax]', $cascade.loadPartial) // Load active partials for popover .on('show.bs.popover', '[data-ajax]', $cascade.loadPartial) // Load active partials for modal .on('click.bs.modal.data-api.ajax', '[data-toggle="modal-ajax"][data-ajax]:not([cascade-loaded])', function (e) { var $link = $(this).attr('cascade-loaded','true'); $.proxy($cascade.loadPartial, $link)(function() { $link.attr('data-toggle', 'modal').trigger('click.bs.modal.data-api'); }); e.preventDefault(); }).on('show.bs.modal', '.modal', closeTooltips) .on('hide.bs.modal', '.modal', closeTooltips) .on('show.bs.modal', '.modal[data-ajax]', $cascade.loadPartial); $.fn.hideGroup = function () { $(this).closest('.form-group').addClass('hidden'); return this; }; $.fn.closeDropdown = function () { this.each(function() { var $dropdown = $(this); var flag = $dropdown.attr('data-previous-container') || $dropdown.attr('data-dropdown-container'); var $trigger = $(); var $container = $(); if (flag) { $trigger = $('[data-dropdown-container="' + flag + '"]'); $dropdown = $('[data-previous-container="' + flag + '"]'); $container = $trigger.parent(); } else if ($dropdown.is('.dropdown-menu')) { $container = $dropdown.parent(); $trigger = $container.find('[data-toggle="dropdown"]'); } else if ($dropdown.is('.dropdown')) { $container = $dropdown; $trigger = $container.find('[data-toggle="dropdown"]'); $dropdown = $container.find('.dropdown-menu'); } else if ($dropdown.is('[data-toggle="dropdown"]')) { $container = $dropdown.parent(); $trigger = $dropdown; $dropdown = $container.find('.dropdown-menu'); } if ($trigger.hasClass('detached')) { $container.removeClass('open').append($dropdown.removeClass('detached').css({ position: '', left: '', width: '', display: '', top: '' }).detach()); $trigger.removeClass('detached'); } $container.removeAttr('data-open'); $trigger.removeAttr('data-dropdown-container'); $dropdown.data('open', false).removeAttr('data-previous-container'); }); }; /** * $ shortcut to apply disabled mode. */ $.fn.disable = function () { var yes = (arguments.length === 0 || arguments[0]) && 'disabled'; $(this)[yes ? 'attr' : 'removeAttr']('disabled', 'disabled').prop('disabled', yes)[yes ? 'addClass' : 'removeClass']('disabled'); return this; }; /** * $ shortcut to apply enabled mode. */ $.fn.enable = function () { $(this).disable(!(arguments.length === 0 || arguments[0])); return this; }; $.fn.showGroup = function () { $(this).closest('.form-group').removeClass('hidden'); return this; }; $.fn.rawText = function (rawText) { // Get text mode if (typeof rawText === 'undefined') { var text = this.first().contents().filter(function () { return this.nodeType === 3; }); return text.length ? text[0].textContent || '' : ''; } // Set text this.each(function () { var text = $(this).contents().filter(function () { return this.nodeType === 3; }); if (rawText && text.length === 0) { // Create a new text node at the end $(this).append(document.createTextNode(rawText)); } else { // Replace the content of existing node text.each(function () { this.textContent = rawText; }); } }); return this; }; function selectMenu() { var selector = $(this).closest('li'); // Check there is not yet selected child if (selector.parents('.navbar,.nav-pills.nav-stacked').find('li.active').length === 0) { selector.addClass('active'); $.fn.collapse && selector.parents('.navbar').length === 0 && selector.parents('.collapse').collapse('show'); selector.parents('.dropdown').addClass('active'); } } /** * Synchronize the menu with the URL of the context url * @param {string} url Current url to synchronize with menus. */ function synchronizeMenu(url) { var patterns = []; var fragments = url.split('/'); do { patterns.push('a[href^="' + fragments.join('/').replace(/"/g, '\\"') + '"]'); fragments.pop(); } while (fragments.length); var base = _('_main').find('.navbar,.nav-pills.nav-stacked'); // Remove all highlights base.find('li.active').removeClass('active'); // Highlight tool bar menu for (var index = 0; index < patterns.length; index++) { base.find(patterns[index]).each(selectMenu); } } // Transformation $cascade.register('html', function (selector) { // Add popover feature selector.find('.tab-pane.active[data-ajax]').each($cascade.loadPartial); }); $cascade.register('hash', function (url) { $('.modal-backdrop').remove(); $('.tooltip').remove(); $('.popover').remove(); $('.dropdown-menu.detached').closeDropdown(); synchronizeMenu(url); }); /** * Full screen management : enter full screen * @param {Object} $selector Optional selector. */ $.fn.fullscreen = function() { var el = $(this)[0] || document.documentElement; // use necessary prefixed versions if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); return; } if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); return; } if (el.msRequestFullscreen) { el.msRequestFullscreen(); return; } // finally the standard version el.requestFullscreen && el.requestFullscreen(); }; /** * Exit full screen management */ $.fn.exitFullscreen = function() { // use necessary prefixed versions if (document.webkitExitFullscreen) { document.webkitCancelFullScreen(); return; } if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); return; } if (document.msExitFullscreen) { document.msExitFullscreen(); return; } // finally the standard version document.exitFullscreen && document.exitFullscreen(); }; });
app-ui/src/main/webapp/lib/bootstrap/bootstrap.mod.js
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ define([ 'jquery', 'cascade', 'bootstrap', 'form' ], function ($, $cascade) { // Global handler for better bootstrap implicit experience $('body').popover({selector: '[data-toggle="popover"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body'}); $('body').tooltip({selector: '[data-toggle="tooltip"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body', animation: false}); var closeTooltips = function() { $('[data-toggle="tooltip"][aria-describedby]').each(function() { $(this).tooltip('hide'); }); // Destroy orphan previous tooltips $('.tooltip.in').empty().remove(); }; $(document).on('click', '.toggle-visibility', function () { $(this).toggleClass('active'); }).on('click', '.disabled,[disabled]', function (event) { event.preventDefault(); }).on('click', '[data-toggle="popover"][data-trigger="manual"]', function () { $(this).popover('toggle'); }).on('mousedown', function (e) { // Auto hide popover on click if ($('.popover.in').length && $(e.target).closest('[data-toggle="popover"],.popover').length === 0) { $('.popover.in').each(function () { $('[aria-describedby="' + $(this).attr('id') + '"]').popover('hide'); }); } }).on('show.bs.tooltip', null, function() { // Close nicely previous tooltips when a new one is displayed closeTooltips(); }).on('show.bs.dropdown', null, function(e) { // Close previous dropdowns $('.dropdown-menu.detached').closeDropdown(); // Handle the dropdown inside an absolute/overflow-hidden container, move the dropdown to body var $trigger = $(e.relatedTarget); if (!$trigger.hasClass('detached') && $trigger.closest('.dropdown-overflow').length && $trigger.closest('.dropdown').length) { var flag = 'dropdown-' + Math.random(); var $dropdown = $trigger.closest('.dropdown'); var $menu = $dropdown.find('.dropdown-menu').addClass('detached').attr('data-previous-container',flag); $trigger.addClass('detached').attr('data-dropdown-container',flag); $('body').append($menu.css({ position: 'absolute', display: 'initial', left: $menu.offset().left + 'px', width : $menu.width() + 'px', top: ($menu.offset().top + $(e.target).outerHeight()) + 'px' }).data('open', true).detach()); } }).on('hidden.bs.dropdown', null, function(e) { var $trigger = $(e.relatedTarget); if ($trigger.hasClass('detached')) { $('[data-previous-container="' + $trigger.attr('data-dropdown-container') + '"]').closeDropdown(); } }).on('change', '.btn-file :file', function () { var $input = $(this); var label = $input.val().replace(/\\/g, '/').replace(/.*\//, ''); $input.parents('.input-group').find(':text').val(label); // FIX : #19192 -> }).off('click.bs.button.data-api', '[data-toggle^="button"]').on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target).closest('.btn').button('toggle'); if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) { // Prevent double click on radios, and the double selections (so cancellation) on checkboxes e.preventDefault(); // The target component still receive the focus if ($btn.is('input,button')) { $btn.trigger('focus'); } else { $btn.find('input:visible,button:visible').first().trigger('focus'); } } }).on('click', '.retract', function () { $(this).closest('.retractable').toggleClass('retracted'); }).on('keypress', 'form:not([method]),[method="get"],form[method="GET"]', function (e) { // Some browser (like Chrome) the first submit is used (hidden or not) and receive a click if ((e.which === 13 || e.keyCode === 13) && !$(e.target).is('textarea')) { // Determines the right input var $button = $(this).find('input:visible[type=submit]:not(.disabled):not(.hide):not(.hidden):not([disabled]),button:visible[type=submit]:not(.disabled):not(.hide):not(.hidden):not([disabled])').first(); if ($button.length) { $button.trigger('click'); e.preventDefault(); return false; } } }).on('submit', 'form:not([method]),[method="get"],form[method="GET"]', function (e) { e.preventDefault(); }).on('show.bs.tab', 'a[data-toggle="tab"]', function () { // Load active partials for tab var $target = $($(this).attr('href')); if ($target.is('[data-ajax]')) { $.proxy($cascade.loadPartial, $target)(); } }) // Load active partials for collapse .on('show.bs.collapse', '.collapse[data-ajax]', $cascade.loadPartial) // Load active partials for popover .on('show.bs.popover', '[data-ajax]', $cascade.loadPartial) // Load active partials for modal .on('click.bs.modal.data-api.ajax', '[data-toggle="modal-ajax"][data-ajax]:not([cascade-loaded])', function (e) { var $link = $(this).attr('cascade-loaded','true'); $.proxy($cascade.loadPartial, $link)(function() { $link.attr('data-toggle', 'modal').trigger('click.bs.modal.data-api'); }); e.preventDefault(); }).on('show.bs.modal', '.modal', closeTooltips) .on('hide.bs.modal', '.modal', closeTooltips) .on('show.bs.modal', '.modal[data-ajax]', $cascade.loadPartial); $.fn.hideGroup = function () { $(this).closest('.form-group').addClass('hidden'); return this; }; $.fn.closeDropdown = function () { this.each(function() { var $dropdown = $(this); var flag = $dropdown.attr('data-previous-container') || $dropdown.attr('data-dropdown-container'); var $trigger = $(); var $container = $(); if (flag) { $trigger = $('[data-dropdown-container="' + flag + '"]'); $dropdown = $('[data-previous-container="' + flag + '"]'); $container = $trigger.parent(); } else if ($dropdown.is('.dropdown-menu')) { $container = $dropdown.parent(); $trigger = $container.find('[data-toggle="dropdown"]'); } else if ($dropdown.is('.dropdown')) { $container = $dropdown; $trigger = $container.find('[data-toggle="dropdown"]'); $dropdown = $container.find('.dropdown-menu'); } else if ($dropdown.is('[data-toggle="dropdown"]')) { $container = $dropdown.parent(); $trigger = $dropdown; $dropdown = $container.find('.dropdown-menu'); } if ($trigger.hasClass('detached')) { $container.removeClass('open').append($dropdown.removeClass('detached').css({ position: '', left: '', width: '', display: '', top: '' }).detach()); $trigger.removeClass('detached'); } $container.removeAttr('data-open'); $trigger.removeAttr('data-dropdown-container'); $dropdown.data('open', false).removeAttr('data-previous-container'); }); }; /** * $ shortcut to apply disabled mode. */ $.fn.disable = function () { var yes = (arguments.length === 0 || arguments[0]) && 'disabled'; $(this)[yes ? 'attr' : 'removeAttr']('disabled', 'disabled').prop('disabled', yes)[yes ? 'addClass' : 'removeClass']('disabled'); return this; }; /** * $ shortcut to apply enabled mode. */ $.fn.enable = function () { $(this).disable(!(arguments.length === 0 || arguments[0])); return this; }; $.fn.showGroup = function () { $(this).closest('.form-group').removeClass('hidden'); return this; }; $.fn.rawText = function (rawText) { // Get text mode if (typeof rawText === 'undefined') { var text = this.first().contents().filter(function () { return this.nodeType === 3; }); return text.length ? text[0].textContent || '' : ''; } // Set text this.each(function () { var text = $(this).contents().filter(function () { return this.nodeType === 3; }); if (rawText && text.length === 0) { // Create a new text node at the end $(this).append(document.createTextNode(rawText)); } else { // Replace the content of existing node text.each(function () { this.textContent = rawText; }); } }); return this; }; function selectMenu() { var selector = $(this).closest('li'); // Check there is not yet selected child if (selector.parents('.navbar,.nav-pills.nav-stacked').find('li.active').length === 0) { selector.addClass('active'); $.fn.collapse && selector.parents('.navbar').length === 0 && selector.parents('.collapse').collapse('show'); selector.parents('.dropdown').addClass('active'); } } /** * Synchronize the menu with the URL of the context url * @param {string} url Current url to synchronize with menus. */ function synchronizeMenu(url) { var patterns = []; var fragments = url.split('/'); do { patterns.push('a[href^="' + fragments.join('/').replace(/"/g, '\\"') + '"]'); fragments.pop(); } while (fragments.length); var base = _('_main').find('.navbar,.nav-pills.nav-stacked'); // Remove all highlights base.find('li.active').removeClass('active'); // Highlight tool bar menu for (var index = 0; index < patterns.length; index++) { base.find(patterns[index]).each(selectMenu); } } // Transformation $cascade.register('html', function (selector) { // Add popover feature selector.find('.tab-pane.active[data-ajax]').each($cascade.loadPartial); }); $cascade.register('hash', function (url) { $('.modal-backdrop').remove(); $('.tooltip').remove(); $('.popover').remove(); $('.dropdown-menu.detached').closeDropdown(); synchronizeMenu(url); }); /** * Full screen management : enter full screen * @param {Object} $selector Optional selector. */ $.fn.fullscreen = function() { var el = $(this)[0] || document.documentElement; // use necessary prefixed versions if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); return; } if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); return; } if (el.msRequestFullscreen) { el.msRequestFullscreen(); return; } // finally the standard version el.requestFullscreen && el.requestFullscreen(); }; /** * Exit full screen management */ $.fn.exitFullscreen = function() { // use necessary prefixed versions if (document.webkitExitFullscreen) { document.webkitCancelFullScreen(); return; } if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); return; } if (document.msExitFullscreen) { document.msExitFullscreen(); return; } // finally the standard version document.exitFullscreen && document.exitFullscreen(); }; });
Fix ligoj/ligoj#35 Using retracting panel does not reorder tiles
app-ui/src/main/webapp/lib/bootstrap/bootstrap.mod.js
Fix ligoj/ligoj#35 Using retracting panel does not reorder tiles
<ide><path>pp-ui/src/main/webapp/lib/bootstrap/bootstrap.mod.js <ide> } <ide> } <ide> }).on('click', '.retract', function () { <del> $(this).closest('.retractable').toggleClass('retracted'); <add> var $retractable = $(this).closest('.retractable'); <add> $retractable.toggleClass('retracted').trigger('retract:' + ($retractable.hasClass('.retracted') ? 'retracted' : 'expended')); <ide> }).on('keypress', 'form:not([method]),[method="get"],form[method="GET"]', function (e) { <ide> // Some browser (like Chrome) the first submit is used (hidden or not) and receive a click <ide> if ((e.which === 13 || e.keyCode === 13) && !$(e.target).is('textarea')) {
Java
apache-2.0
d37fc1e52913c4ca26671216e53c24f618ebd3ed
0
zpao/buck,JoelMarcey/buck,rmaz/buck,romanoid/buck,LegNeato/buck,SeleniumHQ/buck,shs96c/buck,facebook/buck,romanoid/buck,SeleniumHQ/buck,facebook/buck,romanoid/buck,JoelMarcey/buck,JoelMarcey/buck,brettwooldridge/buck,brettwooldridge/buck,brettwooldridge/buck,brettwooldridge/buck,SeleniumHQ/buck,SeleniumHQ/buck,LegNeato/buck,zpao/buck,romanoid/buck,rmaz/buck,JoelMarcey/buck,LegNeato/buck,brettwooldridge/buck,rmaz/buck,kageiit/buck,nguyentruongtho/buck,Addepar/buck,rmaz/buck,shs96c/buck,romanoid/buck,brettwooldridge/buck,brettwooldridge/buck,kageiit/buck,kageiit/buck,shs96c/buck,JoelMarcey/buck,SeleniumHQ/buck,shs96c/buck,shs96c/buck,shs96c/buck,LegNeato/buck,SeleniumHQ/buck,facebook/buck,Addepar/buck,rmaz/buck,shs96c/buck,Addepar/buck,rmaz/buck,JoelMarcey/buck,Addepar/buck,rmaz/buck,rmaz/buck,brettwooldridge/buck,SeleniumHQ/buck,nguyentruongtho/buck,rmaz/buck,LegNeato/buck,Addepar/buck,facebook/buck,LegNeato/buck,LegNeato/buck,LegNeato/buck,kageiit/buck,kageiit/buck,SeleniumHQ/buck,romanoid/buck,JoelMarcey/buck,JoelMarcey/buck,facebook/buck,brettwooldridge/buck,SeleniumHQ/buck,facebook/buck,Addepar/buck,facebook/buck,Addepar/buck,nguyentruongtho/buck,JoelMarcey/buck,romanoid/buck,JoelMarcey/buck,rmaz/buck,LegNeato/buck,brettwooldridge/buck,brettwooldridge/buck,SeleniumHQ/buck,romanoid/buck,LegNeato/buck,zpao/buck,JoelMarcey/buck,rmaz/buck,nguyentruongtho/buck,Addepar/buck,Addepar/buck,LegNeato/buck,zpao/buck,brettwooldridge/buck,LegNeato/buck,romanoid/buck,Addepar/buck,brettwooldridge/buck,LegNeato/buck,zpao/buck,nguyentruongtho/buck,zpao/buck,shs96c/buck,shs96c/buck,nguyentruongtho/buck,shs96c/buck,SeleniumHQ/buck,Addepar/buck,JoelMarcey/buck,kageiit/buck,kageiit/buck,romanoid/buck,rmaz/buck,nguyentruongtho/buck,zpao/buck,shs96c/buck,shs96c/buck,JoelMarcey/buck,romanoid/buck,Addepar/buck,SeleniumHQ/buck,Addepar/buck,SeleniumHQ/buck,rmaz/buck,romanoid/buck,romanoid/buck,shs96c/buck
/* * Copyright 2012-present Facebook, 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.facebook.buck.config; import static java.lang.Integer.parseInt; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.parser.BuildTargetParseException; import com.facebook.buck.parser.BuildTargetParser; import com.facebook.buck.parser.BuildTargetPatternParser; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.DefaultBuildTargetSourcePath; import com.facebook.buck.rules.PathSourcePath; import com.facebook.buck.rules.RuleKeyDiagnosticsMode; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.util.Ansi; import com.facebook.buck.util.AnsiEnvironmentChecking; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.PatternAndMessage; import com.facebook.buck.util.cache.FileHashCacheMode; import com.facebook.buck.util.config.Config; import com.facebook.buck.util.environment.Architecture; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.network.hostname.HostnameFetching; import com.facebook.infer.annotation.PropagatesNullable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import java.io.IOException; import java.net.URI; import java.nio.file.Path; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; /** Structured representation of data read from a {@code .buckconfig} file. */ public class BuckConfig implements ConfigPathGetter { private static final String ALIAS_SECTION_HEADER = "alias"; private static final String TEST_SECTION_HEADER = "test"; private static final Float DEFAULT_THREAD_CORE_RATIO = Float.valueOf(1.0F); /** * This pattern is designed so that a fully-qualified build target cannot be a valid alias name * and vice-versa. */ private static final Pattern ALIAS_PATTERN = Pattern.compile("[a-zA-Z_-][a-zA-Z0-9_-]*"); private static final ImmutableMap<String, ImmutableSet<String>> IGNORE_FIELDS_FOR_DAEMON_RESTART; private final CellPathResolver cellPathResolver; private final Architecture architecture; private final Config config; private final ImmutableSetMultimap<String, BuildTarget> aliasToBuildTargetMap; private final ProjectFilesystem projectFilesystem; private final Platform platform; private final ImmutableMap<String, String> environment; private final ConfigViewCache<BuckConfig> viewCache = new ConfigViewCache<>(this); static { ImmutableMap.Builder<String, ImmutableSet<String>> ignoreFieldsForDaemonRestartBuilder = ImmutableMap.builder(); ignoreFieldsForDaemonRestartBuilder.put( "apple", ImmutableSet.of("generate_header_symlink_tree_only")); ignoreFieldsForDaemonRestartBuilder.put("build", ImmutableSet.of("threads")); ignoreFieldsForDaemonRestartBuilder.put( "cache", ImmutableSet.of("dir", "dir_mode", "http_mode", "http_url", "mode", "slb_server_pool")); ignoreFieldsForDaemonRestartBuilder.put( "client", ImmutableSet.of("id", "skip-action-graph-cache")); ignoreFieldsForDaemonRestartBuilder.put( "log", ImmutableSet.of( "chrome_trace_generation", "compress_traces", "max_traces", "public_announcements")); ignoreFieldsForDaemonRestartBuilder.put("project", ImmutableSet.of("ide_prompt")); ignoreFieldsForDaemonRestartBuilder.put("ui", ImmutableSet.of("superconsole")); ignoreFieldsForDaemonRestartBuilder.put("color", ImmutableSet.of("ui")); IGNORE_FIELDS_FOR_DAEMON_RESTART = ignoreFieldsForDaemonRestartBuilder.build(); } public BuckConfig( Config config, ProjectFilesystem projectFilesystem, Architecture architecture, Platform platform, ImmutableMap<String, String> environment, CellPathResolver cellPathResolver) { this.cellPathResolver = cellPathResolver; this.config = config; this.projectFilesystem = projectFilesystem; this.architecture = architecture; // We could create this Map on demand; however, in practice, it is almost always needed when // BuckConfig is needed because CommandLineBuildTargetNormalizer needs it. this.aliasToBuildTargetMap = createAliasToBuildTargetMap(this.getEntriesForSection(ALIAS_SECTION_HEADER)); this.platform = platform; this.environment = environment; } /** Returns a clone of the current config with a the argument CellPathResolver. */ public BuckConfig withCellPathResolver(CellPathResolver resolver) { return new BuckConfig(config, projectFilesystem, architecture, platform, environment, resolver); } /** * Get a {@link ConfigView} of this config. * * @param cls Class of the config view. * @param <T> Type of the config view. */ public <T extends ConfigView<BuckConfig>> T getView(Class<T> cls) { return viewCache.getView(cls); } /** * @return whether {@code aliasName} conforms to the pattern for a valid alias name. This does not * indicate whether it is an alias that maps to a build target in a BuckConfig. */ private static boolean isValidAliasName(String aliasName) { return ALIAS_PATTERN.matcher(aliasName).matches(); } public static void validateAliasName(String aliasName) throws HumanReadableException { validateAgainstAlias(aliasName, "Alias"); } public static void validateLabelName(String aliasName) throws HumanReadableException { validateAgainstAlias(aliasName, "Label"); } private static void validateAgainstAlias(String aliasName, String fieldName) { if (isValidAliasName(aliasName)) { return; } if (aliasName.isEmpty()) { throw new HumanReadableException("%s cannot be the empty string.", fieldName); } throw new HumanReadableException("Not a valid %s: %s.", fieldName.toLowerCase(), aliasName); } public Architecture getArchitecture() { return architecture; } public ImmutableMap<String, String> getEntriesForSection(String section) { ImmutableMap<String, String> entries = config.get(section); if (entries != null) { return entries; } else { return ImmutableMap.of(); } } public ImmutableList<String> getMessageOfTheDay() { return getListWithoutComments("project", "motd"); } public ImmutableList<String> getListWithoutComments(String section, String field) { return config.getListWithoutComments(section, field); } public ImmutableList<String> getListWithoutComments( String section, String field, char splitChar) { return config.getListWithoutComments(section, field, splitChar); } public CellPathResolver getCellPathResolver() { return cellPathResolver; } public Optional<ImmutableList<String>> getOptionalListWithoutComments( String section, String field) { return config.getOptionalListWithoutComments(section, field); } public Optional<ImmutableList<String>> getOptionalListWithoutComments( String section, String field, char splitChar) { return config.getOptionalListWithoutComments(section, field, splitChar); } public Optional<ImmutableList<Path>> getOptionalPathList( String section, String field, boolean resolve) { Optional<ImmutableList<String>> rawPaths = config.getOptionalListWithoutComments(section, field); if (rawPaths.isPresent()) { ImmutableList<Path> paths = rawPaths .get() .stream() .map( input -> convertPath( input, resolve, String.format( "Error in %s.%s: Cell-relative path not found: ", section, field))) .collect(ImmutableList.toImmutableList()); return Optional.of(paths); } return Optional.empty(); } public ImmutableSet<String> getBuildTargetForAliasAsString(String possiblyFlavoredAlias) { String[] parts = possiblyFlavoredAlias.split("#", 2); String unflavoredAlias = parts[0]; ImmutableSet<BuildTarget> buildTargets = getBuildTargetsForAlias(unflavoredAlias); if (buildTargets.isEmpty()) { return ImmutableSet.of(); } String suffix = parts.length == 2 ? "#" + parts[1] : ""; return buildTargets .stream() .map(buildTarget -> buildTarget.getFullyQualifiedName() + suffix) .collect(ImmutableSet.toImmutableSet()); } public ImmutableSet<BuildTarget> getBuildTargetsForAlias(String unflavoredAlias) { return aliasToBuildTargetMap.get(unflavoredAlias); } public BuildTarget getBuildTargetForFullyQualifiedTarget(String target) { return BuildTargetParser.INSTANCE.parse( target, BuildTargetPatternParser.fullyQualified(), getCellPathResolver()); } public ImmutableList<BuildTarget> getBuildTargetList(String section, String key) { ImmutableList<String> targetsToForce = getListWithoutComments(section, key); if (targetsToForce.size() == 0) { return ImmutableList.of(); } ImmutableList.Builder<BuildTarget> targets = new ImmutableList.Builder<>(); for (String targetOrAlias : targetsToForce) { Set<String> expandedAlias = getBuildTargetForAliasAsString(targetOrAlias); if (expandedAlias.isEmpty()) { targets.add(getBuildTargetForFullyQualifiedTarget(targetOrAlias)); } else { for (String target : expandedAlias) { targets.add(getBuildTargetForFullyQualifiedTarget(target)); } } } return targets.build(); } /** @return the parsed BuildTarget in the given section and field, if set. */ public Optional<BuildTarget> getBuildTarget(String section, String field) { Optional<String> target = getValue(section, field); return target.isPresent() ? Optional.of(getBuildTargetForFullyQualifiedTarget(target.get())) : Optional.empty(); } /** * @return the parsed BuildTarget in the given section and field, if set and a valid build target. * <p>This is useful if you use getTool to get the target, if any, but allow filesystem * references. */ public Optional<BuildTarget> getMaybeBuildTarget(String section, String field) { Optional<String> value = getValue(section, field); if (!value.isPresent()) { return Optional.empty(); } try { return Optional.of(getBuildTargetForFullyQualifiedTarget(value.get())); } catch (BuildTargetParseException e) { return Optional.empty(); } } /** @return the parsed BuildTarget in the given section and field. */ public BuildTarget getRequiredBuildTarget(String section, String field) { Optional<BuildTarget> target = getBuildTarget(section, field); return getOrThrow(section, field, target); } public <T extends Enum<T>> Optional<T> getEnum(String section, String field, Class<T> clazz) { return config.getEnum(section, field, clazz); } /** * @return a {@link SourcePath} identified by a @{link BuildTarget} or {@link Path} reference by * the given section:field, if set. */ public Optional<SourcePath> getSourcePath(String section, String field) { Optional<String> value = getValue(section, field); if (!value.isPresent()) { return Optional.empty(); } try { BuildTarget target = getBuildTargetForFullyQualifiedTarget(value.get()); return Optional.of(DefaultBuildTargetSourcePath.of(target)); } catch (BuildTargetParseException e) { return Optional.of( PathSourcePath.of( projectFilesystem, checkPathExists( value.get(), String.format("Overridden %s:%s path not found: ", section, field)))); } } /** @return a {@link SourcePath} identified by a {@link Path}. */ public PathSourcePath getPathSourcePath(@PropagatesNullable Path path) { if (path == null) { return null; } if (path.isAbsolute()) { return PathSourcePath.of(projectFilesystem, path); } return PathSourcePath.of( projectFilesystem, checkPathExists( path.toString(), "Failed to transform Path to SourcePath, path not found: ")); } /** * In a {@link BuckConfig}, an alias can either refer to a fully-qualified build target, or an * alias defined earlier in the {@code alias} section. The mapping produced by this method * reflects the result of resolving all aliases as values in the {@code alias} section. */ private ImmutableSetMultimap<String, BuildTarget> createAliasToBuildTargetMap( ImmutableMap<String, String> rawAliasMap) { // We use a LinkedHashMap rather than an ImmutableMap.Builder because we want both (1) order to // be preserved, and (2) the ability to inspect the Map while building it up. SetMultimap<String, BuildTarget> aliasToBuildTarget = LinkedHashMultimap.create(); for (Map.Entry<String, String> aliasEntry : rawAliasMap.entrySet()) { String alias = aliasEntry.getKey(); validateAliasName(alias); // Determine whether the mapping is to a build target or to an alias. List<String> values = Splitter.on(' ').splitToList(aliasEntry.getValue()); for (String value : values) { Set<BuildTarget> buildTargets; if (isValidAliasName(value)) { buildTargets = aliasToBuildTarget.get(value); if (buildTargets.isEmpty()) { throw new HumanReadableException("No alias for: %s.", value); } } else if (value.isEmpty()) { continue; } else { // Here we parse the alias values with a BuildTargetParser to be strict. We could be // looser and just grab everything between "//" and ":" and assume it's a valid base path. buildTargets = ImmutableSet.of( BuildTargetParser.INSTANCE.parse( value, BuildTargetPatternParser.fullyQualified(), getCellPathResolver())); } aliasToBuildTarget.putAll(alias, buildTargets); } } return ImmutableSetMultimap.copyOf(aliasToBuildTarget); } /** * Create a map of {@link BuildTarget} base paths to aliases. Note that there may be more than one * alias to a base path, so the first one listed in the .buckconfig will be chosen. */ public ImmutableMap<Path, String> getBasePathToAliasMap() { ImmutableMap<String, String> aliases = config.get(ALIAS_SECTION_HEADER); if (aliases == null) { return ImmutableMap.of(); } // Build up the Map with an ordinary HashMap because we need to be able to check whether the Map // already contains the key before inserting. Map<Path, String> basePathToAlias = new HashMap<>(); for (Map.Entry<String, BuildTarget> entry : aliasToBuildTargetMap.entries()) { String alias = entry.getKey(); BuildTarget buildTarget = entry.getValue(); Path basePath = buildTarget.getBasePath(); if (!basePathToAlias.containsKey(basePath)) { basePathToAlias.put(basePath, alias); } } return ImmutableMap.copyOf(basePathToAlias); } public ImmutableMultimap<String, BuildTarget> getAliases() { return this.aliasToBuildTargetMap; } public long getDefaultTestTimeoutMillis() { return Long.parseLong(getValue("test", "timeout").orElse("0")); } public boolean isParallelExternalTestSpecComputationEnabled() { return getBooleanValue( TEST_SECTION_HEADER, "parallel_external_test_spec_computation_enabled", false); } private static final String LOG_SECTION = "log"; public boolean isPublicAnnouncementsEnabled() { return getBooleanValue(LOG_SECTION, "public_announcements", true); } public boolean isProcessTrackerEnabled() { return getBooleanValue(LOG_SECTION, "process_tracker_enabled", true); } public boolean isProcessTrackerDeepEnabled() { return getBooleanValue(LOG_SECTION, "process_tracker_deep_enabled", false); } public boolean isRuleKeyLoggerEnabled() { return getBooleanValue(LOG_SECTION, "rule_key_logger_enabled", false); } public RuleKeyDiagnosticsMode getRuleKeyDiagnosticsMode() { return getEnum(LOG_SECTION, "rule_key_diagnostics_mode", RuleKeyDiagnosticsMode.class) .orElse(RuleKeyDiagnosticsMode.NEVER); } public boolean isMachineReadableLoggerEnabled() { return getBooleanValue(LOG_SECTION, "machine_readable_logger_enabled", true); } public boolean isBuckConfigLocalWarningEnabled() { return getBooleanValue(LOG_SECTION, "buckconfig_local_warning_enabled", false); } public ProjectTestsMode xcodeProjectTestsMode() { return getEnum("project", "xcode_project_tests_mode", ProjectTestsMode.class) .orElse(ProjectTestsMode.WITH_TESTS); } public boolean getRestartAdbOnFailure() { return Boolean.parseBoolean(getValue("adb", "adb_restart_on_failure").orElse("true")); } public ImmutableList<String> getAdbRapidInstallTypes() { return getListWithoutComments("adb", "rapid_install_types_beta"); } public boolean getMultiInstallMode() { return getBooleanValue("adb", "multi_install_mode", false); } public boolean getFlushEventsBeforeExit() { return getBooleanValue("daemon", "flush_events_before_exit", false); } public ImmutableSet<String> getListenerJars() { return ImmutableSet.copyOf(getListWithoutComments("extensions", "listeners")); } /** Return Strings so as to avoid a dependency on {@link com.facebook.buck.cli.LabelSelector}! */ public ImmutableList<String> getDefaultRawExcludedLabelSelectors() { return getListWithoutComments("test", "excluded_labels"); } /** * Create an Ansi object appropriate for the current output. First respect the user's preferences, * if set. Next, respect any default provided by the caller. (This is used by buckd to tell the * daemon about the client's terminal.) Finally, allow the Ansi class to autodetect whether the * current output is a tty. * * @param defaultColor Default value provided by the caller (e.g. the client of buckd) */ public Ansi createAnsi(Optional<String> defaultColor) { String color = getValue("color", "ui").map(Optional::of).orElse(defaultColor).orElse("auto"); switch (color) { case "false": case "never": return Ansi.withoutTty(); case "true": case "always": return Ansi.forceTty(); case "auto": default: return new Ansi( AnsiEnvironmentChecking.environmentSupportsAnsiEscapes(platform, environment)); } } public Path resolvePathThatMayBeOutsideTheProjectFilesystem(@PropagatesNullable Path path) { if (path == null) { return path; } return resolveNonNullPathOutsideTheProjectFilesystem(path); } public Path resolveNonNullPathOutsideTheProjectFilesystem(Path path) { if (path.isAbsolute()) { return getPathFromVfs(path); } Path expandedPath = MorePaths.expandHomeDir(path); return projectFilesystem.resolve(expandedPath); } public String getLocalhost() { try { return HostnameFetching.getHostname(); } catch (IOException e) { return "<unknown>"; } } public Platform getPlatform() { return platform; } public boolean isActionGraphCheckingEnabled() { return getBooleanValue("cache", "action_graph_cache_check_enabled", false); } public int getMaxActionGraphCacheEntries() { return getInteger("cache", "max_action_graph_cache_entries").orElse(1); } public IncrementalActionGraphMode getIncrementalActionGraphMode() { return getEnum("cache", "incremental_action_graph", IncrementalActionGraphMode.class) .orElse(IncrementalActionGraphMode.DEFAULT); } public Optional<String> getRepository() { return config.get("cache", "repository"); } /** * Whether Buck should use Buck binary hash or git commit id as the core key in all rule keys. * * <p>The binary hash reflects the code that can affect the content of artifacts. * * <p>By default git commit id is used as the core key. * * @return <code>True</code> if binary hash should be used as the core key */ public boolean useBuckBinaryHash() { return getBooleanValue("cache", "use_buck_binary_hash", false); } public Optional<ImmutableSet<PatternAndMessage>> getUnexpectedFlavorsMessages() { ImmutableMap<String, String> entries = config.get("unknown_flavors_messages"); if (!entries.isEmpty()) { Set<PatternAndMessage> patternAndMessages = new HashSet<>(); for (Map.Entry<String, String> entry : entries.entrySet()) { patternAndMessages.add( PatternAndMessage.of(Pattern.compile(entry.getKey()), entry.getValue())); } return Optional.of(ImmutableSet.copyOf(patternAndMessages)); } return Optional.empty(); } public boolean hasUserDefinedValue(String sectionName, String propertyName) { return config.get(sectionName).containsKey(propertyName); } public Optional<ImmutableMap<String, String>> getSection(String sectionName) { ImmutableMap<String, String> values = config.get(sectionName); return values.isEmpty() ? Optional.empty() : Optional.of(values); } /** * @return the string value for the config settings, where present empty values are {@code * Optional.empty()}. */ public Optional<String> getValue(String sectionName, String propertyName) { return config.getValue(sectionName, propertyName); } /** * @return the string value for the config settings, where present empty values are {@code * Optional[]}. */ public Optional<String> getRawValue(String sectionName, String propertyName) { return config.get(sectionName, propertyName); } public Optional<Integer> getInteger(String sectionName, String propertyName) { return config.getInteger(sectionName, propertyName); } public Optional<Long> getLong(String sectionName, String propertyName) { return config.getLong(sectionName, propertyName); } public Optional<Float> getFloat(String sectionName, String propertyName) { return config.getFloat(sectionName, propertyName); } public Optional<Boolean> getBoolean(String sectionName, String propertyName) { return config.getBoolean(sectionName, propertyName); } public boolean getBooleanValue(String sectionName, String propertyName, boolean defaultValue) { return config.getBooleanValue(sectionName, propertyName, defaultValue); } public Optional<URI> getUrl(String section, String field) { return config.getUrl(section, field); } public ImmutableMap<String, String> getMap(String section, String field) { return config.getMap(section, field); } public <T> T getOrThrow(String section, String field, Optional<T> value) { if (!value.isPresent()) { throw new HumanReadableException( String.format(".buckconfig: %s:%s must be set", section, field)); } return value.get(); } // This is a hack. A cleaner approach would be to expose a narrow view of the config to any code // that affects the state cached by the Daemon. public boolean equalsForDaemonRestart(BuckConfig other) { return this.config.equalsIgnoring(other.config, IGNORE_FIELDS_FOR_DAEMON_RESTART); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (!(obj instanceof BuckConfig)) { return false; } BuckConfig that = (BuckConfig) obj; return Objects.equal(this.config, that.config); } @Override public String toString() { return String.format("%s (config=%s)", super.toString(), config); } @Override public int hashCode() { return Objects.hashCode(config); } public ImmutableMap<String, String> getEnvironment() { return environment; } public String[] getEnv(String propertyName, String separator) { String value = getEnvironment().get(propertyName); if (value == null) { value = ""; } return value.split(separator); } /** @return the local cache directory */ public String getLocalCacheDirectory(String dirCacheName) { return getValue(dirCacheName, "dir") .orElse(projectFilesystem.getBuckPaths().getCacheDir().toString()); } public int getKeySeed() { return parseInt(getValue("cache", "key_seed").orElse("0")); } /** @return the path for the given section and property. */ @Override public Optional<Path> getPath(String sectionName, String name) { return getPath(sectionName, name, true); } public Path getRequiredPath(String section, String field) { Optional<Path> path = getPath(section, field); return getOrThrow(section, field, path); } public String getClientId() { return getValue("client", "id").orElse("buck"); } /** * @return whether the current invocation of Buck should skip the Action Graph cache, leaving the * cached Action Graph in memory for the next request and creating a fresh Action Graph for * the current request (which will be garbage-collected when the current request is complete). * Commonly, a one-off request, like from a linter, will specify this option so that it does * not invalidate the primary in-memory Action Graph that the user is likely relying on for * fast iterative builds. */ public boolean isSkipActionGraphCache() { return getBooleanValue("client", "skip-action-graph-cache", false); } /** @return the number of threads Buck should use. */ public int getNumThreads() { return getNumThreads(getDefaultMaximumNumberOfThreads()); } /** * @return the number of threads Buck should use for testing. This will use the build * parallelization settings if not configured. */ public int getNumTestThreads() { double ratio = config.getFloat(TEST_SECTION_HEADER, "thread_utilization_ratio").orElse(1.0F); if (ratio <= 0.0F) { throw new HumanReadableException( "thread_utilization_ratio must be greater than zero (was " + ratio + ")"); } return (int) Math.ceil(ratio * getNumThreads()); } /** @return the number of threads to be used for the scheduled executor thread pool. */ public int getNumThreadsForSchedulerPool() { return config.getLong("build", "scheduler_threads").orElse((long) 2).intValue(); } /** @return the maximum size of files input based rule keys will be willing to hash. */ public long getBuildInputRuleKeyFileSizeLimit() { return config.getLong("build", "input_rule_key_file_size_limit").orElse(Long.MAX_VALUE); } public int getDefaultMaximumNumberOfThreads() { return getDefaultMaximumNumberOfThreads(Runtime.getRuntime().availableProcessors()); } @VisibleForTesting int getDefaultMaximumNumberOfThreads(int detectedProcessorCount) { double ratio = config.getFloat("build", "thread_core_ratio").orElse(DEFAULT_THREAD_CORE_RATIO); if (ratio <= 0.0F) { throw new HumanReadableException( "thread_core_ratio must be greater than zero (was " + ratio + ")"); } int scaledValue = (int) Math.ceil(ratio * detectedProcessorCount); int threadLimit = detectedProcessorCount; Optional<Long> reservedCores = getNumberOfReservedCores(); if (reservedCores.isPresent()) { threadLimit -= reservedCores.get(); } if (scaledValue > threadLimit) { scaledValue = threadLimit; } Optional<Long> minThreads = getThreadCoreRatioMinThreads(); if (minThreads.isPresent()) { scaledValue = Math.max(scaledValue, minThreads.get().intValue()); } Optional<Long> maxThreads = getThreadCoreRatioMaxThreads(); if (maxThreads.isPresent()) { long maxThreadsValue = maxThreads.get(); if (minThreads.isPresent() && minThreads.get() > maxThreadsValue) { throw new HumanReadableException( "thread_core_ratio_max_cores must be larger than thread_core_ratio_min_cores"); } if (maxThreadsValue > threadLimit) { throw new HumanReadableException( "thread_core_ratio_max_cores is larger than thread_core_ratio_reserved_cores allows"); } scaledValue = Math.min(scaledValue, (int) maxThreadsValue); } if (scaledValue <= 0) { throw new HumanReadableException( "Configuration resulted in an invalid number of build threads (" + scaledValue + ")."); } return scaledValue; } private Optional<Long> getNumberOfReservedCores() { Optional<Long> reservedCores = config.getLong("build", "thread_core_ratio_reserved_cores"); if (reservedCores.isPresent() && reservedCores.get() < 0) { throw new HumanReadableException("thread_core_ratio_reserved_cores must be larger than zero"); } return reservedCores; } private Optional<Long> getThreadCoreRatioMaxThreads() { Optional<Long> maxThreads = config.getLong("build", "thread_core_ratio_max_threads"); if (maxThreads.isPresent() && maxThreads.get() < 0) { throw new HumanReadableException("thread_core_ratio_max_threads must be larger than zero"); } return maxThreads; } private Optional<Long> getThreadCoreRatioMinThreads() { Optional<Long> minThreads = config.getLong("build", "thread_core_ratio_min_threads"); if (minThreads.isPresent() && minThreads.get() <= 0) { throw new HumanReadableException("thread_core_ratio_min_threads must be larger than zero"); } return minThreads; } /** * @return the number of threads Buck should use or the specified defaultValue if it is not set. */ public int getNumThreads(int defaultValue) { return config.getLong("build", "threads").orElse((long) defaultValue).intValue(); } public Optional<ImmutableList<String>> getAllowedJavaSpecificationVersions() { return getOptionalListWithoutComments("project", "allowed_java_specification_versions"); } public long getCountersFirstFlushIntervalMillis() { return config.getLong("counters", "first_flush_interval_millis").orElse(5000L); } public long getCountersFlushIntervalMillis() { return config.getLong("counters", "flush_interval_millis").orElse(30000L); } public Optional<Path> getPath(String sectionName, String name, boolean isCellRootRelative) { Optional<String> pathString = getValue(sectionName, name); return pathString.isPresent() ? Optional.of( convertPathWithError( pathString.get(), isCellRootRelative, String.format("Overridden %s:%s path not found: ", sectionName, name))) : Optional.empty(); } /** * Return a {@link Path} from the underlying {@link java.nio.file.FileSystem} implementation. This * allows to safely call {@link Path#resolve(Path)} and similar calls without exceptions caused by * mis-matched underlying filesystem implementations causing grief. This is particularly useful * for those times where we're using (eg) JimFs for our testing. */ private Path getPathFromVfs(String path) { return projectFilesystem.getPath(path); } private Path getPathFromVfs(Path path) { return projectFilesystem.getPath(path.toString()); } private Path convertPathWithError(String pathString, boolean isCellRootRelative, String error) { return isCellRootRelative ? checkPathExistsAndResolve(pathString, error) : getPathFromVfs(pathString); } private Path convertPath(String pathString, boolean resolve, String error) { return resolve ? checkPathExistsAndResolve(pathString, error) : checkPathExists(pathString, error); } public Path checkPathExistsAndResolve(String pathString, String errorMsg) { return projectFilesystem.getPathForRelativePath(checkPathExists(pathString, errorMsg)); } private Path checkPathExists(String pathString, String errorMsg) { Path path = getPathFromVfs(pathString); if (projectFilesystem.exists(path)) { return path; } throw new HumanReadableException(errorMsg + path); } public ImmutableSet<String> getSections() { return config.getSectionToEntries().keySet(); } public ImmutableMap<String, ImmutableMap<String, String>> getRawConfigForParser() { ImmutableMap<String, ImmutableMap<String, String>> rawSections = config.getSectionToEntries(); // If the raw config doesn't have sections which have ignored fields, then just return it as-is. ImmutableSet<String> sectionsWithIgnoredFields = IGNORE_FIELDS_FOR_DAEMON_RESTART.keySet(); if (Sets.intersection(rawSections.keySet(), sectionsWithIgnoredFields).isEmpty()) { return rawSections; } // Otherwise, iterate through the config to do finer-grain filtering. ImmutableMap.Builder<String, ImmutableMap<String, String>> filtered = ImmutableMap.builder(); for (Map.Entry<String, ImmutableMap<String, String>> sectionEnt : rawSections.entrySet()) { String sectionName = sectionEnt.getKey(); // If this section doesn't have a corresponding ignored section, then just add it as-is. if (!sectionsWithIgnoredFields.contains(sectionName)) { filtered.put(sectionEnt); continue; } // If none of this section's entries are ignored, then add it as-is. ImmutableMap<String, String> fields = sectionEnt.getValue(); ImmutableSet<String> ignoredFieldNames = IGNORE_FIELDS_FOR_DAEMON_RESTART.getOrDefault(sectionName, ImmutableSet.of()); if (Sets.intersection(fields.keySet(), ignoredFieldNames).isEmpty()) { filtered.put(sectionEnt); continue; } // Otherwise, filter out the ignored fields. ImmutableMap<String, String> remainingKeys = ImmutableMap.copyOf(Maps.filterKeys(fields, Predicates.not(ignoredFieldNames::contains))); if (!remainingKeys.isEmpty()) { filtered.put(sectionName, remainingKeys); } } return filtered.build(); } public Optional<ImmutableList<String>> getExternalTestRunner() { Optional<String> value = getValue("test", "external_runner"); if (!value.isPresent()) { return Optional.empty(); } return Optional.of(ImmutableList.copyOf(Splitter.on(' ').splitToList(value.get()))); } /** * @return whether to symlink the default output location (`buck-out`) to the user-provided * override for compatibility. */ public boolean getBuckOutCompatLink() { return getBooleanValue("project", "buck_out_compat_link", false); } /** @return whether to enabled versions on build/test command. */ public boolean getBuildVersions() { return getBooleanValue("build", "versions", false); } /** @return whether to enabled versions on targets command. */ public boolean getTargetsVersions() { return getBooleanValue("targets", "versions", false); } /** @return whether to enable caching of rule key calculations between builds. */ public boolean getRuleKeyCaching() { return getBooleanValue("build", "rule_key_caching", false); } public ImmutableList<String> getCleanAdditionalPaths() { return getListWithoutComments("clean", "additional_paths"); } public ImmutableList<String> getCleanExcludedCaches() { return getListWithoutComments("clean", "excluded_dir_caches"); } /** @return whether to enable new file hash cache engine. */ public FileHashCacheMode getFileHashCacheMode() { return getEnum("build", "file_hash_cache_mode", FileHashCacheMode.class) .orElse(FileHashCacheMode.DEFAULT); } /** Whether to parallelize action graph creation. */ public ActionGraphParallelizationMode getActionGraphParallelizationMode() { return getEnum("build", "action_graph_parallelization", ActionGraphParallelizationMode.class) .orElse(ActionGraphParallelizationMode.DEFAULT); } public Config getConfig() { return config; } public boolean isLogBuildIdToConsoleEnabled() { return getBooleanValue("log", "log_build_id_to_console_enabled", false); } /** Whether to create symlinks of build output in buck-out/last. */ public boolean createBuildOutputSymLinksEnabled() { return getBooleanValue("build", "create_build_output_symlinks_enabled", false); } public boolean isEmbeddedCellBuckOutEnabled() { return getBooleanValue("project", "embedded_cell_buck_out_enabled", false); } /** Whether to instrument the action graph and record performance */ public boolean getShouldInstrumentActionGraph() { return getBooleanValue("instrumentation", "action_graph", false); } public Optional<String> getPathToBuildPrehookScript() { return getValue("build", "prehook_script"); } /** The timeout to apply to entire test rules. */ public Optional<Long> getDefaultTestRuleTimeoutMs() { return config.getLong(TEST_SECTION_HEADER, "rule_timeout"); } }
src/com/facebook/buck/config/BuckConfig.java
/* * Copyright 2012-present Facebook, 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.facebook.buck.config; import static java.lang.Integer.parseInt; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.parser.BuildTargetParseException; import com.facebook.buck.parser.BuildTargetParser; import com.facebook.buck.parser.BuildTargetPatternParser; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.DefaultBuildTargetSourcePath; import com.facebook.buck.rules.PathSourcePath; import com.facebook.buck.rules.RuleKeyDiagnosticsMode; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.util.Ansi; import com.facebook.buck.util.AnsiEnvironmentChecking; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.PatternAndMessage; import com.facebook.buck.util.cache.FileHashCacheMode; import com.facebook.buck.util.config.Config; import com.facebook.buck.util.environment.Architecture; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.network.hostname.HostnameFetching; import com.facebook.infer.annotation.PropagatesNullable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import java.io.IOException; import java.net.URI; import java.nio.file.Path; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; /** Structured representation of data read from a {@code .buckconfig} file. */ public class BuckConfig implements ConfigPathGetter { private static final String ALIAS_SECTION_HEADER = "alias"; private static final String TEST_SECTION_HEADER = "test"; private static final Float DEFAULT_THREAD_CORE_RATIO = Float.valueOf(1.0F); /** * This pattern is designed so that a fully-qualified build target cannot be a valid alias name * and vice-versa. */ private static final Pattern ALIAS_PATTERN = Pattern.compile("[a-zA-Z_-][a-zA-Z0-9_-]*"); private static final ImmutableMap<String, ImmutableSet<String>> IGNORE_FIELDS_FOR_DAEMON_RESTART; private final CellPathResolver cellPathResolver; private final Architecture architecture; private final Config config; private final ImmutableSetMultimap<String, BuildTarget> aliasToBuildTargetMap; private final ProjectFilesystem projectFilesystem; private final Platform platform; private final ImmutableMap<String, String> environment; private final ConfigViewCache<BuckConfig> viewCache = new ConfigViewCache<>(this); static { ImmutableMap.Builder<String, ImmutableSet<String>> ignoreFieldsForDaemonRestartBuilder = ImmutableMap.builder(); ignoreFieldsForDaemonRestartBuilder.put( "apple", ImmutableSet.of("generate_header_symlink_tree_only")); ignoreFieldsForDaemonRestartBuilder.put("build", ImmutableSet.of("threads")); ignoreFieldsForDaemonRestartBuilder.put( "cache", ImmutableSet.of("dir", "dir_mode", "http_mode", "http_url", "mode", "slb_server_pool")); ignoreFieldsForDaemonRestartBuilder.put( "client", ImmutableSet.of("id", "skip-action-graph-cache")); ignoreFieldsForDaemonRestartBuilder.put( "log", ImmutableSet.of( "chrome_trace_generation", "compress_traces", "max_traces", "public_announcements")); ignoreFieldsForDaemonRestartBuilder.put("project", ImmutableSet.of("ide_prompt")); ignoreFieldsForDaemonRestartBuilder.put("ui", ImmutableSet.of("superconsole")); ignoreFieldsForDaemonRestartBuilder.put("color", ImmutableSet.of("ui")); IGNORE_FIELDS_FOR_DAEMON_RESTART = ignoreFieldsForDaemonRestartBuilder.build(); } public BuckConfig( Config config, ProjectFilesystem projectFilesystem, Architecture architecture, Platform platform, ImmutableMap<String, String> environment, CellPathResolver cellPathResolver) { this.cellPathResolver = cellPathResolver; this.config = config; this.projectFilesystem = projectFilesystem; this.architecture = architecture; // We could create this Map on demand; however, in practice, it is almost always needed when // BuckConfig is needed because CommandLineBuildTargetNormalizer needs it. this.aliasToBuildTargetMap = createAliasToBuildTargetMap(this.getEntriesForSection(ALIAS_SECTION_HEADER)); this.platform = platform; this.environment = environment; } /** Returns a clone of the current config with a the argument CellPathResolver. */ public BuckConfig withCellPathResolver(CellPathResolver resolver) { return new BuckConfig(config, projectFilesystem, architecture, platform, environment, resolver); } /** * Get a {@link ConfigView} of this config. * * @param cls Class of the config view. * @param <T> Type of the config view. */ public <T extends ConfigView<BuckConfig>> T getView(Class<T> cls) { return viewCache.getView(cls); } /** * @return whether {@code aliasName} conforms to the pattern for a valid alias name. This does not * indicate whether it is an alias that maps to a build target in a BuckConfig. */ private static boolean isValidAliasName(String aliasName) { return ALIAS_PATTERN.matcher(aliasName).matches(); } public static void validateAliasName(String aliasName) throws HumanReadableException { validateAgainstAlias(aliasName, "Alias"); } public static void validateLabelName(String aliasName) throws HumanReadableException { validateAgainstAlias(aliasName, "Label"); } private static void validateAgainstAlias(String aliasName, String fieldName) { if (isValidAliasName(aliasName)) { return; } if (aliasName.isEmpty()) { throw new HumanReadableException("%s cannot be the empty string.", fieldName); } throw new HumanReadableException("Not a valid %s: %s.", fieldName.toLowerCase(), aliasName); } public Architecture getArchitecture() { return architecture; } public ImmutableMap<String, String> getEntriesForSection(String section) { ImmutableMap<String, String> entries = config.get(section); if (entries != null) { return entries; } else { return ImmutableMap.of(); } } public ImmutableList<String> getMessageOfTheDay() { return getListWithoutComments("project", "motd"); } public ImmutableList<String> getListWithoutComments(String section, String field) { return config.getListWithoutComments(section, field); } public ImmutableList<String> getListWithoutComments( String section, String field, char splitChar) { return config.getListWithoutComments(section, field, splitChar); } public CellPathResolver getCellPathResolver() { return cellPathResolver; } public Optional<ImmutableList<String>> getOptionalListWithoutComments( String section, String field) { return config.getOptionalListWithoutComments(section, field); } public Optional<ImmutableList<String>> getOptionalListWithoutComments( String section, String field, char splitChar) { return config.getOptionalListWithoutComments(section, field, splitChar); } public Optional<ImmutableList<Path>> getOptionalPathList( String section, String field, boolean resolve) { Optional<ImmutableList<String>> rawPaths = config.getOptionalListWithoutComments(section, field); if (rawPaths.isPresent()) { ImmutableList<Path> paths = rawPaths .get() .stream() .map( input -> convertPath( input, resolve, String.format( "Error in %s.%s: Cell-relative path not found: ", section, field))) .collect(ImmutableList.toImmutableList()); return Optional.of(paths); } return Optional.empty(); } public ImmutableSet<String> getBuildTargetForAliasAsString(String possiblyFlavoredAlias) { String[] parts = possiblyFlavoredAlias.split("#", 2); String unflavoredAlias = parts[0]; ImmutableSet<BuildTarget> buildTargets = getBuildTargetsForAlias(unflavoredAlias); if (buildTargets.isEmpty()) { return ImmutableSet.of(); } String suffix = parts.length == 2 ? "#" + parts[1] : ""; return buildTargets .stream() .map(buildTarget -> buildTarget.getFullyQualifiedName() + suffix) .collect(ImmutableSet.toImmutableSet()); } public ImmutableSet<BuildTarget> getBuildTargetsForAlias(String unflavoredAlias) { return aliasToBuildTargetMap.get(unflavoredAlias); } public BuildTarget getBuildTargetForFullyQualifiedTarget(String target) { return BuildTargetParser.INSTANCE.parse( target, BuildTargetPatternParser.fullyQualified(), getCellPathResolver()); } public ImmutableList<BuildTarget> getBuildTargetList(String section, String key) { ImmutableList<String> targetsToForce = getListWithoutComments(section, key); if (targetsToForce.size() == 0) { return ImmutableList.of(); } ImmutableList.Builder<BuildTarget> targets = new ImmutableList.Builder<>(); for (String targetOrAlias : targetsToForce) { Set<String> expandedAlias = getBuildTargetForAliasAsString(targetOrAlias); if (expandedAlias.isEmpty()) { targets.add(getBuildTargetForFullyQualifiedTarget(targetOrAlias)); } else { for (String target : expandedAlias) { targets.add(getBuildTargetForFullyQualifiedTarget(target)); } } } return targets.build(); } /** @return the parsed BuildTarget in the given section and field, if set. */ public Optional<BuildTarget> getBuildTarget(String section, String field) { Optional<String> target = getValue(section, field); return target.isPresent() ? Optional.of(getBuildTargetForFullyQualifiedTarget(target.get())) : Optional.empty(); } /** * @return the parsed BuildTarget in the given section and field, if set and a valid build target. * <p>This is useful if you use getTool to get the target, if any, but allow filesystem * references. */ public Optional<BuildTarget> getMaybeBuildTarget(String section, String field) { Optional<String> value = getValue(section, field); if (!value.isPresent()) { return Optional.empty(); } try { return Optional.of(getBuildTargetForFullyQualifiedTarget(value.get())); } catch (BuildTargetParseException e) { return Optional.empty(); } } /** @return the parsed BuildTarget in the given section and field. */ public BuildTarget getRequiredBuildTarget(String section, String field) { Optional<BuildTarget> target = getBuildTarget(section, field); return getOrThrow(section, field, target); } public <T extends Enum<T>> Optional<T> getEnum(String section, String field, Class<T> clazz) { return config.getEnum(section, field, clazz); } /** * @return a {@link SourcePath} identified by a @{link BuildTarget} or {@link Path} reference by * the given section:field, if set. */ public Optional<SourcePath> getSourcePath(String section, String field) { Optional<String> value = getValue(section, field); if (!value.isPresent()) { return Optional.empty(); } try { BuildTarget target = getBuildTargetForFullyQualifiedTarget(value.get()); return Optional.of(DefaultBuildTargetSourcePath.of(target)); } catch (BuildTargetParseException e) { return Optional.of( PathSourcePath.of( projectFilesystem, checkPathExists( value.get(), String.format("Overridden %s:%s path not found: ", section, field)))); } } /** @return a {@link SourcePath} identified by a {@link Path}. */ public PathSourcePath getPathSourcePath(@PropagatesNullable Path path) { if (path == null) { return null; } if (path.isAbsolute()) { return PathSourcePath.of(projectFilesystem, path); } return PathSourcePath.of( projectFilesystem, checkPathExists( path.toString(), String.format( "Failed to transform Path %s to Source Path because path was not found.", path))); } /** * In a {@link BuckConfig}, an alias can either refer to a fully-qualified build target, or an * alias defined earlier in the {@code alias} section. The mapping produced by this method * reflects the result of resolving all aliases as values in the {@code alias} section. */ private ImmutableSetMultimap<String, BuildTarget> createAliasToBuildTargetMap( ImmutableMap<String, String> rawAliasMap) { // We use a LinkedHashMap rather than an ImmutableMap.Builder because we want both (1) order to // be preserved, and (2) the ability to inspect the Map while building it up. SetMultimap<String, BuildTarget> aliasToBuildTarget = LinkedHashMultimap.create(); for (Map.Entry<String, String> aliasEntry : rawAliasMap.entrySet()) { String alias = aliasEntry.getKey(); validateAliasName(alias); // Determine whether the mapping is to a build target or to an alias. List<String> values = Splitter.on(' ').splitToList(aliasEntry.getValue()); for (String value : values) { Set<BuildTarget> buildTargets; if (isValidAliasName(value)) { buildTargets = aliasToBuildTarget.get(value); if (buildTargets.isEmpty()) { throw new HumanReadableException("No alias for: %s.", value); } } else if (value.isEmpty()) { continue; } else { // Here we parse the alias values with a BuildTargetParser to be strict. We could be // looser and just grab everything between "//" and ":" and assume it's a valid base path. buildTargets = ImmutableSet.of( BuildTargetParser.INSTANCE.parse( value, BuildTargetPatternParser.fullyQualified(), getCellPathResolver())); } aliasToBuildTarget.putAll(alias, buildTargets); } } return ImmutableSetMultimap.copyOf(aliasToBuildTarget); } /** * Create a map of {@link BuildTarget} base paths to aliases. Note that there may be more than one * alias to a base path, so the first one listed in the .buckconfig will be chosen. */ public ImmutableMap<Path, String> getBasePathToAliasMap() { ImmutableMap<String, String> aliases = config.get(ALIAS_SECTION_HEADER); if (aliases == null) { return ImmutableMap.of(); } // Build up the Map with an ordinary HashMap because we need to be able to check whether the Map // already contains the key before inserting. Map<Path, String> basePathToAlias = new HashMap<>(); for (Map.Entry<String, BuildTarget> entry : aliasToBuildTargetMap.entries()) { String alias = entry.getKey(); BuildTarget buildTarget = entry.getValue(); Path basePath = buildTarget.getBasePath(); if (!basePathToAlias.containsKey(basePath)) { basePathToAlias.put(basePath, alias); } } return ImmutableMap.copyOf(basePathToAlias); } public ImmutableMultimap<String, BuildTarget> getAliases() { return this.aliasToBuildTargetMap; } public long getDefaultTestTimeoutMillis() { return Long.parseLong(getValue("test", "timeout").orElse("0")); } public boolean isParallelExternalTestSpecComputationEnabled() { return getBooleanValue( TEST_SECTION_HEADER, "parallel_external_test_spec_computation_enabled", false); } private static final String LOG_SECTION = "log"; public boolean isPublicAnnouncementsEnabled() { return getBooleanValue(LOG_SECTION, "public_announcements", true); } public boolean isProcessTrackerEnabled() { return getBooleanValue(LOG_SECTION, "process_tracker_enabled", true); } public boolean isProcessTrackerDeepEnabled() { return getBooleanValue(LOG_SECTION, "process_tracker_deep_enabled", false); } public boolean isRuleKeyLoggerEnabled() { return getBooleanValue(LOG_SECTION, "rule_key_logger_enabled", false); } public RuleKeyDiagnosticsMode getRuleKeyDiagnosticsMode() { return getEnum(LOG_SECTION, "rule_key_diagnostics_mode", RuleKeyDiagnosticsMode.class) .orElse(RuleKeyDiagnosticsMode.NEVER); } public boolean isMachineReadableLoggerEnabled() { return getBooleanValue(LOG_SECTION, "machine_readable_logger_enabled", true); } public boolean isBuckConfigLocalWarningEnabled() { return getBooleanValue(LOG_SECTION, "buckconfig_local_warning_enabled", false); } public ProjectTestsMode xcodeProjectTestsMode() { return getEnum("project", "xcode_project_tests_mode", ProjectTestsMode.class) .orElse(ProjectTestsMode.WITH_TESTS); } public boolean getRestartAdbOnFailure() { return Boolean.parseBoolean(getValue("adb", "adb_restart_on_failure").orElse("true")); } public ImmutableList<String> getAdbRapidInstallTypes() { return getListWithoutComments("adb", "rapid_install_types_beta"); } public boolean getMultiInstallMode() { return getBooleanValue("adb", "multi_install_mode", false); } public boolean getFlushEventsBeforeExit() { return getBooleanValue("daemon", "flush_events_before_exit", false); } public ImmutableSet<String> getListenerJars() { return ImmutableSet.copyOf(getListWithoutComments("extensions", "listeners")); } /** Return Strings so as to avoid a dependency on {@link com.facebook.buck.cli.LabelSelector}! */ public ImmutableList<String> getDefaultRawExcludedLabelSelectors() { return getListWithoutComments("test", "excluded_labels"); } /** * Create an Ansi object appropriate for the current output. First respect the user's preferences, * if set. Next, respect any default provided by the caller. (This is used by buckd to tell the * daemon about the client's terminal.) Finally, allow the Ansi class to autodetect whether the * current output is a tty. * * @param defaultColor Default value provided by the caller (e.g. the client of buckd) */ public Ansi createAnsi(Optional<String> defaultColor) { String color = getValue("color", "ui").map(Optional::of).orElse(defaultColor).orElse("auto"); switch (color) { case "false": case "never": return Ansi.withoutTty(); case "true": case "always": return Ansi.forceTty(); case "auto": default: return new Ansi( AnsiEnvironmentChecking.environmentSupportsAnsiEscapes(platform, environment)); } } public Path resolvePathThatMayBeOutsideTheProjectFilesystem(@PropagatesNullable Path path) { if (path == null) { return path; } return resolveNonNullPathOutsideTheProjectFilesystem(path); } public Path resolveNonNullPathOutsideTheProjectFilesystem(Path path) { if (path.isAbsolute()) { return getPathFromVfs(path); } Path expandedPath = MorePaths.expandHomeDir(path); return projectFilesystem.resolve(expandedPath); } public String getLocalhost() { try { return HostnameFetching.getHostname(); } catch (IOException e) { return "<unknown>"; } } public Platform getPlatform() { return platform; } public boolean isActionGraphCheckingEnabled() { return getBooleanValue("cache", "action_graph_cache_check_enabled", false); } public int getMaxActionGraphCacheEntries() { return getInteger("cache", "max_action_graph_cache_entries").orElse(1); } public IncrementalActionGraphMode getIncrementalActionGraphMode() { return getEnum("cache", "incremental_action_graph", IncrementalActionGraphMode.class) .orElse(IncrementalActionGraphMode.DEFAULT); } public Optional<String> getRepository() { return config.get("cache", "repository"); } /** * Whether Buck should use Buck binary hash or git commit id as the core key in all rule keys. * * <p>The binary hash reflects the code that can affect the content of artifacts. * * <p>By default git commit id is used as the core key. * * @return <code>True</code> if binary hash should be used as the core key */ public boolean useBuckBinaryHash() { return getBooleanValue("cache", "use_buck_binary_hash", false); } public Optional<ImmutableSet<PatternAndMessage>> getUnexpectedFlavorsMessages() { ImmutableMap<String, String> entries = config.get("unknown_flavors_messages"); if (!entries.isEmpty()) { Set<PatternAndMessage> patternAndMessages = new HashSet<>(); for (Map.Entry<String, String> entry : entries.entrySet()) { patternAndMessages.add( PatternAndMessage.of(Pattern.compile(entry.getKey()), entry.getValue())); } return Optional.of(ImmutableSet.copyOf(patternAndMessages)); } return Optional.empty(); } public boolean hasUserDefinedValue(String sectionName, String propertyName) { return config.get(sectionName).containsKey(propertyName); } public Optional<ImmutableMap<String, String>> getSection(String sectionName) { ImmutableMap<String, String> values = config.get(sectionName); return values.isEmpty() ? Optional.empty() : Optional.of(values); } /** * @return the string value for the config settings, where present empty values are {@code * Optional.empty()}. */ public Optional<String> getValue(String sectionName, String propertyName) { return config.getValue(sectionName, propertyName); } /** * @return the string value for the config settings, where present empty values are {@code * Optional[]}. */ public Optional<String> getRawValue(String sectionName, String propertyName) { return config.get(sectionName, propertyName); } public Optional<Integer> getInteger(String sectionName, String propertyName) { return config.getInteger(sectionName, propertyName); } public Optional<Long> getLong(String sectionName, String propertyName) { return config.getLong(sectionName, propertyName); } public Optional<Float> getFloat(String sectionName, String propertyName) { return config.getFloat(sectionName, propertyName); } public Optional<Boolean> getBoolean(String sectionName, String propertyName) { return config.getBoolean(sectionName, propertyName); } public boolean getBooleanValue(String sectionName, String propertyName, boolean defaultValue) { return config.getBooleanValue(sectionName, propertyName, defaultValue); } public Optional<URI> getUrl(String section, String field) { return config.getUrl(section, field); } public ImmutableMap<String, String> getMap(String section, String field) { return config.getMap(section, field); } public <T> T getOrThrow(String section, String field, Optional<T> value) { if (!value.isPresent()) { throw new HumanReadableException( String.format(".buckconfig: %s:%s must be set", section, field)); } return value.get(); } // This is a hack. A cleaner approach would be to expose a narrow view of the config to any code // that affects the state cached by the Daemon. public boolean equalsForDaemonRestart(BuckConfig other) { return this.config.equalsIgnoring(other.config, IGNORE_FIELDS_FOR_DAEMON_RESTART); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (!(obj instanceof BuckConfig)) { return false; } BuckConfig that = (BuckConfig) obj; return Objects.equal(this.config, that.config); } @Override public String toString() { return String.format("%s (config=%s)", super.toString(), config); } @Override public int hashCode() { return Objects.hashCode(config); } public ImmutableMap<String, String> getEnvironment() { return environment; } public String[] getEnv(String propertyName, String separator) { String value = getEnvironment().get(propertyName); if (value == null) { value = ""; } return value.split(separator); } /** @return the local cache directory */ public String getLocalCacheDirectory(String dirCacheName) { return getValue(dirCacheName, "dir") .orElse(projectFilesystem.getBuckPaths().getCacheDir().toString()); } public int getKeySeed() { return parseInt(getValue("cache", "key_seed").orElse("0")); } /** @return the path for the given section and property. */ @Override public Optional<Path> getPath(String sectionName, String name) { return getPath(sectionName, name, true); } public Path getRequiredPath(String section, String field) { Optional<Path> path = getPath(section, field); return getOrThrow(section, field, path); } public String getClientId() { return getValue("client", "id").orElse("buck"); } /** * @return whether the current invocation of Buck should skip the Action Graph cache, leaving the * cached Action Graph in memory for the next request and creating a fresh Action Graph for * the current request (which will be garbage-collected when the current request is complete). * Commonly, a one-off request, like from a linter, will specify this option so that it does * not invalidate the primary in-memory Action Graph that the user is likely relying on for * fast iterative builds. */ public boolean isSkipActionGraphCache() { return getBooleanValue("client", "skip-action-graph-cache", false); } /** @return the number of threads Buck should use. */ public int getNumThreads() { return getNumThreads(getDefaultMaximumNumberOfThreads()); } /** * @return the number of threads Buck should use for testing. This will use the build * parallelization settings if not configured. */ public int getNumTestThreads() { double ratio = config.getFloat(TEST_SECTION_HEADER, "thread_utilization_ratio").orElse(1.0F); if (ratio <= 0.0F) { throw new HumanReadableException( "thread_utilization_ratio must be greater than zero (was " + ratio + ")"); } return (int) Math.ceil(ratio * getNumThreads()); } /** @return the number of threads to be used for the scheduled executor thread pool. */ public int getNumThreadsForSchedulerPool() { return config.getLong("build", "scheduler_threads").orElse((long) 2).intValue(); } /** @return the maximum size of files input based rule keys will be willing to hash. */ public long getBuildInputRuleKeyFileSizeLimit() { return config.getLong("build", "input_rule_key_file_size_limit").orElse(Long.MAX_VALUE); } public int getDefaultMaximumNumberOfThreads() { return getDefaultMaximumNumberOfThreads(Runtime.getRuntime().availableProcessors()); } @VisibleForTesting int getDefaultMaximumNumberOfThreads(int detectedProcessorCount) { double ratio = config.getFloat("build", "thread_core_ratio").orElse(DEFAULT_THREAD_CORE_RATIO); if (ratio <= 0.0F) { throw new HumanReadableException( "thread_core_ratio must be greater than zero (was " + ratio + ")"); } int scaledValue = (int) Math.ceil(ratio * detectedProcessorCount); int threadLimit = detectedProcessorCount; Optional<Long> reservedCores = getNumberOfReservedCores(); if (reservedCores.isPresent()) { threadLimit -= reservedCores.get(); } if (scaledValue > threadLimit) { scaledValue = threadLimit; } Optional<Long> minThreads = getThreadCoreRatioMinThreads(); if (minThreads.isPresent()) { scaledValue = Math.max(scaledValue, minThreads.get().intValue()); } Optional<Long> maxThreads = getThreadCoreRatioMaxThreads(); if (maxThreads.isPresent()) { long maxThreadsValue = maxThreads.get(); if (minThreads.isPresent() && minThreads.get() > maxThreadsValue) { throw new HumanReadableException( "thread_core_ratio_max_cores must be larger than thread_core_ratio_min_cores"); } if (maxThreadsValue > threadLimit) { throw new HumanReadableException( "thread_core_ratio_max_cores is larger than thread_core_ratio_reserved_cores allows"); } scaledValue = Math.min(scaledValue, (int) maxThreadsValue); } if (scaledValue <= 0) { throw new HumanReadableException( "Configuration resulted in an invalid number of build threads (" + scaledValue + ")."); } return scaledValue; } private Optional<Long> getNumberOfReservedCores() { Optional<Long> reservedCores = config.getLong("build", "thread_core_ratio_reserved_cores"); if (reservedCores.isPresent() && reservedCores.get() < 0) { throw new HumanReadableException("thread_core_ratio_reserved_cores must be larger than zero"); } return reservedCores; } private Optional<Long> getThreadCoreRatioMaxThreads() { Optional<Long> maxThreads = config.getLong("build", "thread_core_ratio_max_threads"); if (maxThreads.isPresent() && maxThreads.get() < 0) { throw new HumanReadableException("thread_core_ratio_max_threads must be larger than zero"); } return maxThreads; } private Optional<Long> getThreadCoreRatioMinThreads() { Optional<Long> minThreads = config.getLong("build", "thread_core_ratio_min_threads"); if (minThreads.isPresent() && minThreads.get() <= 0) { throw new HumanReadableException("thread_core_ratio_min_threads must be larger than zero"); } return minThreads; } /** * @return the number of threads Buck should use or the specified defaultValue if it is not set. */ public int getNumThreads(int defaultValue) { return config.getLong("build", "threads").orElse((long) defaultValue).intValue(); } public Optional<ImmutableList<String>> getAllowedJavaSpecificationVersions() { return getOptionalListWithoutComments("project", "allowed_java_specification_versions"); } public long getCountersFirstFlushIntervalMillis() { return config.getLong("counters", "first_flush_interval_millis").orElse(5000L); } public long getCountersFlushIntervalMillis() { return config.getLong("counters", "flush_interval_millis").orElse(30000L); } public Optional<Path> getPath(String sectionName, String name, boolean isCellRootRelative) { Optional<String> pathString = getValue(sectionName, name); return pathString.isPresent() ? Optional.of( convertPathWithError( pathString.get(), isCellRootRelative, String.format("Overridden %s:%s path not found: ", sectionName, name))) : Optional.empty(); } /** * Return a {@link Path} from the underlying {@link java.nio.file.FileSystem} implementation. This * allows to safely call {@link Path#resolve(Path)} and similar calls without exceptions caused by * mis-matched underlying filesystem implementations causing grief. This is particularly useful * for those times where we're using (eg) JimFs for our testing. */ private Path getPathFromVfs(String path) { return projectFilesystem.getPath(path); } private Path getPathFromVfs(Path path) { return projectFilesystem.getPath(path.toString()); } private Path convertPathWithError(String pathString, boolean isCellRootRelative, String error) { return isCellRootRelative ? checkPathExistsAndResolve(pathString, error) : getPathFromVfs(pathString); } private Path convertPath(String pathString, boolean resolve, String error) { return resolve ? checkPathExistsAndResolve(pathString, error) : checkPathExists(pathString, error); } public Path checkPathExistsAndResolve(String pathString, String errorMsg) { return projectFilesystem.getPathForRelativePath(checkPathExists(pathString, errorMsg)); } private Path checkPathExists(String pathString, String errorMsg) { Path path = getPathFromVfs(pathString); if (projectFilesystem.exists(path)) { return path; } throw new HumanReadableException(errorMsg + path); } public ImmutableSet<String> getSections() { return config.getSectionToEntries().keySet(); } public ImmutableMap<String, ImmutableMap<String, String>> getRawConfigForParser() { ImmutableMap<String, ImmutableMap<String, String>> rawSections = config.getSectionToEntries(); // If the raw config doesn't have sections which have ignored fields, then just return it as-is. ImmutableSet<String> sectionsWithIgnoredFields = IGNORE_FIELDS_FOR_DAEMON_RESTART.keySet(); if (Sets.intersection(rawSections.keySet(), sectionsWithIgnoredFields).isEmpty()) { return rawSections; } // Otherwise, iterate through the config to do finer-grain filtering. ImmutableMap.Builder<String, ImmutableMap<String, String>> filtered = ImmutableMap.builder(); for (Map.Entry<String, ImmutableMap<String, String>> sectionEnt : rawSections.entrySet()) { String sectionName = sectionEnt.getKey(); // If this section doesn't have a corresponding ignored section, then just add it as-is. if (!sectionsWithIgnoredFields.contains(sectionName)) { filtered.put(sectionEnt); continue; } // If none of this section's entries are ignored, then add it as-is. ImmutableMap<String, String> fields = sectionEnt.getValue(); ImmutableSet<String> ignoredFieldNames = IGNORE_FIELDS_FOR_DAEMON_RESTART.getOrDefault(sectionName, ImmutableSet.of()); if (Sets.intersection(fields.keySet(), ignoredFieldNames).isEmpty()) { filtered.put(sectionEnt); continue; } // Otherwise, filter out the ignored fields. ImmutableMap<String, String> remainingKeys = ImmutableMap.copyOf(Maps.filterKeys(fields, Predicates.not(ignoredFieldNames::contains))); if (!remainingKeys.isEmpty()) { filtered.put(sectionName, remainingKeys); } } return filtered.build(); } public Optional<ImmutableList<String>> getExternalTestRunner() { Optional<String> value = getValue("test", "external_runner"); if (!value.isPresent()) { return Optional.empty(); } return Optional.of(ImmutableList.copyOf(Splitter.on(' ').splitToList(value.get()))); } /** * @return whether to symlink the default output location (`buck-out`) to the user-provided * override for compatibility. */ public boolean getBuckOutCompatLink() { return getBooleanValue("project", "buck_out_compat_link", false); } /** @return whether to enabled versions on build/test command. */ public boolean getBuildVersions() { return getBooleanValue("build", "versions", false); } /** @return whether to enabled versions on targets command. */ public boolean getTargetsVersions() { return getBooleanValue("targets", "versions", false); } /** @return whether to enable caching of rule key calculations between builds. */ public boolean getRuleKeyCaching() { return getBooleanValue("build", "rule_key_caching", false); } public ImmutableList<String> getCleanAdditionalPaths() { return getListWithoutComments("clean", "additional_paths"); } public ImmutableList<String> getCleanExcludedCaches() { return getListWithoutComments("clean", "excluded_dir_caches"); } /** @return whether to enable new file hash cache engine. */ public FileHashCacheMode getFileHashCacheMode() { return getEnum("build", "file_hash_cache_mode", FileHashCacheMode.class) .orElse(FileHashCacheMode.DEFAULT); } /** Whether to parallelize action graph creation. */ public ActionGraphParallelizationMode getActionGraphParallelizationMode() { return getEnum("build", "action_graph_parallelization", ActionGraphParallelizationMode.class) .orElse(ActionGraphParallelizationMode.DEFAULT); } public Config getConfig() { return config; } public boolean isLogBuildIdToConsoleEnabled() { return getBooleanValue("log", "log_build_id_to_console_enabled", false); } /** Whether to create symlinks of build output in buck-out/last. */ public boolean createBuildOutputSymLinksEnabled() { return getBooleanValue("build", "create_build_output_symlinks_enabled", false); } public boolean isEmbeddedCellBuckOutEnabled() { return getBooleanValue("project", "embedded_cell_buck_out_enabled", false); } /** Whether to instrument the action graph and record performance */ public boolean getShouldInstrumentActionGraph() { return getBooleanValue("instrumentation", "action_graph", false); } public Optional<String> getPathToBuildPrehookScript() { return getValue("build", "prehook_script"); } /** The timeout to apply to entire test rules. */ public Optional<Long> getDefaultTestRuleTimeoutMs() { return config.getLong(TEST_SECTION_HEADER, "rule_timeout"); } }
Fix error message when Path to SourcePath conversion fails Summary: Before: `Failed to transform Path clang to Source Path because path was not found.clang` After: `Failed to transform Path to SourcePath, path not found: clang` Reviewed By: jtorkkola fbshipit-source-id: a25a133
src/com/facebook/buck/config/BuckConfig.java
Fix error message when Path to SourcePath conversion fails
<ide><path>rc/com/facebook/buck/config/BuckConfig.java <ide> return PathSourcePath.of( <ide> projectFilesystem, <ide> checkPathExists( <del> path.toString(), <del> String.format( <del> "Failed to transform Path %s to Source Path because path was not found.", path))); <add> path.toString(), "Failed to transform Path to SourcePath, path not found: ")); <ide> } <ide> <ide> /**
Java
bsd-3-clause
0c073df757846afe8bb3a26dde03975871271e71
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.alloc; import static com.oracle.graal.api.code.CodeUtil.*; import static com.oracle.graal.api.code.ValueUtil.*; import static com.oracle.graal.compiler.GraalDebugConfig.*; import static com.oracle.graal.compiler.common.cfg.AbstractControlFlowGraph.*; import static com.oracle.graal.lir.LIRValueUtil.*; import java.util.*; import com.oracle.graal.alloc.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.alloc.Interval.RegisterBinding; import com.oracle.graal.compiler.alloc.Interval.RegisterPriority; import com.oracle.graal.compiler.alloc.Interval.SpillState; import com.oracle.graal.compiler.common.*; import com.oracle.graal.compiler.common.cfg.*; import com.oracle.graal.compiler.gen.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.Debug.Scope; import com.oracle.graal.lir.*; import com.oracle.graal.lir.LIRInstruction.OperandFlag; import com.oracle.graal.lir.LIRInstruction.OperandMode; import com.oracle.graal.lir.StandardOp.MoveOp; import com.oracle.graal.nodes.*; import com.oracle.graal.options.*; import com.oracle.graal.phases.util.*; /** * An implementation of the linear scan register allocator algorithm described in <a * href="http://doi.acm.org/10.1145/1064979.1064998" * >"Optimized Interval Splitting in a Linear Scan Register Allocator"</a> by Christian Wimmer and * Hanspeter Moessenboeck. */ public final class LinearScan { final TargetDescription target; final LIR ir; final FrameMap frameMap; final RegisterAttributes[] registerAttributes; final Register[] registers; boolean callKillsRegisters; public static final int DOMINATOR_SPILL_MOVE_ID = -2; private static final int SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT = 1; public static class Options { // @formatter:off @Option(help = "Enable spill position optimization") public static final OptionValue<Boolean> LSRAOptimizeSpillPosition = new OptionValue<>(true); // @formatter:on } public static class BlockData { /** * Bit map specifying which operands are live upon entry to this block. These are values * used in this block or any of its successors where such value are not defined in this * block. The bit index of an operand is its {@linkplain LinearScan#operandNumber(Value) * operand number}. */ public BitSet liveIn; /** * Bit map specifying which operands are live upon exit from this block. These are values * used in a successor block that are either defined in this block or were live upon entry * to this block. The bit index of an operand is its * {@linkplain LinearScan#operandNumber(Value) operand number}. */ public BitSet liveOut; /** * Bit map specifying which operands are used (before being defined) in this block. That is, * these are the values that are live upon entry to the block. The bit index of an operand * is its {@linkplain LinearScan#operandNumber(Value) operand number}. */ public BitSet liveGen; /** * Bit map specifying which operands are defined/overwritten in this block. The bit index of * an operand is its {@linkplain LinearScan#operandNumber(Value) operand number}. */ public BitSet liveKill; } public final BlockMap<BlockData> blockData; /** * List of blocks in linear-scan order. This is only correct as long as the CFG does not change. */ final List<? extends AbstractBlock<?>> sortedBlocks; /** * Map from {@linkplain #operandNumber(Value) operand numbers} to intervals. */ Interval[] intervals; /** * The number of valid entries in {@link #intervals}. */ int intervalsSize; /** * The index of the first entry in {@link #intervals} for a * {@linkplain #createDerivedInterval(Interval) derived interval}. */ int firstDerivedIntervalIndex = -1; /** * Intervals sorted by {@link Interval#from()}. */ Interval[] sortedIntervals; /** * Map from an instruction {@linkplain LIRInstruction#id id} to the instruction. Entries should * be retrieved with {@link #instructionForId(int)} as the id is not simply an index into this * array. */ LIRInstruction[] opIdToInstructionMap; /** * Map from an instruction {@linkplain LIRInstruction#id id} to the {@linkplain AbstractBlock * block} containing the instruction. Entries should be retrieved with {@link #blockForId(int)} * as the id is not simply an index into this array. */ AbstractBlock<?>[] opIdToBlockMap; /** * Bit set for each variable that is contained in each loop. */ BitMap2D intervalInLoop; /** * The {@linkplain #operandNumber(Value) number} of the first variable operand allocated. */ private final int firstVariableNumber; public LinearScan(TargetDescription target, LIR ir, FrameMap frameMap) { this.target = target; this.ir = ir; this.frameMap = frameMap; this.sortedBlocks = ir.linearScanOrder(); this.registerAttributes = frameMap.registerConfig.getAttributesMap(); this.registers = target.arch.getRegisters(); this.firstVariableNumber = registers.length; this.blockData = new BlockMap<>(ir.getControlFlowGraph()); } public int getFirstLirInstructionId(AbstractBlock<?> block) { int result = ir.getLIRforBlock(block).get(0).id(); assert result >= 0; return result; } public int getLastLirInstructionId(AbstractBlock<?> block) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); int result = instructions.get(instructions.size() - 1).id(); assert result >= 0; return result; } public static boolean isVariableOrRegister(Value value) { return isVariable(value) || isRegister(value); } /** * Converts an operand (variable or register) to an index in a flat address space covering all * the {@linkplain Variable variables} and {@linkplain RegisterValue registers} being processed * by this allocator. */ private int operandNumber(Value operand) { if (isRegister(operand)) { int number = asRegister(operand).number; assert number < firstVariableNumber; return number; } assert isVariable(operand) : operand; return firstVariableNumber + ((Variable) operand).index; } /** * Gets the number of operands. This value will increase by 1 for new variable. */ private int operandSize() { return firstVariableNumber + ir.numVariables(); } /** * Gets the highest operand number for a register operand. This value will never change. */ public int maxRegisterNumber() { return firstVariableNumber - 1; } static final IntervalPredicate IS_PRECOLORED_INTERVAL = new IntervalPredicate() { @Override public boolean apply(Interval i) { return isRegister(i.operand); } }; static final IntervalPredicate IS_VARIABLE_INTERVAL = new IntervalPredicate() { @Override public boolean apply(Interval i) { return isVariable(i.operand); } }; static final IntervalPredicate IS_STACK_INTERVAL = new IntervalPredicate() { @Override public boolean apply(Interval i) { return !isRegister(i.operand); } }; /** * Gets an object describing the attributes of a given register according to this register * configuration. */ RegisterAttributes attributes(Register reg) { return registerAttributes[reg.number]; } void assignSpillSlot(Interval interval) { // assign the canonical spill slot of the parent (if a part of the interval // is already spilled) or allocate a new spill slot if (interval.canMaterialize()) { interval.assignLocation(Value.ILLEGAL); } else if (interval.spillSlot() != null) { interval.assignLocation(interval.spillSlot()); } else { StackSlot slot = frameMap.allocateSpillSlot(interval.kind()); interval.setSpillSlot(slot); interval.assignLocation(slot); } } /** * Creates a new interval. * * @param operand the operand for the interval * @return the created interval */ Interval createInterval(AllocatableValue operand) { assert isLegal(operand); int operandNumber = operandNumber(operand); Interval interval = new Interval(operand, operandNumber); assert operandNumber < intervalsSize; assert intervals[operandNumber] == null; intervals[operandNumber] = interval; return interval; } /** * Creates an interval as a result of splitting or spilling another interval. * * @param source an interval being split of spilled * @return a new interval derived from {@code source} */ Interval createDerivedInterval(Interval source) { if (firstDerivedIntervalIndex == -1) { firstDerivedIntervalIndex = intervalsSize; } if (intervalsSize == intervals.length) { intervals = Arrays.copyOf(intervals, intervals.length + (intervals.length >> SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT)); } intervalsSize++; Variable variable = new Variable(source.kind(), ir.nextVariable()); Interval interval = createInterval(variable); assert intervals[intervalsSize - 1] == interval; return interval; } // access to block list (sorted in linear scan order) int blockCount() { return sortedBlocks.size(); } AbstractBlock<?> blockAt(int index) { return sortedBlocks.get(index); } /** * Gets the size of the {@link BlockData#liveIn} and {@link BlockData#liveOut} sets for a basic * block. These sets do not include any operands allocated as a result of creating * {@linkplain #createDerivedInterval(Interval) derived intervals}. */ int liveSetSize() { return firstDerivedIntervalIndex == -1 ? operandSize() : firstDerivedIntervalIndex; } int numLoops() { return ir.getControlFlowGraph().getLoops().size(); } boolean isIntervalInLoop(int interval, int loop) { return intervalInLoop.at(interval, loop); } Interval intervalFor(int operandNumber) { return intervals[operandNumber]; } Interval intervalFor(Value operand) { int operandNumber = operandNumber(operand); assert operandNumber < intervalsSize; return intervals[operandNumber]; } Interval getOrCreateInterval(AllocatableValue operand) { Interval ret = intervalFor(operand); if (ret == null) { return createInterval(operand); } else { return ret; } } /** * Gets the highest instruction id allocated by this object. */ int maxOpId() { assert opIdToInstructionMap.length > 0 : "no operations"; return (opIdToInstructionMap.length - 1) << 1; } /** * Converts an {@linkplain LIRInstruction#id instruction id} to an instruction index. All LIR * instructions in a method have an index one greater than their linear-scan order predecesor * with the first instruction having an index of 0. */ static int opIdToIndex(int opId) { return opId >> 1; } /** * Retrieves the {@link LIRInstruction} based on its {@linkplain LIRInstruction#id id}. * * @param opId an instruction {@linkplain LIRInstruction#id id} * @return the instruction whose {@linkplain LIRInstruction#id} {@code == id} */ LIRInstruction instructionForId(int opId) { assert isEven(opId) : "opId not even"; LIRInstruction instr = opIdToInstructionMap[opIdToIndex(opId)]; assert instr.id() == opId; return instr; } /** * Gets the block containing a given instruction. * * @param opId an instruction {@linkplain LIRInstruction#id id} * @return the block containing the instruction denoted by {@code opId} */ AbstractBlock<?> blockForId(int opId) { assert opIdToBlockMap.length > 0 && opId >= 0 && opId <= maxOpId() + 1 : "opId out of range"; return opIdToBlockMap[opIdToIndex(opId)]; } boolean isBlockBegin(int opId) { return opId == 0 || blockForId(opId) != blockForId(opId - 1); } boolean coversBlockBegin(int opId1, int opId2) { return blockForId(opId1) != blockForId(opId2); } /** * Determines if an {@link LIRInstruction} destroys all caller saved registers. * * @param opId an instruction {@linkplain LIRInstruction#id id} * @return {@code true} if the instruction denoted by {@code id} destroys all caller saved * registers. */ boolean hasCall(int opId) { assert isEven(opId) : "opId not even"; return instructionForId(opId).destroysCallerSavedRegisters(); } /** * Eliminates moves from register to stack if the stack slot is known to be correct. */ void changeSpillDefinitionPos(Interval interval, int defPos) { assert interval.isSplitParent() : "can only be called for split parents"; switch (interval.spillState()) { case NoDefinitionFound: assert interval.spillDefinitionPos() == -1 : "must no be set before"; interval.setSpillDefinitionPos(defPos); interval.setSpillState(SpillState.NoSpillStore); break; case NoSpillStore: assert defPos <= interval.spillDefinitionPos() : "positions are processed in reverse order when intervals are created"; if (defPos < interval.spillDefinitionPos() - 2) { // second definition found, so no spill optimization possible for this interval interval.setSpillState(SpillState.NoOptimization); } else { // two consecutive definitions (because of two-operand LIR form) assert blockForId(defPos) == blockForId(interval.spillDefinitionPos()) : "block must be equal"; } break; case NoOptimization: // nothing to do break; default: throw new BailoutException("other states not allowed at this time"); } } // called during register allocation void changeSpillState(Interval interval, int spillPos) { switch (interval.spillState()) { case NoSpillStore: { int defLoopDepth = blockForId(interval.spillDefinitionPos()).getLoopDepth(); int spillLoopDepth = blockForId(spillPos).getLoopDepth(); if (defLoopDepth < spillLoopDepth) { // the loop depth of the spilling position is higher then the loop depth // at the definition of the interval . move write to memory out of loop. if (Options.LSRAOptimizeSpillPosition.getValue()) { // find best spill position in dominator the tree interval.setSpillState(SpillState.SpillInDominator); } else { // store at definition of the interval interval.setSpillState(SpillState.StoreAtDefinition); } } else { // the interval is currently spilled only once, so for now there is no // reason to store the interval at the definition interval.setSpillState(SpillState.OneSpillStore); } break; } case OneSpillStore: { if (Options.LSRAOptimizeSpillPosition.getValue()) { // the interval is spilled more then once interval.setSpillState(SpillState.SpillInDominator); } else { // it is better to store it to // memory at the definition interval.setSpillState(SpillState.StoreAtDefinition); } break; } case SpillInDominator: case StoreAtDefinition: case StartInMemory: case NoOptimization: case NoDefinitionFound: // nothing to do break; default: throw new BailoutException("other states not allowed at this time"); } } abstract static class IntervalPredicate { abstract boolean apply(Interval i); } private static final IntervalPredicate mustStoreAtDefinition = new IntervalPredicate() { @Override public boolean apply(Interval i) { return i.isSplitParent() && i.spillState() == SpillState.StoreAtDefinition; } }; // called once before assignment of register numbers void eliminateSpillMoves() { try (Indent indent = Debug.logAndIndent("Eliminating unnecessary spill moves")) { // collect all intervals that must be stored after their definition. // the list is sorted by Interval.spillDefinitionPos Interval interval; interval = createUnhandledLists(mustStoreAtDefinition, null).first; if (DetailedAsserts.getValue()) { checkIntervals(interval); } LIRInsertionBuffer insertionBuffer = new LIRInsertionBuffer(); for (AbstractBlock<?> block : sortedBlocks) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); int numInst = instructions.size(); // iterate all instructions of the block. skip the first // because it is always a label for (int j = 1; j < numInst; j++) { LIRInstruction op = instructions.get(j); int opId = op.id(); if (opId == -1) { MoveOp move = (MoveOp) op; // remove move from register to stack if the stack slot is guaranteed to be // correct. // only moves that have been inserted by LinearScan can be removed. assert isVariable(move.getResult()) : "LinearScan inserts only moves to variables"; Interval curInterval = intervalFor(move.getResult()); if (!isRegister(curInterval.location()) && curInterval.alwaysInMemory()) { // move target is a stack slot that is always correct, so eliminate // instruction if (Debug.isLogEnabled()) { Debug.log("eliminating move from interval %d to %d", operandNumber(move.getInput()), operandNumber(move.getResult())); } // null-instructions are deleted by assignRegNum instructions.set(j, null); } } else { // insert move from register to stack just after // the beginning of the interval assert interval == Interval.EndMarker || interval.spillDefinitionPos() >= opId : "invalid order"; assert interval == Interval.EndMarker || (interval.isSplitParent() && interval.spillState() == SpillState.StoreAtDefinition) : "invalid interval"; while (interval != Interval.EndMarker && interval.spillDefinitionPos() == opId) { if (!interval.canMaterialize()) { if (!insertionBuffer.initialized()) { // prepare insertion buffer (appended when all instructions in // the block are processed) insertionBuffer.init(instructions); } AllocatableValue fromLocation = interval.location(); AllocatableValue toLocation = canonicalSpillOpr(interval); assert isRegister(fromLocation) : "from operand must be a register but is: " + fromLocation + " toLocation=" + toLocation + " spillState=" + interval.spillState(); assert isStackSlot(toLocation) : "to operand must be a stack slot"; insertionBuffer.append(j + 1, ir.getSpillMoveFactory().createMove(toLocation, fromLocation)); Debug.log("inserting move after definition of interval %d to stack slot %s at opId %d", interval.operandNumber, interval.spillSlot(), opId); } interval = interval.next; } } } // end of instruction iteration if (insertionBuffer.initialized()) { insertionBuffer.finish(); } } // end of block iteration assert interval == Interval.EndMarker : "missed an interval"; } } private static void checkIntervals(Interval interval) { Interval prev = null; Interval temp = interval; while (temp != Interval.EndMarker) { assert temp.spillDefinitionPos() > 0 : "invalid spill definition pos"; if (prev != null) { assert temp.from() >= prev.from() : "intervals not sorted"; assert temp.spillDefinitionPos() >= prev.spillDefinitionPos() : "when intervals are sorted by from : then they must also be sorted by spillDefinitionPos"; } assert temp.spillSlot() != null || temp.canMaterialize() : "interval has no spill slot assigned"; assert temp.spillDefinitionPos() >= temp.from() : "invalid order"; assert temp.spillDefinitionPos() <= temp.from() + 2 : "only intervals defined once at their start-pos can be optimized"; Debug.log("interval %d (from %d to %d) must be stored at %d", temp.operandNumber, temp.from(), temp.to(), temp.spillDefinitionPos()); prev = temp; temp = temp.next; } } /** * Numbers all instructions in all blocks. The numbering follows the * {@linkplain ComputeBlockOrder linear scan order}. */ void numberInstructions() { intervalsSize = operandSize(); intervals = new Interval[intervalsSize + (intervalsSize >> SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT)]; ValueConsumer setVariableConsumer = new ValueConsumer() { @Override public void visitValue(Value value, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariable(value)) { getOrCreateInterval(asVariable(value)); } } }; // Assign IDs to LIR nodes and build a mapping, lirOps, from ID to LIRInstruction node. int numInstructions = 0; for (AbstractBlock<?> block : sortedBlocks) { numInstructions += ir.getLIRforBlock(block).size(); } // initialize with correct length opIdToInstructionMap = new LIRInstruction[numInstructions]; opIdToBlockMap = new AbstractBlock<?>[numInstructions]; int opId = 0; int index = 0; for (AbstractBlock<?> block : sortedBlocks) { blockData.put(block, new BlockData()); List<LIRInstruction> instructions = ir.getLIRforBlock(block); int numInst = instructions.size(); for (int j = 0; j < numInst; j++) { LIRInstruction op = instructions.get(j); op.setId(opId); opIdToInstructionMap[index] = op; opIdToBlockMap[index] = block; assert instructionForId(opId) == op : "must match"; op.visitEachTemp(setVariableConsumer); op.visitEachOutput(setVariableConsumer); index++; opId += 2; // numbering of lirOps by two } } assert index == numInstructions : "must match"; assert (index << 1) == opId : "must match: " + (index << 1); } /** * Computes local live sets (i.e. {@link BlockData#liveGen} and {@link BlockData#liveKill}) * separately for each block. */ void computeLocalLiveSets() { int liveSize = liveSetSize(); intervalInLoop = new BitMap2D(operandSize(), numLoops()); // iterate all blocks for (final AbstractBlock<?> block : sortedBlocks) { try (Indent indent = Debug.logAndIndent("compute local live sets for block %d", block.getId())) { final BitSet liveGen = new BitSet(liveSize); final BitSet liveKill = new BitSet(liveSize); List<LIRInstruction> instructions = ir.getLIRforBlock(block); int numInst = instructions.size(); ValueConsumer useConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariable(operand)) { int operandNum = operandNumber(operand); if (!liveKill.get(operandNum)) { liveGen.set(operandNum); Debug.log("liveGen for operand %d", operandNum); } if (block.getLoop() != null) { intervalInLoop.setBit(operandNum, block.getLoop().getIndex()); } } if (DetailedAsserts.getValue()) { verifyInput(block, liveKill, operand); } } }; ValueConsumer stateConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { int operandNum = operandNumber(operand); if (!liveKill.get(operandNum)) { liveGen.set(operandNum); Debug.log("liveGen in state for operand %d", operandNum); } } }; ValueConsumer defConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariable(operand)) { int varNum = operandNumber(operand); liveKill.set(varNum); Debug.log("liveKill for operand %d", varNum); if (block.getLoop() != null) { intervalInLoop.setBit(varNum, block.getLoop().getIndex()); } } if (DetailedAsserts.getValue()) { // fixed intervals are never live at block boundaries, so // they need not be processed in live sets // process them only in debug mode so that this can be checked verifyTemp(liveKill, operand); } } }; // iterate all instructions of the block for (int j = 0; j < numInst; j++) { final LIRInstruction op = instructions.get(j); try (Indent indent2 = Debug.logAndIndent("handle op %d", op.id())) { op.visitEachInput(useConsumer); op.visitEachAlive(useConsumer); // Add uses of live locals from interpreter's point of view for proper debug // information generation op.visitEachState(stateConsumer); op.visitEachTemp(defConsumer); op.visitEachOutput(defConsumer); } } // end of instruction iteration BlockData blockSets = blockData.get(block); blockSets.liveGen = liveGen; blockSets.liveKill = liveKill; blockSets.liveIn = new BitSet(liveSize); blockSets.liveOut = new BitSet(liveSize); Debug.log("liveGen B%d %s", block.getId(), blockSets.liveGen); Debug.log("liveKill B%d %s", block.getId(), blockSets.liveKill); } } // end of block iteration } private void verifyTemp(BitSet liveKill, Value operand) { // fixed intervals are never live at block boundaries, so // they need not be processed in live sets // process them only in debug mode so that this can be checked if (isRegister(operand)) { if (isProcessed(operand)) { liveKill.set(operandNumber(operand)); } } } private void verifyInput(AbstractBlock<?> block, BitSet liveKill, Value operand) { // fixed intervals are never live at block boundaries, so // they need not be processed in live sets. // this is checked by these assertions to be sure about it. // the entry block may have incoming // values in registers, which is ok. if (isRegister(operand) && block != ir.getControlFlowGraph().getStartBlock()) { if (isProcessed(operand)) { assert liveKill.get(operandNumber(operand)) : "using fixed register that is not defined in this block"; } } } /** * Performs a backward dataflow analysis to compute global live sets (i.e. * {@link BlockData#liveIn} and {@link BlockData#liveOut}) for each block. */ void computeGlobalLiveSets() { try (Indent indent = Debug.logAndIndent("compute global live sets")) { int numBlocks = blockCount(); boolean changeOccurred; boolean changeOccurredInBlock; int iterationCount = 0; BitSet liveOut = new BitSet(liveSetSize()); // scratch set for calculations // Perform a backward dataflow analysis to compute liveOut and liveIn for each block. // The loop is executed until a fixpoint is reached (no changes in an iteration) do { changeOccurred = false; try (Indent indent2 = Debug.logAndIndent("new iteration %d", iterationCount)) { // iterate all blocks in reverse order for (int i = numBlocks - 1; i >= 0; i--) { AbstractBlock<?> block = blockAt(i); BlockData blockSets = blockData.get(block); changeOccurredInBlock = false; // liveOut(block) is the union of liveIn(sux), for successors sux of block int n = block.getSuccessorCount(); if (n > 0) { liveOut.clear(); // block has successors if (n > 0) { for (AbstractBlock<?> successor : block.getSuccessors()) { liveOut.or(blockData.get(successor).liveIn); } } if (!blockSets.liveOut.equals(liveOut)) { // A change occurred. Swap the old and new live out // sets to avoid copying. BitSet temp = blockSets.liveOut; blockSets.liveOut = liveOut; liveOut = temp; changeOccurred = true; changeOccurredInBlock = true; } } if (iterationCount == 0 || changeOccurredInBlock) { // liveIn(block) is the union of liveGen(block) with (liveOut(block) & // !liveKill(block)) // note: liveIn has to be computed only in first iteration // or if liveOut has changed! BitSet liveIn = blockSets.liveIn; liveIn.clear(); liveIn.or(blockSets.liveOut); liveIn.andNot(blockSets.liveKill); liveIn.or(blockSets.liveGen); Debug.log("block %d: livein = %s, liveout = %s", block.getId(), liveIn, blockSets.liveOut); } } iterationCount++; if (changeOccurred && iterationCount > 50) { throw new BailoutException("too many iterations in computeGlobalLiveSets"); } } } while (changeOccurred); if (DetailedAsserts.getValue()) { verifyLiveness(); } // check that the liveIn set of the first block is empty AbstractBlock<?> startBlock = ir.getControlFlowGraph().getStartBlock(); if (blockData.get(startBlock).liveIn.cardinality() != 0) { if (DetailedAsserts.getValue()) { reportFailure(numBlocks); } // bailout if this occurs in product mode. throw new GraalInternalError("liveIn set of first block must be empty: " + blockData.get(startBlock).liveIn); } } } private static NodeLIRBuilder getNodeLIRGeneratorFromDebugContext() { if (Debug.isEnabled()) { NodeLIRBuilder lirGen = Debug.contextLookup(NodeLIRBuilder.class); assert lirGen != null; return lirGen; } return null; } private static ValueNode getValueForOperandFromDebugContext(Value value) { NodeLIRBuilder gen = getNodeLIRGeneratorFromDebugContext(); if (gen != null) { return gen.valueForOperand(value); } return null; } private void reportFailure(int numBlocks) { try (Scope s = Debug.forceLog()) { try (Indent indent = Debug.logAndIndent("report failure")) { BitSet startBlockLiveIn = blockData.get(ir.getControlFlowGraph().getStartBlock()).liveIn; try (Indent indent2 = Debug.logAndIndent("Error: liveIn set of first block must be empty (when this fails, variables are used before they are defined):")) { for (int operandNum = startBlockLiveIn.nextSetBit(0); operandNum >= 0; operandNum = startBlockLiveIn.nextSetBit(operandNum + 1)) { Interval interval = intervalFor(operandNum); if (interval != null) { Value operand = interval.operand; Debug.log("var %d; operand=%s; node=%s", operandNum, operand, getValueForOperandFromDebugContext(operand)); } else { Debug.log("var %d; missing operand", operandNum); } } } // print some additional information to simplify debugging for (int operandNum = startBlockLiveIn.nextSetBit(0); operandNum >= 0; operandNum = startBlockLiveIn.nextSetBit(operandNum + 1)) { Interval interval = intervalFor(operandNum); Value operand = null; ValueNode valueForOperandFromDebugContext = null; if (interval != null) { operand = interval.operand; valueForOperandFromDebugContext = getValueForOperandFromDebugContext(operand); } try (Indent indent2 = Debug.logAndIndent("---- Detailed information for var %d; operand=%s; node=%s ----", operandNum, operand, valueForOperandFromDebugContext)) { Deque<AbstractBlock<?>> definedIn = new ArrayDeque<>(); HashSet<AbstractBlock<?>> usedIn = new HashSet<>(); for (AbstractBlock<?> block : sortedBlocks) { if (blockData.get(block).liveGen.get(operandNum)) { usedIn.add(block); try (Indent indent3 = Debug.logAndIndent("used in block B%d", block.getId())) { for (LIRInstruction ins : ir.getLIRforBlock(block)) { try (Indent indent4 = Debug.logAndIndent("%d: %s", ins.id(), ins)) { ins.forEachState((liveStateOperand, mode, flags) -> { Debug.log("operand=%s", liveStateOperand); return liveStateOperand; }); } } } } if (blockData.get(block).liveKill.get(operandNum)) { definedIn.add(block); try (Indent indent3 = Debug.logAndIndent("defined in block B%d", block.getId())) { for (LIRInstruction ins : ir.getLIRforBlock(block)) { Debug.log("%d: %s", ins.id(), ins); } } } } int[] hitCount = new int[numBlocks]; while (!definedIn.isEmpty()) { AbstractBlock<?> block = definedIn.removeFirst(); usedIn.remove(block); for (AbstractBlock<?> successor : block.getSuccessors()) { if (successor.isLoopHeader()) { if (!block.isLoopEnd()) { definedIn.add(successor); } } else { if (++hitCount[successor.getId()] == successor.getPredecessorCount()) { definedIn.add(successor); } } } } try (Indent indent3 = Debug.logAndIndent("**** offending usages are in: ")) { for (AbstractBlock<?> block : usedIn) { Debug.log("B%d", block.getId()); } } } } } } catch (Throwable e) { throw Debug.handle(e); } } private void verifyLiveness() { // check that fixed intervals are not live at block boundaries // (live set must be empty at fixed intervals) for (AbstractBlock<?> block : sortedBlocks) { for (int j = 0; j <= maxRegisterNumber(); j++) { assert !blockData.get(block).liveIn.get(j) : "liveIn set of fixed register must be empty"; assert !blockData.get(block).liveOut.get(j) : "liveOut set of fixed register must be empty"; assert !blockData.get(block).liveGen.get(j) : "liveGen set of fixed register must be empty"; } } } void addUse(AllocatableValue operand, int from, int to, RegisterPriority registerPriority, LIRKind kind) { if (!isProcessed(operand)) { return; } Interval interval = getOrCreateInterval(operand); if (!kind.equals(LIRKind.Illegal)) { interval.setKind(kind); } interval.addRange(from, to); // Register use position at even instruction id. interval.addUsePos(to & ~1, registerPriority); Debug.log("add use: %s, from %d to %d (%s)", interval, from, to, registerPriority.name()); } void addTemp(AllocatableValue operand, int tempPos, RegisterPriority registerPriority, LIRKind kind) { if (!isProcessed(operand)) { return; } Interval interval = getOrCreateInterval(operand); if (!kind.equals(LIRKind.Illegal)) { interval.setKind(kind); } interval.addRange(tempPos, tempPos + 1); interval.addUsePos(tempPos, registerPriority); interval.addMaterializationValue(null); Debug.log("add temp: %s tempPos %d (%s)", interval, tempPos, RegisterPriority.MustHaveRegister.name()); } boolean isProcessed(Value operand) { return !isRegister(operand) || attributes(asRegister(operand)).isAllocatable(); } void addDef(AllocatableValue operand, LIRInstruction op, RegisterPriority registerPriority, LIRKind kind) { if (!isProcessed(operand)) { return; } int defPos = op.id(); Interval interval = getOrCreateInterval(operand); if (!kind.equals(LIRKind.Illegal)) { interval.setKind(kind); } Range r = interval.first(); if (r.from <= defPos) { // Update the starting point (when a range is first created for a use, its // start is the beginning of the current block until a def is encountered.) r.from = defPos; interval.addUsePos(defPos, registerPriority); } else { // Dead value - make vacuous interval // also add register priority for dead intervals interval.addRange(defPos, defPos + 1); interval.addUsePos(defPos, registerPriority); Debug.log("Warning: def of operand %s at %d occurs without use", operand, defPos); } changeSpillDefinitionPos(interval, defPos); if (registerPriority == RegisterPriority.None && interval.spillState().ordinal() <= SpillState.StartInMemory.ordinal()) { // detection of method-parameters and roundfp-results interval.setSpillState(SpillState.StartInMemory); } interval.addMaterializationValue(LinearScan.getMaterializedValue(op, operand, interval)); Debug.log("add def: %s defPos %d (%s)", interval, defPos, registerPriority.name()); } /** * Determines the register priority for an instruction's output/result operand. */ static RegisterPriority registerPriorityOfOutputOperand(LIRInstruction op) { if (op instanceof MoveOp) { MoveOp move = (MoveOp) op; if (optimizeMethodArgument(move.getInput())) { return RegisterPriority.None; } } // all other operands require a register return RegisterPriority.MustHaveRegister; } /** * Determines the priority which with an instruction's input operand will be allocated a * register. */ static RegisterPriority registerPriorityOfInputOperand(EnumSet<OperandFlag> flags) { if (flags.contains(OperandFlag.STACK)) { return RegisterPriority.ShouldHaveRegister; } // all other operands require a register return RegisterPriority.MustHaveRegister; } private static boolean optimizeMethodArgument(Value value) { /* * Object method arguments that are passed on the stack are currently not optimized because * this requires that the runtime visits method arguments during stack walking. */ return isStackSlot(value) && asStackSlot(value).isInCallerFrame() && value.getKind() != Kind.Object; } /** * Optimizes moves related to incoming stack based arguments. The interval for the destination * of such moves is assigned the stack slot (which is in the caller's frame) as its spill slot. */ void handleMethodArguments(LIRInstruction op) { if (op instanceof MoveOp) { MoveOp move = (MoveOp) op; if (optimizeMethodArgument(move.getInput())) { StackSlot slot = asStackSlot(move.getInput()); if (DetailedAsserts.getValue()) { assert op.id() > 0 : "invalid id"; assert blockForId(op.id()).getPredecessorCount() == 0 : "move from stack must be in first block"; assert isVariable(move.getResult()) : "result of move must be a variable"; Debug.log("found move from stack slot %s to %s", slot, move.getResult()); } Interval interval = intervalFor(move.getResult()); interval.setSpillSlot(slot); interval.assignLocation(slot); } } } void addRegisterHint(final LIRInstruction op, final Value targetValue, OperandMode mode, EnumSet<OperandFlag> flags, final boolean hintAtDef) { if (flags.contains(OperandFlag.HINT) && isVariableOrRegister(targetValue)) { op.forEachRegisterHint(targetValue, mode, (registerHint, valueMode, valueFlags) -> { if (isVariableOrRegister(registerHint)) { Interval from = getOrCreateInterval((AllocatableValue) registerHint); Interval to = getOrCreateInterval((AllocatableValue) targetValue); /* hints always point from def to use */ if (hintAtDef) { to.setLocationHint(from); } else { from.setLocationHint(to); } Debug.log("operation at opId %d: added hint from interval %d to %d", op.id(), from.operandNumber, to.operandNumber); return registerHint; } return null; }); } } void buildIntervals() { try (Indent indent = Debug.logAndIndent("build intervals")) { InstructionValueConsumer outputConsumer = (op, operand, mode, flags) -> { if (isVariableOrRegister(operand)) { addDef((AllocatableValue) operand, op, registerPriorityOfOutputOperand(op), operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, true); } }; InstructionValueConsumer tempConsumer = (op, operand, mode, flags) -> { if (isVariableOrRegister(operand)) { addTemp((AllocatableValue) operand, op.id(), RegisterPriority.MustHaveRegister, operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, false); } }; InstructionValueConsumer aliveConsumer = (op, operand, mode, flags) -> { if (isVariableOrRegister(operand)) { RegisterPriority p = registerPriorityOfInputOperand(flags); int opId = op.id(); int blockFrom = getFirstLirInstructionId((blockForId(opId))); addUse((AllocatableValue) operand, blockFrom, opId + 1, p, operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, false); } }; InstructionValueConsumer inputConsumer = (op, operand, mode, flags) -> { if (isVariableOrRegister(operand)) { int opId = op.id(); int blockFrom = getFirstLirInstructionId((blockForId(opId))); RegisterPriority p = registerPriorityOfInputOperand(flags); addUse((AllocatableValue) operand, blockFrom, opId, p, operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, false); } }; InstructionValueConsumer stateProc = (op, operand, mode, flags) -> { int opId = op.id(); int blockFrom = getFirstLirInstructionId((blockForId(opId))); addUse((AllocatableValue) operand, blockFrom, opId + 1, RegisterPriority.None, operand.getLIRKind()); }; // create a list with all caller-save registers (cpu, fpu, xmm) Register[] callerSaveRegs = frameMap.registerConfig.getCallerSaveRegisters(); // iterate all blocks in reverse order for (int i = blockCount() - 1; i >= 0; i--) { AbstractBlock<?> block = blockAt(i); try (Indent indent2 = Debug.logAndIndent("handle block %d", block.getId())) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); final int blockFrom = getFirstLirInstructionId(block); int blockTo = getLastLirInstructionId(block); assert blockFrom == instructions.get(0).id(); assert blockTo == instructions.get(instructions.size() - 1).id(); // Update intervals for operands live at the end of this block; BitSet live = blockData.get(block).liveOut; for (int operandNum = live.nextSetBit(0); operandNum >= 0; operandNum = live.nextSetBit(operandNum + 1)) { assert live.get(operandNum) : "should not stop here otherwise"; AllocatableValue operand = intervalFor(operandNum).operand; Debug.log("live in %d: %s", operandNum, operand); addUse(operand, blockFrom, blockTo + 2, RegisterPriority.None, LIRKind.Illegal); // add special use positions for loop-end blocks when the // interval is used anywhere inside this loop. It's possible // that the block was part of a non-natural loop, so it might // have an invalid loop index. if (block.isLoopEnd() && block.getLoop() != null && isIntervalInLoop(operandNum, block.getLoop().getIndex())) { intervalFor(operandNum).addUsePos(blockTo + 1, RegisterPriority.LiveAtLoopEnd); } } // iterate all instructions of the block in reverse order. // definitions of intervals are processed before uses for (int j = instructions.size() - 1; j >= 0; j--) { final LIRInstruction op = instructions.get(j); final int opId = op.id(); try (Indent indent3 = Debug.logAndIndent("handle inst %d: %s", opId, op)) { // add a temp range for each register if operation destroys // caller-save registers if (op.destroysCallerSavedRegisters()) { for (Register r : callerSaveRegs) { if (attributes(r).isAllocatable()) { addTemp(r.asValue(), opId, RegisterPriority.None, LIRKind.Illegal); } } Debug.log("operation destroys all caller-save registers"); } op.visitEachOutput(outputConsumer); op.visitEachTemp(tempConsumer); op.visitEachAlive(aliveConsumer); op.visitEachInput(inputConsumer); // Add uses of live locals from interpreter's point of view for proper // debug information generation // Treat these operands as temp values (if the live range is extended // to a call site, the value would be in a register at // the call otherwise) op.visitEachState(stateProc); // special steps for some instructions (especially moves) handleMethodArguments(op); } } // end of instruction iteration } } // end of block iteration // add the range [0, 1] to all fixed intervals. // the register allocator need not handle unhandled fixed intervals for (Interval interval : intervals) { if (interval != null && isRegister(interval.operand)) { interval.addRange(0, 1); } } } } // * Phase 5: actual register allocation private static boolean isSorted(Interval[] intervals) { int from = -1; for (Interval interval : intervals) { assert interval != null; assert from <= interval.from(); from = interval.from(); } return true; } static Interval addToList(Interval first, Interval prev, Interval interval) { Interval newFirst = first; if (prev != null) { prev.next = interval; } else { newFirst = interval; } return newFirst; } Interval.Pair createUnhandledLists(IntervalPredicate isList1, IntervalPredicate isList2) { assert isSorted(sortedIntervals) : "interval list is not sorted"; Interval list1 = Interval.EndMarker; Interval list2 = Interval.EndMarker; Interval list1Prev = null; Interval list2Prev = null; Interval v; int n = sortedIntervals.length; for (int i = 0; i < n; i++) { v = sortedIntervals[i]; if (v == null) { continue; } if (isList1.apply(v)) { list1 = addToList(list1, list1Prev, v); list1Prev = v; } else if (isList2 == null || isList2.apply(v)) { list2 = addToList(list2, list2Prev, v); list2Prev = v; } } if (list1Prev != null) { list1Prev.next = Interval.EndMarker; } if (list2Prev != null) { list2Prev.next = Interval.EndMarker; } assert list1Prev == null || list1Prev.next == Interval.EndMarker : "linear list ends not with sentinel"; assert list2Prev == null || list2Prev.next == Interval.EndMarker : "linear list ends not with sentinel"; return new Interval.Pair(list1, list2); } void sortIntervalsBeforeAllocation() { int sortedLen = 0; for (Interval interval : intervals) { if (interval != null) { sortedLen++; } } Interval[] sortedList = new Interval[sortedLen]; int sortedIdx = 0; int sortedFromMax = -1; // special sorting algorithm: the original interval-list is almost sorted, // only some intervals are swapped. So this is much faster than a complete QuickSort for (Interval interval : intervals) { if (interval != null) { int from = interval.from(); if (sortedFromMax <= from) { sortedList[sortedIdx++] = interval; sortedFromMax = interval.from(); } else { // the assumption that the intervals are already sorted failed, // so this interval must be sorted in manually int j; for (j = sortedIdx - 1; j >= 0 && from < sortedList[j].from(); j--) { sortedList[j + 1] = sortedList[j]; } sortedList[j + 1] = interval; sortedIdx++; } } } sortedIntervals = sortedList; } void sortIntervalsAfterAllocation() { if (firstDerivedIntervalIndex == -1) { // no intervals have been added during allocation, so sorted list is already up to date return; } Interval[] oldList = sortedIntervals; Interval[] newList = Arrays.copyOfRange(intervals, firstDerivedIntervalIndex, intervalsSize); int oldLen = oldList.length; int newLen = newList.length; // conventional sort-algorithm for new intervals Arrays.sort(newList, (Interval a, Interval b) -> a.from() - b.from()); // merge old and new list (both already sorted) into one combined list Interval[] combinedList = new Interval[oldLen + newLen]; int oldIdx = 0; int newIdx = 0; while (oldIdx + newIdx < combinedList.length) { if (newIdx >= newLen || (oldIdx < oldLen && oldList[oldIdx].from() <= newList[newIdx].from())) { combinedList[oldIdx + newIdx] = oldList[oldIdx]; oldIdx++; } else { combinedList[oldIdx + newIdx] = newList[newIdx]; newIdx++; } } sortedIntervals = combinedList; } public void allocateRegisters() { try (Indent indent = Debug.logAndIndent("allocate registers")) { Interval precoloredIntervals; Interval notPrecoloredIntervals; Interval.Pair result = createUnhandledLists(IS_PRECOLORED_INTERVAL, IS_VARIABLE_INTERVAL); precoloredIntervals = result.first; notPrecoloredIntervals = result.second; // allocate cpu registers LinearScanWalker lsw; if (OptimizingLinearScanWalker.Options.LSRAOptimization.getValue()) { lsw = new OptimizingLinearScanWalker(this, precoloredIntervals, notPrecoloredIntervals); } else { lsw = new LinearScanWalker(this, precoloredIntervals, notPrecoloredIntervals); } lsw.walk(); lsw.finishAllocation(); } } // * Phase 6: resolve data flow // (insert moves at edges between blocks if intervals have been split) // wrapper for Interval.splitChildAtOpId that performs a bailout in product mode // instead of returning null Interval splitChildAtOpId(Interval interval, int opId, LIRInstruction.OperandMode mode) { Interval result = interval.getSplitChildAtOpId(opId, mode, this); if (result != null) { Debug.log("Split child at pos %d of interval %s is %s", opId, interval, result); return result; } throw new BailoutException("LinearScan: interval is null"); } Interval intervalAtBlockBegin(AbstractBlock<?> block, int operandNumber) { return splitChildAtOpId(intervalFor(operandNumber), getFirstLirInstructionId(block), LIRInstruction.OperandMode.DEF); } Interval intervalAtBlockEnd(AbstractBlock<?> block, int operandNumber) { return splitChildAtOpId(intervalFor(operandNumber), getLastLirInstructionId(block) + 1, LIRInstruction.OperandMode.DEF); } void resolveCollectMappings(AbstractBlock<?> fromBlock, AbstractBlock<?> toBlock, MoveResolver moveResolver) { assert moveResolver.checkEmpty(); int numOperands = operandSize(); BitSet liveAtEdge = blockData.get(toBlock).liveIn; // visit all variables for which the liveAtEdge bit is set for (int operandNum = liveAtEdge.nextSetBit(0); operandNum >= 0; operandNum = liveAtEdge.nextSetBit(operandNum + 1)) { assert operandNum < numOperands : "live information set for not exisiting interval"; assert blockData.get(fromBlock).liveOut.get(operandNum) && blockData.get(toBlock).liveIn.get(operandNum) : "interval not live at this edge"; Interval fromInterval = intervalAtBlockEnd(fromBlock, operandNum); Interval toInterval = intervalAtBlockBegin(toBlock, operandNum); if (fromInterval != toInterval && !fromInterval.location().equals(toInterval.location())) { // need to insert move instruction moveResolver.addMapping(fromInterval, toInterval); } } } void resolveFindInsertPos(AbstractBlock<?> fromBlock, AbstractBlock<?> toBlock, MoveResolver moveResolver) { if (fromBlock.getSuccessorCount() <= 1) { Debug.log("inserting moves at end of fromBlock B%d", fromBlock.getId()); List<LIRInstruction> instructions = ir.getLIRforBlock(fromBlock); LIRInstruction instr = instructions.get(instructions.size() - 1); if (instr instanceof StandardOp.JumpOp) { // insert moves before branch moveResolver.setInsertPosition(instructions, instructions.size() - 1); } else { moveResolver.setInsertPosition(instructions, instructions.size()); } } else { Debug.log("inserting moves at beginning of toBlock B%d", toBlock.getId()); if (DetailedAsserts.getValue()) { assert ir.getLIRforBlock(fromBlock).get(0) instanceof StandardOp.LabelOp : "block does not start with a label"; // because the number of predecessor edges matches the number of // successor edges, blocks which are reached by switch statements // may have be more than one predecessor but it will be guaranteed // that all predecessors will be the same. for (AbstractBlock<?> predecessor : toBlock.getPredecessors()) { assert fromBlock == predecessor : "all critical edges must be broken"; } } moveResolver.setInsertPosition(ir.getLIRforBlock(toBlock), 1); } } /** * Inserts necessary moves (spilling or reloading) at edges between blocks for intervals that * have been split. */ void resolveDataFlow() { try (Indent indent = Debug.logAndIndent("resolve data flow")) { int numBlocks = blockCount(); MoveResolver moveResolver = new MoveResolver(this); BitSet blockCompleted = new BitSet(numBlocks); BitSet alreadyResolved = new BitSet(numBlocks); for (AbstractBlock<?> block : sortedBlocks) { // check if block has only one predecessor and only one successor if (block.getPredecessorCount() == 1 && block.getSuccessorCount() == 1) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); assert instructions.get(0) instanceof StandardOp.LabelOp : "block must start with label"; assert instructions.get(instructions.size() - 1) instanceof StandardOp.JumpOp : "block with successor must end with unconditional jump"; // check if block is empty (only label and branch) if (instructions.size() == 2) { AbstractBlock<?> pred = block.getPredecessors().iterator().next(); AbstractBlock<?> sux = block.getSuccessors().iterator().next(); // prevent optimization of two consecutive blocks if (!blockCompleted.get(pred.getLinearScanNumber()) && !blockCompleted.get(sux.getLinearScanNumber())) { Debug.log(" optimizing empty block B%d (pred: B%d, sux: B%d)", block.getId(), pred.getId(), sux.getId()); blockCompleted.set(block.getLinearScanNumber()); // directly resolve between pred and sux (without looking // at the empty block // between) resolveCollectMappings(pred, sux, moveResolver); if (moveResolver.hasMappings()) { moveResolver.setInsertPosition(instructions, 1); moveResolver.resolveAndAppendMoves(); } } } } } for (AbstractBlock<?> fromBlock : sortedBlocks) { if (!blockCompleted.get(fromBlock.getLinearScanNumber())) { alreadyResolved.clear(); alreadyResolved.or(blockCompleted); for (AbstractBlock<?> toBlock : fromBlock.getSuccessors()) { // check for duplicate edges between the same blocks (can happen with switch // blocks) if (!alreadyResolved.get(toBlock.getLinearScanNumber())) { Debug.log("processing edge between B%d and B%d", fromBlock.getId(), toBlock.getId()); alreadyResolved.set(toBlock.getLinearScanNumber()); // collect all intervals that have been split between // fromBlock and toBlock resolveCollectMappings(fromBlock, toBlock, moveResolver); if (moveResolver.hasMappings()) { resolveFindInsertPos(fromBlock, toBlock, moveResolver); moveResolver.resolveAndAppendMoves(); } } } } } } } // * Phase 7: assign register numbers back to LIR // (includes computation of debug information and oop maps) static StackSlot canonicalSpillOpr(Interval interval) { assert interval.spillSlot() != null : "canonical spill slot not set"; return interval.spillSlot(); } /** * Assigns the allocated location for an LIR instruction operand back into the instruction. * * @param operand an LIR instruction operand * @param opId the id of the LIR instruction using {@code operand} * @param mode the usage mode for {@code operand} by the instruction * @return the location assigned for the operand */ private Value colorLirOperand(Variable operand, int opId, OperandMode mode) { Interval interval = intervalFor(operand); assert interval != null : "interval must exist"; if (opId != -1) { if (DetailedAsserts.getValue()) { AbstractBlock<?> block = blockForId(opId); if (block.getSuccessorCount() <= 1 && opId == getLastLirInstructionId(block)) { // check if spill moves could have been appended at the end of this block, but // before the branch instruction. So the split child information for this branch // would // be incorrect. LIRInstruction instr = ir.getLIRforBlock(block).get(ir.getLIRforBlock(block).size() - 1); if (instr instanceof StandardOp.JumpOp) { if (blockData.get(block).liveOut.get(operandNumber(operand))) { assert false : "can't get split child for the last branch of a block because the information would be incorrect (moves are inserted before the branch in resolveDataFlow)"; } } } } // operands are not changed when an interval is split during allocation, // so search the right interval here interval = splitChildAtOpId(interval, opId, mode); } if (isIllegal(interval.location()) && interval.canMaterialize()) { assert mode != OperandMode.DEF; return interval.getMaterializedValue(); } return interval.location(); } private boolean isMaterialized(AllocatableValue operand, int opId, OperandMode mode) { Interval interval = intervalFor(operand); assert interval != null : "interval must exist"; if (opId != -1) { // operands are not changed when an interval is split during allocation, // so search the right interval here interval = splitChildAtOpId(interval, opId, mode); } return isIllegal(interval.location()) && interval.canMaterialize(); } protected IntervalWalker initIntervalWalker(IntervalPredicate predicate) { // setup lists of potential oops for walking Interval oopIntervals; Interval nonOopIntervals; oopIntervals = createUnhandledLists(predicate, null).first; // intervals that have no oops inside need not to be processed. // to ensure a walking until the last instruction id, add a dummy interval // with a high operation id nonOopIntervals = new Interval(Value.ILLEGAL, -1); nonOopIntervals.addRange(Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1); return new IntervalWalker(this, oopIntervals, nonOopIntervals); } /** * Visits all intervals for a frame state. The frame state use this information to build the OOP * maps. */ void markFrameLocations(IntervalWalker iw, LIRInstruction op, LIRFrameState info) { Debug.log("creating oop map at opId %d", op.id()); // walk before the current operation . intervals that start at // the operation (i.e. output operands of the operation) are not // included in the oop map iw.walkBefore(op.id()); // TODO(je) we could pass this as parameter AbstractBlock<?> block = blockForId(op.id()); // Iterate through active intervals for (Interval interval = iw.activeLists.get(RegisterBinding.Fixed); interval != Interval.EndMarker; interval = interval.next) { Value operand = interval.operand; assert interval.currentFrom() <= op.id() && op.id() <= interval.currentTo() : "interval should not be active otherwise"; assert isVariable(interval.operand) : "fixed interval found"; // Check if this range covers the instruction. Intervals that // start or end at the current operation are not included in the // oop map, except in the case of patching moves. For patching // moves, any intervals which end at this instruction are included // in the oop map since we may safepoint while doing the patch // before we've consumed the inputs. if (op.id() < interval.currentTo() && !isIllegal(interval.location())) { // caller-save registers must not be included into oop-maps at calls assert !op.destroysCallerSavedRegisters() || !isRegister(operand) || !isCallerSave(operand) : "interval is in a caller-save register at a call . register will be overwritten"; info.markLocation(interval.location(), frameMap); // Spill optimization: when the stack value is guaranteed to be always correct, // then it must be added to the oop map even if the interval is currently in a // register int spillPos = interval.spillDefinitionPos(); if (interval.spillState() != SpillState.SpillInDominator) { if (interval.alwaysInMemory() && op.id() > interval.spillDefinitionPos() && !interval.location().equals(interval.spillSlot())) { assert interval.spillDefinitionPos() > 0 : "position not set correctly"; assert spillPos > 0 : "position not set correctly"; assert interval.spillSlot() != null : "no spill slot assigned"; assert !isRegister(interval.operand) : "interval is on stack : so stack slot is registered twice"; info.markLocation(interval.spillSlot(), frameMap); } } else { AbstractBlock<?> spillBlock = blockForId(spillPos); if (interval.alwaysInMemory() && !interval.location().equals(interval.spillSlot())) { if ((spillBlock.equals(block) && op.id() > spillPos) || dominates(spillBlock, block)) { assert spillPos > 0 : "position not set correctly"; assert interval.spillSlot() != null : "no spill slot assigned"; assert !isRegister(interval.operand) : "interval is on stack : so stack slot is registered twice"; info.markLocation(interval.spillSlot(), frameMap); } } } } } } private boolean isCallerSave(Value operand) { return attributes(asRegister(operand)).isCallerSave(); } private InstructionValueProcedure debugInfoProc = (op, operand, valueMode, flags) -> { int tempOpId = op.id(); OperandMode mode = OperandMode.USE; AbstractBlock<?> block = blockForId(tempOpId); if (block.getSuccessorCount() == 1 && tempOpId == getLastLirInstructionId(block)) { // generating debug information for the last instruction of a block. // if this instruction is a branch, spill moves are inserted before this branch // and so the wrong operand would be returned (spill moves at block boundaries // are not // considered in the live ranges of intervals) // Solution: use the first opId of the branch target block instead. final LIRInstruction instr = ir.getLIRforBlock(block).get(ir.getLIRforBlock(block).size() - 1); if (instr instanceof StandardOp.JumpOp) { if (blockData.get(block).liveOut.get(operandNumber(operand))) { tempOpId = getFirstLirInstructionId(block.getSuccessors().iterator().next()); mode = OperandMode.DEF; } } } // Get current location of operand // The operand must be live because debug information is considered when building // the intervals // if the interval is not live, colorLirOperand will cause an assert on failure Value result = colorLirOperand((Variable) operand, tempOpId, mode); assert !hasCall(tempOpId) || isStackSlot(result) || isConstant(result) || !isCallerSave(result) : "cannot have caller-save register operands at calls"; return result; }; private void computeDebugInfo(IntervalWalker iw, final LIRInstruction op, LIRFrameState info) { info.initDebugInfo(frameMap, !op.destroysCallerSavedRegisters() || !callKillsRegisters); markFrameLocations(iw, op, info); info.forEachState(op, debugInfoProc); info.finish(op, frameMap); } private void assignLocations(List<LIRInstruction> instructions, final IntervalWalker iw) { int numInst = instructions.size(); boolean hasDead = false; InstructionValueProcedure assignProc = (op, operand, mode, flags) -> isVariable(operand) ? colorLirOperand((Variable) operand, op.id(), mode) : operand; InstructionStateProcedure stateProc = (op, state) -> computeDebugInfo(iw, op, state); for (int j = 0; j < numInst; j++) { final LIRInstruction op = instructions.get(j); if (op == null) { // this can happen when spill-moves are removed in eliminateSpillMoves hasDead = true; continue; } // remove useless moves MoveOp move = null; if (op instanceof MoveOp) { move = (MoveOp) op; AllocatableValue result = move.getResult(); if (isVariable(result) && isMaterialized(result, op.id(), OperandMode.DEF)) { /* * This happens if a materializable interval is originally not spilled but then * kicked out in LinearScanWalker.splitForSpilling(). When kicking out such an * interval this move operation was already generated. */ instructions.set(j, null); hasDead = true; continue; } } op.forEachInput(assignProc); op.forEachAlive(assignProc); op.forEachTemp(assignProc); op.forEachOutput(assignProc); // compute reference map and debug information op.forEachState(stateProc); // remove useless moves if (move != null) { if (move.getInput().equals(move.getResult())) { instructions.set(j, null); hasDead = true; } } } if (hasDead) { // Remove null values from the list. instructions.removeAll(Collections.singleton(null)); } } private void assignLocations() { IntervalWalker iw = initIntervalWalker(IS_STACK_INTERVAL); try (Indent indent = Debug.logAndIndent("assign locations")) { for (AbstractBlock<?> block : sortedBlocks) { try (Indent indent2 = Debug.logAndIndent("assign locations in block B%d", block.getId())) { assignLocations(ir.getLIRforBlock(block), iw); } } } } public static void allocate(TargetDescription target, LIR lir, FrameMap frameMap) { new LinearScan(target, lir, frameMap).allocate(); } private void allocate() { /* * This is the point to enable debug logging for the whole register allocation. */ try (Indent indent = Debug.logAndIndent("LinearScan allocate")) { try (Scope s = Debug.scope("LifetimeAnalysis")) { numberInstructions(); printLir("Before register allocation", true); computeLocalLiveSets(); computeGlobalLiveSets(); buildIntervals(); sortIntervalsBeforeAllocation(); } catch (Throwable e) { throw Debug.handle(e); } try (Scope s = Debug.scope("RegisterAllocation")) { printIntervals("Before register allocation"); allocateRegisters(); } catch (Throwable e) { throw Debug.handle(e); } if (Options.LSRAOptimizeSpillPosition.getValue()) { try (Scope s = Debug.scope("OptimizeSpillPosition")) { optimizeSpillPosition(); } catch (Throwable e) { throw Debug.handle(e); } } try (Scope s = Debug.scope("ResolveDataFlow")) { resolveDataFlow(); } catch (Throwable e) { throw Debug.handle(e); } try (Scope s = Debug.scope("DebugInfo")) { frameMap.finish(); printIntervals("After register allocation"); printLir("After register allocation", true); sortIntervalsAfterAllocation(); if (DetailedAsserts.getValue()) { verify(); } try (Scope s1 = Debug.scope("EliminateSpillMove")) { eliminateSpillMoves(); } catch (Throwable e) { throw Debug.handle(e); } printLir("After spill move elimination", true); try (Scope s1 = Debug.scope("AssignLocations")) { assignLocations(); } catch (Throwable e) { throw Debug.handle(e); } if (DetailedAsserts.getValue()) { verifyIntervals(); } } catch (Throwable e) { throw Debug.handle(e); } printLir("After register number assignment", true); } } private DebugMetric betterSpillPos = Debug.metric("BetterSpillPosition"); private DebugMetric betterSpillPosWithLowerProbability = Debug.metric("BetterSpillPositionWithLowerProbability"); private void optimizeSpillPosition() { LIRInsertionBuffer[] insertionBuffers = new LIRInsertionBuffer[ir.linearScanOrder().size()]; for (Interval interval : intervals) { if (interval != null && interval.isSplitParent() && interval.spillState() == SpillState.SpillInDominator) { AbstractBlock<?> defBlock = blockForId(interval.spillDefinitionPos()); AbstractBlock<?> spillBlock = null; Interval firstSpillChild = null; try (Indent indent = Debug.logAndIndent("interval %s (%s)", interval, defBlock)) { for (Interval splitChild : interval.getSplitChildren()) { if (isStackSlot(splitChild.location())) { if (firstSpillChild == null || splitChild.from() < firstSpillChild.from()) { firstSpillChild = splitChild; } else { assert firstSpillChild.from() < splitChild.from(); } // iterate all blocks where the interval has use positions for (AbstractBlock<?> splitBlock : blocksForInterval(splitChild)) { if (dominates(defBlock, splitBlock)) { Debug.log("Split interval %s, block %s", splitChild, splitBlock); if (spillBlock == null) { spillBlock = splitBlock; } else { spillBlock = commonDominator(spillBlock, splitBlock); assert spillBlock != null; } } } } } if (spillBlock == null) { // no spill interval interval.setSpillState(SpillState.StoreAtDefinition); } else { // move out of loops if (defBlock.getLoopDepth() < spillBlock.getLoopDepth()) { spillBlock = moveSpillOutOfLoop(defBlock, spillBlock); } /* * If the spill block is the begin of the first split child (aka the value * is on the stack) spill in the dominator. */ assert firstSpillChild != null; if (!defBlock.equals(spillBlock) && spillBlock.equals(blockForId(firstSpillChild.from()))) { AbstractBlock<?> dom = spillBlock.getDominator(); Debug.log("Spill block (%s) is the beginning of a spill child -> use dominator (%s)", spillBlock, dom); spillBlock = dom; } if (!defBlock.equals(spillBlock)) { assert dominates(defBlock, spillBlock); betterSpillPos.increment(); Debug.log("Better spill position found (Block %s)", spillBlock); if (defBlock.probability() <= spillBlock.probability()) { // better spill block has the same probability -> do nothing interval.setSpillState(SpillState.StoreAtDefinition); } else { LIRInsertionBuffer insertionBuffer = insertionBuffers[spillBlock.getId()]; if (insertionBuffer == null) { insertionBuffer = new LIRInsertionBuffer(); insertionBuffers[spillBlock.getId()] = insertionBuffer; insertionBuffer.init(ir.getLIRforBlock(spillBlock)); } int spillOpId = getFirstLirInstructionId(spillBlock); // insert spill move AllocatableValue fromLocation = interval.getSplitChildAtOpId(spillOpId, OperandMode.DEF, this).location(); AllocatableValue toLocation = canonicalSpillOpr(interval); LIRInstruction move = ir.getSpillMoveFactory().createMove(toLocation, fromLocation); move.setId(DOMINATOR_SPILL_MOVE_ID); /* * We can use the insertion buffer directly because we always insert * at position 1. */ insertionBuffer.append(1, move); betterSpillPosWithLowerProbability.increment(); interval.setSpillDefinitionPos(spillOpId); } } else { // definition is the best choice interval.setSpillState(SpillState.StoreAtDefinition); } } } } } for (LIRInsertionBuffer insertionBuffer : insertionBuffers) { if (insertionBuffer != null) { assert insertionBuffer.initialized() : "Insertion buffer is nonnull but not initialized!"; insertionBuffer.finish(); } } } /** * Iterate over all {@link AbstractBlock blocks} of an interval. */ private class IntervalBlockIterator implements Iterator<AbstractBlock<?>> { Range range; AbstractBlock<?> block; public IntervalBlockIterator(Interval interval) { range = interval.first(); block = blockForId(range.from); } public AbstractBlock<?> next() { AbstractBlock<?> currentBlock = block; int nextBlockIndex = block.getLinearScanNumber() + 1; if (nextBlockIndex < sortedBlocks.size()) { block = sortedBlocks.get(nextBlockIndex); if (range.to <= getFirstLirInstructionId(block)) { range = range.next; if (range == Range.EndMarker) { block = null; } else { block = blockForId(range.from); } } } else { block = null; } return currentBlock; } public boolean hasNext() { return block != null; } } private Iterable<AbstractBlock<?>> blocksForInterval(Interval interval) { return new Iterable<AbstractBlock<?>>() { public Iterator<AbstractBlock<?>> iterator() { return new IntervalBlockIterator(interval); } }; } private static AbstractBlock<?> moveSpillOutOfLoop(AbstractBlock<?> defBlock, AbstractBlock<?> spillBlock) { int defLoopDepth = defBlock.getLoopDepth(); for (AbstractBlock<?> block = spillBlock.getDominator(); !defBlock.equals(block); block = block.getDominator()) { assert block != null : "spill block not dominated by definition block?"; if (block.getLoopDepth() <= defLoopDepth) { assert block.getLoopDepth() == defLoopDepth : "Cannot spill an interval outside of the loop where it is defined!"; return block; } } return defBlock; } void printIntervals(String label) { if (Debug.isLogEnabled()) { try (Indent indent = Debug.logAndIndent("intervals %s", label)) { for (Interval interval : intervals) { if (interval != null) { Debug.log("%s", interval.logString(this)); } } try (Indent indent2 = Debug.logAndIndent("Basic Blocks")) { for (int i = 0; i < blockCount(); i++) { AbstractBlock<?> block = blockAt(i); Debug.log("B%d [%d, %d, %s] ", block.getId(), getFirstLirInstructionId(block), getLastLirInstructionId(block), block.getLoop()); } } } } Debug.dump(Arrays.copyOf(intervals, intervalsSize), label); } void printLir(String label, @SuppressWarnings("unused") boolean hirValid) { Debug.dump(ir, label); } boolean verify() { // (check that all intervals have a correct register and that no registers are overwritten) verifyIntervals(); verifyRegisters(); Debug.log("no errors found"); return true; } private void verifyRegisters() { // Enable this logging to get output for the verification process. try (Indent indent = Debug.logAndIndent("verifying register allocation")) { RegisterVerifier verifier = new RegisterVerifier(this); verifier.verify(blockAt(0)); } } void verifyIntervals() { try (Indent indent = Debug.logAndIndent("verifying intervals")) { int len = intervalsSize; for (int i = 0; i < len; i++) { Interval i1 = intervals[i]; if (i1 == null) { continue; } i1.checkSplitChildren(); if (i1.operandNumber != i) { Debug.log("Interval %d is on position %d in list", i1.operandNumber, i); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } if (isVariable(i1.operand) && i1.kind().equals(LIRKind.Illegal)) { Debug.log("Interval %d has no type assigned", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } if (i1.location() == null) { Debug.log("Interval %d has no register assigned", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } if (i1.first() == Range.EndMarker) { Debug.log("Interval %d has no Range", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } for (Range r = i1.first(); r != Range.EndMarker; r = r.next) { if (r.from >= r.to) { Debug.log("Interval %d has zero length range", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } } for (int j = i + 1; j < len; j++) { Interval i2 = intervals[j]; if (i2 == null) { continue; } // special intervals that are created in MoveResolver // . ignore them because the range information has no meaning there if (i1.from() == 1 && i1.to() == 2) { continue; } if (i2.from() == 1 && i2.to() == 2) { continue; } Value l1 = i1.location(); Value l2 = i2.location(); if (i1.intersects(i2) && !isIllegal(l1) && (l1.equals(l2))) { if (DetailedAsserts.getValue()) { Debug.log("Intervals %d and %d overlap and have the same register assigned", i1.operandNumber, i2.operandNumber); Debug.log(i1.logString(this)); Debug.log(i2.logString(this)); } throw new BailoutException(""); } } } } } class CheckConsumer implements ValueConsumer { boolean ok; Interval curInterval; @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isRegister(operand)) { if (intervalFor(operand) == curInterval) { ok = true; } } } } void verifyNoOopsInFixedIntervals() { try (Indent indent = Debug.logAndIndent("verifying that no oops are in fixed intervals *")) { CheckConsumer checkConsumer = new CheckConsumer(); Interval fixedIntervals; Interval otherIntervals; fixedIntervals = createUnhandledLists(IS_PRECOLORED_INTERVAL, null).first; // to ensure a walking until the last instruction id, add a dummy interval // with a high operation id otherIntervals = new Interval(Value.ILLEGAL, -1); otherIntervals.addRange(Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1); IntervalWalker iw = new IntervalWalker(this, fixedIntervals, otherIntervals); for (AbstractBlock<?> block : sortedBlocks) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); for (int j = 0; j < instructions.size(); j++) { LIRInstruction op = instructions.get(j); if (op.hasState()) { iw.walkBefore(op.id()); boolean checkLive = true; // Make sure none of the fixed registers is live across an // oopmap since we can't handle that correctly. if (checkLive) { for (Interval interval = iw.activeLists.get(RegisterBinding.Fixed); interval != Interval.EndMarker; interval = interval.next) { if (interval.currentTo() > op.id() + 1) { // This interval is live out of this op so make sure // that this interval represents some value that's // referenced by this op either as an input or output. checkConsumer.curInterval = interval; checkConsumer.ok = false; op.visitEachInput(checkConsumer); op.visitEachAlive(checkConsumer); op.visitEachTemp(checkConsumer); op.visitEachOutput(checkConsumer); assert checkConsumer.ok : "fixed intervals should never be live across an oopmap point"; } } } } } } } } /** * Returns a value for a interval definition, which can be used for re-materialization. * * @param op An instruction which defines a value * @param operand The destination operand of the instruction * @param interval The interval for this defined value. * @return Returns the value which is moved to the instruction and which can be reused at all * reload-locations in case the interval of this instruction is spilled. Currently this * can only be a {@link Constant}. */ public static Constant getMaterializedValue(LIRInstruction op, Value operand, Interval interval) { if (op instanceof MoveOp) { MoveOp move = (MoveOp) op; if (move.getInput() instanceof Constant) { /* * Check if the interval has any uses which would accept an stack location (priority * == ShouldHaveRegister). Rematerialization of such intervals can result in a * degradation, because rematerialization always inserts a constant load, even if * the value is not needed in a register. */ Interval.UsePosList usePosList = interval.usePosList(); int numUsePos = usePosList.size(); for (int useIdx = 0; useIdx < numUsePos; useIdx++) { Interval.RegisterPriority priority = usePosList.registerPriority(useIdx); if (priority == Interval.RegisterPriority.ShouldHaveRegister) { return null; } } return (Constant) move.getInput(); } } return null; } }
graal/com.oracle.graal.compiler/src/com/oracle/graal/compiler/alloc/LinearScan.java
/* * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.alloc; import static com.oracle.graal.api.code.CodeUtil.*; import static com.oracle.graal.api.code.ValueUtil.*; import static com.oracle.graal.compiler.GraalDebugConfig.*; import static com.oracle.graal.compiler.common.cfg.AbstractControlFlowGraph.*; import static com.oracle.graal.lir.LIRValueUtil.*; import java.util.*; import com.oracle.graal.alloc.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.alloc.Interval.RegisterBinding; import com.oracle.graal.compiler.alloc.Interval.RegisterPriority; import com.oracle.graal.compiler.alloc.Interval.SpillState; import com.oracle.graal.compiler.common.*; import com.oracle.graal.compiler.common.cfg.*; import com.oracle.graal.compiler.gen.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.Debug.Scope; import com.oracle.graal.lir.*; import com.oracle.graal.lir.LIRInstruction.OperandFlag; import com.oracle.graal.lir.LIRInstruction.OperandMode; import com.oracle.graal.lir.StandardOp.MoveOp; import com.oracle.graal.nodes.*; import com.oracle.graal.options.*; import com.oracle.graal.phases.util.*; /** * An implementation of the linear scan register allocator algorithm described in <a * href="http://doi.acm.org/10.1145/1064979.1064998" * >"Optimized Interval Splitting in a Linear Scan Register Allocator"</a> by Christian Wimmer and * Hanspeter Moessenboeck. */ public final class LinearScan { final TargetDescription target; final LIR ir; final FrameMap frameMap; final RegisterAttributes[] registerAttributes; final Register[] registers; boolean callKillsRegisters; public static final int DOMINATOR_SPILL_MOVE_ID = -2; private static final int SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT = 1; public static class Options { // @formatter:off @Option(help = "Enable spill position optimization") public static final OptionValue<Boolean> LSRAOptimizeSpillPosition = new OptionValue<>(true); // @formatter:on } public static class BlockData { /** * Bit map specifying which operands are live upon entry to this block. These are values * used in this block or any of its successors where such value are not defined in this * block. The bit index of an operand is its {@linkplain LinearScan#operandNumber(Value) * operand number}. */ public BitSet liveIn; /** * Bit map specifying which operands are live upon exit from this block. These are values * used in a successor block that are either defined in this block or were live upon entry * to this block. The bit index of an operand is its * {@linkplain LinearScan#operandNumber(Value) operand number}. */ public BitSet liveOut; /** * Bit map specifying which operands are used (before being defined) in this block. That is, * these are the values that are live upon entry to the block. The bit index of an operand * is its {@linkplain LinearScan#operandNumber(Value) operand number}. */ public BitSet liveGen; /** * Bit map specifying which operands are defined/overwritten in this block. The bit index of * an operand is its {@linkplain LinearScan#operandNumber(Value) operand number}. */ public BitSet liveKill; } public final BlockMap<BlockData> blockData; /** * List of blocks in linear-scan order. This is only correct as long as the CFG does not change. */ final List<? extends AbstractBlock<?>> sortedBlocks; /** * Map from {@linkplain #operandNumber(Value) operand numbers} to intervals. */ Interval[] intervals; /** * The number of valid entries in {@link #intervals}. */ int intervalsSize; /** * The index of the first entry in {@link #intervals} for a * {@linkplain #createDerivedInterval(Interval) derived interval}. */ int firstDerivedIntervalIndex = -1; /** * Intervals sorted by {@link Interval#from()}. */ Interval[] sortedIntervals; /** * Map from an instruction {@linkplain LIRInstruction#id id} to the instruction. Entries should * be retrieved with {@link #instructionForId(int)} as the id is not simply an index into this * array. */ LIRInstruction[] opIdToInstructionMap; /** * Map from an instruction {@linkplain LIRInstruction#id id} to the {@linkplain AbstractBlock * block} containing the instruction. Entries should be retrieved with {@link #blockForId(int)} * as the id is not simply an index into this array. */ AbstractBlock<?>[] opIdToBlockMap; /** * Bit set for each variable that is contained in each loop. */ BitMap2D intervalInLoop; /** * The {@linkplain #operandNumber(Value) number} of the first variable operand allocated. */ private final int firstVariableNumber; public LinearScan(TargetDescription target, LIR ir, FrameMap frameMap) { this.target = target; this.ir = ir; this.frameMap = frameMap; this.sortedBlocks = ir.linearScanOrder(); this.registerAttributes = frameMap.registerConfig.getAttributesMap(); this.registers = target.arch.getRegisters(); this.firstVariableNumber = registers.length; this.blockData = new BlockMap<>(ir.getControlFlowGraph()); } public int getFirstLirInstructionId(AbstractBlock<?> block) { int result = ir.getLIRforBlock(block).get(0).id(); assert result >= 0; return result; } public int getLastLirInstructionId(AbstractBlock<?> block) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); int result = instructions.get(instructions.size() - 1).id(); assert result >= 0; return result; } public static boolean isVariableOrRegister(Value value) { return isVariable(value) || isRegister(value); } /** * Converts an operand (variable or register) to an index in a flat address space covering all * the {@linkplain Variable variables} and {@linkplain RegisterValue registers} being processed * by this allocator. */ private int operandNumber(Value operand) { if (isRegister(operand)) { int number = asRegister(operand).number; assert number < firstVariableNumber; return number; } assert isVariable(operand) : operand; return firstVariableNumber + ((Variable) operand).index; } /** * Gets the number of operands. This value will increase by 1 for new variable. */ private int operandSize() { return firstVariableNumber + ir.numVariables(); } /** * Gets the highest operand number for a register operand. This value will never change. */ public int maxRegisterNumber() { return firstVariableNumber - 1; } static final IntervalPredicate IS_PRECOLORED_INTERVAL = new IntervalPredicate() { @Override public boolean apply(Interval i) { return isRegister(i.operand); } }; static final IntervalPredicate IS_VARIABLE_INTERVAL = new IntervalPredicate() { @Override public boolean apply(Interval i) { return isVariable(i.operand); } }; static final IntervalPredicate IS_STACK_INTERVAL = new IntervalPredicate() { @Override public boolean apply(Interval i) { return !isRegister(i.operand); } }; /** * Gets an object describing the attributes of a given register according to this register * configuration. */ RegisterAttributes attributes(Register reg) { return registerAttributes[reg.number]; } void assignSpillSlot(Interval interval) { // assign the canonical spill slot of the parent (if a part of the interval // is already spilled) or allocate a new spill slot if (interval.canMaterialize()) { interval.assignLocation(Value.ILLEGAL); } else if (interval.spillSlot() != null) { interval.assignLocation(interval.spillSlot()); } else { StackSlot slot = frameMap.allocateSpillSlot(interval.kind()); interval.setSpillSlot(slot); interval.assignLocation(slot); } } /** * Creates a new interval. * * @param operand the operand for the interval * @return the created interval */ Interval createInterval(AllocatableValue operand) { assert isLegal(operand); int operandNumber = operandNumber(operand); Interval interval = new Interval(operand, operandNumber); assert operandNumber < intervalsSize; assert intervals[operandNumber] == null; intervals[operandNumber] = interval; return interval; } /** * Creates an interval as a result of splitting or spilling another interval. * * @param source an interval being split of spilled * @return a new interval derived from {@code source} */ Interval createDerivedInterval(Interval source) { if (firstDerivedIntervalIndex == -1) { firstDerivedIntervalIndex = intervalsSize; } if (intervalsSize == intervals.length) { intervals = Arrays.copyOf(intervals, intervals.length + (intervals.length >> SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT)); } intervalsSize++; Variable variable = new Variable(source.kind(), ir.nextVariable()); Interval interval = createInterval(variable); assert intervals[intervalsSize - 1] == interval; return interval; } // access to block list (sorted in linear scan order) int blockCount() { return sortedBlocks.size(); } AbstractBlock<?> blockAt(int index) { return sortedBlocks.get(index); } /** * Gets the size of the {@link BlockData#liveIn} and {@link BlockData#liveOut} sets for a basic * block. These sets do not include any operands allocated as a result of creating * {@linkplain #createDerivedInterval(Interval) derived intervals}. */ int liveSetSize() { return firstDerivedIntervalIndex == -1 ? operandSize() : firstDerivedIntervalIndex; } int numLoops() { return ir.getControlFlowGraph().getLoops().size(); } boolean isIntervalInLoop(int interval, int loop) { return intervalInLoop.at(interval, loop); } Interval intervalFor(int operandNumber) { return intervals[operandNumber]; } Interval intervalFor(Value operand) { int operandNumber = operandNumber(operand); assert operandNumber < intervalsSize; return intervals[operandNumber]; } Interval getOrCreateInterval(AllocatableValue operand) { Interval ret = intervalFor(operand); if (ret == null) { return createInterval(operand); } else { return ret; } } /** * Gets the highest instruction id allocated by this object. */ int maxOpId() { assert opIdToInstructionMap.length > 0 : "no operations"; return (opIdToInstructionMap.length - 1) << 1; } /** * Converts an {@linkplain LIRInstruction#id instruction id} to an instruction index. All LIR * instructions in a method have an index one greater than their linear-scan order predecesor * with the first instruction having an index of 0. */ static int opIdToIndex(int opId) { return opId >> 1; } /** * Retrieves the {@link LIRInstruction} based on its {@linkplain LIRInstruction#id id}. * * @param opId an instruction {@linkplain LIRInstruction#id id} * @return the instruction whose {@linkplain LIRInstruction#id} {@code == id} */ LIRInstruction instructionForId(int opId) { assert isEven(opId) : "opId not even"; LIRInstruction instr = opIdToInstructionMap[opIdToIndex(opId)]; assert instr.id() == opId; return instr; } /** * Gets the block containing a given instruction. * * @param opId an instruction {@linkplain LIRInstruction#id id} * @return the block containing the instruction denoted by {@code opId} */ AbstractBlock<?> blockForId(int opId) { assert opIdToBlockMap.length > 0 && opId >= 0 && opId <= maxOpId() + 1 : "opId out of range"; return opIdToBlockMap[opIdToIndex(opId)]; } boolean isBlockBegin(int opId) { return opId == 0 || blockForId(opId) != blockForId(opId - 1); } boolean coversBlockBegin(int opId1, int opId2) { return blockForId(opId1) != blockForId(opId2); } /** * Determines if an {@link LIRInstruction} destroys all caller saved registers. * * @param opId an instruction {@linkplain LIRInstruction#id id} * @return {@code true} if the instruction denoted by {@code id} destroys all caller saved * registers. */ boolean hasCall(int opId) { assert isEven(opId) : "opId not even"; return instructionForId(opId).destroysCallerSavedRegisters(); } /** * Eliminates moves from register to stack if the stack slot is known to be correct. */ void changeSpillDefinitionPos(Interval interval, int defPos) { assert interval.isSplitParent() : "can only be called for split parents"; switch (interval.spillState()) { case NoDefinitionFound: assert interval.spillDefinitionPos() == -1 : "must no be set before"; interval.setSpillDefinitionPos(defPos); interval.setSpillState(SpillState.NoSpillStore); break; case NoSpillStore: assert defPos <= interval.spillDefinitionPos() : "positions are processed in reverse order when intervals are created"; if (defPos < interval.spillDefinitionPos() - 2) { // second definition found, so no spill optimization possible for this interval interval.setSpillState(SpillState.NoOptimization); } else { // two consecutive definitions (because of two-operand LIR form) assert blockForId(defPos) == blockForId(interval.spillDefinitionPos()) : "block must be equal"; } break; case NoOptimization: // nothing to do break; default: throw new BailoutException("other states not allowed at this time"); } } // called during register allocation void changeSpillState(Interval interval, int spillPos) { switch (interval.spillState()) { case NoSpillStore: { int defLoopDepth = blockForId(interval.spillDefinitionPos()).getLoopDepth(); int spillLoopDepth = blockForId(spillPos).getLoopDepth(); if (defLoopDepth < spillLoopDepth) { // the loop depth of the spilling position is higher then the loop depth // at the definition of the interval . move write to memory out of loop. if (Options.LSRAOptimizeSpillPosition.getValue()) { // find best spill position in dominator the tree interval.setSpillState(SpillState.SpillInDominator); } else { // store at definition of the interval interval.setSpillState(SpillState.StoreAtDefinition); } } else { // the interval is currently spilled only once, so for now there is no // reason to store the interval at the definition interval.setSpillState(SpillState.OneSpillStore); } break; } case OneSpillStore: { if (Options.LSRAOptimizeSpillPosition.getValue()) { // the interval is spilled more then once interval.setSpillState(SpillState.SpillInDominator); } else { // it is better to store it to // memory at the definition interval.setSpillState(SpillState.StoreAtDefinition); } break; } case SpillInDominator: case StoreAtDefinition: case StartInMemory: case NoOptimization: case NoDefinitionFound: // nothing to do break; default: throw new BailoutException("other states not allowed at this time"); } } abstract static class IntervalPredicate { abstract boolean apply(Interval i); } private static final IntervalPredicate mustStoreAtDefinition = new IntervalPredicate() { @Override public boolean apply(Interval i) { return i.isSplitParent() && i.spillState() == SpillState.StoreAtDefinition; } }; // called once before assignment of register numbers void eliminateSpillMoves() { try (Indent indent = Debug.logAndIndent("Eliminating unnecessary spill moves")) { // collect all intervals that must be stored after their definition. // the list is sorted by Interval.spillDefinitionPos Interval interval; interval = createUnhandledLists(mustStoreAtDefinition, null).first; if (DetailedAsserts.getValue()) { checkIntervals(interval); } LIRInsertionBuffer insertionBuffer = new LIRInsertionBuffer(); for (AbstractBlock<?> block : sortedBlocks) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); int numInst = instructions.size(); // iterate all instructions of the block. skip the first // because it is always a label for (int j = 1; j < numInst; j++) { LIRInstruction op = instructions.get(j); int opId = op.id(); if (opId == -1) { MoveOp move = (MoveOp) op; // remove move from register to stack if the stack slot is guaranteed to be // correct. // only moves that have been inserted by LinearScan can be removed. assert isVariable(move.getResult()) : "LinearScan inserts only moves to variables"; Interval curInterval = intervalFor(move.getResult()); if (!isRegister(curInterval.location()) && curInterval.alwaysInMemory()) { // move target is a stack slot that is always correct, so eliminate // instruction if (Debug.isLogEnabled()) { Debug.log("eliminating move from interval %d to %d", operandNumber(move.getInput()), operandNumber(move.getResult())); } // null-instructions are deleted by assignRegNum instructions.set(j, null); } } else { // insert move from register to stack just after // the beginning of the interval assert interval == Interval.EndMarker || interval.spillDefinitionPos() >= opId : "invalid order"; assert interval == Interval.EndMarker || (interval.isSplitParent() && interval.spillState() == SpillState.StoreAtDefinition) : "invalid interval"; while (interval != Interval.EndMarker && interval.spillDefinitionPos() == opId) { if (!interval.canMaterialize()) { if (!insertionBuffer.initialized()) { // prepare insertion buffer (appended when all instructions in // the block are processed) insertionBuffer.init(instructions); } AllocatableValue fromLocation = interval.location(); AllocatableValue toLocation = canonicalSpillOpr(interval); assert isRegister(fromLocation) : "from operand must be a register but is: " + fromLocation + " toLocation=" + toLocation + " spillState=" + interval.spillState(); assert isStackSlot(toLocation) : "to operand must be a stack slot"; insertionBuffer.append(j + 1, ir.getSpillMoveFactory().createMove(toLocation, fromLocation)); Debug.log("inserting move after definition of interval %d to stack slot %s at opId %d", interval.operandNumber, interval.spillSlot(), opId); } interval = interval.next; } } } // end of instruction iteration if (insertionBuffer.initialized()) { insertionBuffer.finish(); } } // end of block iteration assert interval == Interval.EndMarker : "missed an interval"; } } private static void checkIntervals(Interval interval) { Interval prev = null; Interval temp = interval; while (temp != Interval.EndMarker) { assert temp.spillDefinitionPos() > 0 : "invalid spill definition pos"; if (prev != null) { assert temp.from() >= prev.from() : "intervals not sorted"; assert temp.spillDefinitionPos() >= prev.spillDefinitionPos() : "when intervals are sorted by from : then they must also be sorted by spillDefinitionPos"; } assert temp.spillSlot() != null || temp.canMaterialize() : "interval has no spill slot assigned"; assert temp.spillDefinitionPos() >= temp.from() : "invalid order"; assert temp.spillDefinitionPos() <= temp.from() + 2 : "only intervals defined once at their start-pos can be optimized"; Debug.log("interval %d (from %d to %d) must be stored at %d", temp.operandNumber, temp.from(), temp.to(), temp.spillDefinitionPos()); prev = temp; temp = temp.next; } } /** * Numbers all instructions in all blocks. The numbering follows the * {@linkplain ComputeBlockOrder linear scan order}. */ void numberInstructions() { intervalsSize = operandSize(); intervals = new Interval[intervalsSize + (intervalsSize >> SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT)]; ValueConsumer setVariableConsumer = new ValueConsumer() { @Override public void visitValue(Value value, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariable(value)) { getOrCreateInterval(asVariable(value)); } } }; // Assign IDs to LIR nodes and build a mapping, lirOps, from ID to LIRInstruction node. int numInstructions = 0; for (AbstractBlock<?> block : sortedBlocks) { numInstructions += ir.getLIRforBlock(block).size(); } // initialize with correct length opIdToInstructionMap = new LIRInstruction[numInstructions]; opIdToBlockMap = new AbstractBlock<?>[numInstructions]; int opId = 0; int index = 0; for (AbstractBlock<?> block : sortedBlocks) { blockData.put(block, new BlockData()); List<LIRInstruction> instructions = ir.getLIRforBlock(block); int numInst = instructions.size(); for (int j = 0; j < numInst; j++) { LIRInstruction op = instructions.get(j); op.setId(opId); opIdToInstructionMap[index] = op; opIdToBlockMap[index] = block; assert instructionForId(opId) == op : "must match"; op.visitEachTemp(setVariableConsumer); op.visitEachOutput(setVariableConsumer); index++; opId += 2; // numbering of lirOps by two } } assert index == numInstructions : "must match"; assert (index << 1) == opId : "must match: " + (index << 1); } /** * Computes local live sets (i.e. {@link BlockData#liveGen} and {@link BlockData#liveKill}) * separately for each block. */ void computeLocalLiveSets() { int liveSize = liveSetSize(); intervalInLoop = new BitMap2D(operandSize(), numLoops()); // iterate all blocks for (final AbstractBlock<?> block : sortedBlocks) { try (Indent indent = Debug.logAndIndent("compute local live sets for block %d", block.getId())) { final BitSet liveGen = new BitSet(liveSize); final BitSet liveKill = new BitSet(liveSize); List<LIRInstruction> instructions = ir.getLIRforBlock(block); int numInst = instructions.size(); ValueConsumer useConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariable(operand)) { int operandNum = operandNumber(operand); if (!liveKill.get(operandNum)) { liveGen.set(operandNum); Debug.log("liveGen for operand %d", operandNum); } if (block.getLoop() != null) { intervalInLoop.setBit(operandNum, block.getLoop().getIndex()); } } if (DetailedAsserts.getValue()) { verifyInput(block, liveKill, operand); } } }; ValueConsumer stateConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { int operandNum = operandNumber(operand); if (!liveKill.get(operandNum)) { liveGen.set(operandNum); Debug.log("liveGen in state for operand %d", operandNum); } } }; ValueConsumer defConsumer = new ValueConsumer() { @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariable(operand)) { int varNum = operandNumber(operand); liveKill.set(varNum); Debug.log("liveKill for operand %d", varNum); if (block.getLoop() != null) { intervalInLoop.setBit(varNum, block.getLoop().getIndex()); } } if (DetailedAsserts.getValue()) { // fixed intervals are never live at block boundaries, so // they need not be processed in live sets // process them only in debug mode so that this can be checked verifyTemp(liveKill, operand); } } }; // iterate all instructions of the block for (int j = 0; j < numInst; j++) { final LIRInstruction op = instructions.get(j); try (Indent indent2 = Debug.logAndIndent("handle op %d", op.id())) { op.visitEachInput(useConsumer); op.visitEachAlive(useConsumer); // Add uses of live locals from interpreter's point of view for proper debug // information generation op.visitEachState(stateConsumer); op.visitEachTemp(defConsumer); op.visitEachOutput(defConsumer); } } // end of instruction iteration BlockData blockSets = blockData.get(block); blockSets.liveGen = liveGen; blockSets.liveKill = liveKill; blockSets.liveIn = new BitSet(liveSize); blockSets.liveOut = new BitSet(liveSize); Debug.log("liveGen B%d %s", block.getId(), blockSets.liveGen); Debug.log("liveKill B%d %s", block.getId(), blockSets.liveKill); } } // end of block iteration } private void verifyTemp(BitSet liveKill, Value operand) { // fixed intervals are never live at block boundaries, so // they need not be processed in live sets // process them only in debug mode so that this can be checked if (isRegister(operand)) { if (isProcessed(operand)) { liveKill.set(operandNumber(operand)); } } } private void verifyInput(AbstractBlock<?> block, BitSet liveKill, Value operand) { // fixed intervals are never live at block boundaries, so // they need not be processed in live sets. // this is checked by these assertions to be sure about it. // the entry block may have incoming // values in registers, which is ok. if (isRegister(operand) && block != ir.getControlFlowGraph().getStartBlock()) { if (isProcessed(operand)) { assert liveKill.get(operandNumber(operand)) : "using fixed register that is not defined in this block"; } } } /** * Performs a backward dataflow analysis to compute global live sets (i.e. * {@link BlockData#liveIn} and {@link BlockData#liveOut}) for each block. */ void computeGlobalLiveSets() { try (Indent indent = Debug.logAndIndent("compute global live sets")) { int numBlocks = blockCount(); boolean changeOccurred; boolean changeOccurredInBlock; int iterationCount = 0; BitSet liveOut = new BitSet(liveSetSize()); // scratch set for calculations // Perform a backward dataflow analysis to compute liveOut and liveIn for each block. // The loop is executed until a fixpoint is reached (no changes in an iteration) do { changeOccurred = false; try (Indent indent2 = Debug.logAndIndent("new iteration %d", iterationCount)) { // iterate all blocks in reverse order for (int i = numBlocks - 1; i >= 0; i--) { AbstractBlock<?> block = blockAt(i); BlockData blockSets = blockData.get(block); changeOccurredInBlock = false; // liveOut(block) is the union of liveIn(sux), for successors sux of block int n = block.getSuccessorCount(); if (n > 0) { liveOut.clear(); // block has successors if (n > 0) { for (AbstractBlock<?> successor : block.getSuccessors()) { liveOut.or(blockData.get(successor).liveIn); } } if (!blockSets.liveOut.equals(liveOut)) { // A change occurred. Swap the old and new live out // sets to avoid copying. BitSet temp = blockSets.liveOut; blockSets.liveOut = liveOut; liveOut = temp; changeOccurred = true; changeOccurredInBlock = true; } } if (iterationCount == 0 || changeOccurredInBlock) { // liveIn(block) is the union of liveGen(block) with (liveOut(block) & // !liveKill(block)) // note: liveIn has to be computed only in first iteration // or if liveOut has changed! BitSet liveIn = blockSets.liveIn; liveIn.clear(); liveIn.or(blockSets.liveOut); liveIn.andNot(blockSets.liveKill); liveIn.or(blockSets.liveGen); Debug.log("block %d: livein = %s, liveout = %s", block.getId(), liveIn, blockSets.liveOut); } } iterationCount++; if (changeOccurred && iterationCount > 50) { throw new BailoutException("too many iterations in computeGlobalLiveSets"); } } } while (changeOccurred); if (DetailedAsserts.getValue()) { verifyLiveness(); } // check that the liveIn set of the first block is empty AbstractBlock<?> startBlock = ir.getControlFlowGraph().getStartBlock(); if (blockData.get(startBlock).liveIn.cardinality() != 0) { if (DetailedAsserts.getValue()) { reportFailure(numBlocks); } // bailout if this occurs in product mode. throw new GraalInternalError("liveIn set of first block must be empty: " + blockData.get(startBlock).liveIn); } } } private static NodeLIRBuilder getNodeLIRGeneratorFromDebugContext() { if (Debug.isEnabled()) { NodeLIRBuilder lirGen = Debug.contextLookup(NodeLIRBuilder.class); assert lirGen != null; return lirGen; } return null; } private static ValueNode getValueForOperandFromDebugContext(Value value) { NodeLIRBuilder gen = getNodeLIRGeneratorFromDebugContext(); if (gen != null) { return gen.valueForOperand(value); } return null; } private void reportFailure(int numBlocks) { try (Scope s = Debug.forceLog()) { try (Indent indent = Debug.logAndIndent("report failure")) { BitSet startBlockLiveIn = blockData.get(ir.getControlFlowGraph().getStartBlock()).liveIn; try (Indent indent2 = Debug.logAndIndent("Error: liveIn set of first block must be empty (when this fails, variables are used before they are defined):")) { for (int operandNum = startBlockLiveIn.nextSetBit(0); operandNum >= 0; operandNum = startBlockLiveIn.nextSetBit(operandNum + 1)) { Interval interval = intervalFor(operandNum); if (interval != null) { Value operand = interval.operand; Debug.log("var %d; operand=%s; node=%s", operandNum, operand, getValueForOperandFromDebugContext(operand)); } else { Debug.log("var %d; missing operand", operandNum); } } } // print some additional information to simplify debugging for (int operandNum = startBlockLiveIn.nextSetBit(0); operandNum >= 0; operandNum = startBlockLiveIn.nextSetBit(operandNum + 1)) { Interval interval = intervalFor(operandNum); Value operand = null; ValueNode valueForOperandFromDebugContext = null; if (interval != null) { operand = interval.operand; valueForOperandFromDebugContext = getValueForOperandFromDebugContext(operand); } try (Indent indent2 = Debug.logAndIndent("---- Detailed information for var %d; operand=%s; node=%s ----", operandNum, operand, valueForOperandFromDebugContext)) { Deque<AbstractBlock<?>> definedIn = new ArrayDeque<>(); HashSet<AbstractBlock<?>> usedIn = new HashSet<>(); for (AbstractBlock<?> block : sortedBlocks) { if (blockData.get(block).liveGen.get(operandNum)) { usedIn.add(block); try (Indent indent3 = Debug.logAndIndent("used in block B%d", block.getId())) { for (LIRInstruction ins : ir.getLIRforBlock(block)) { try (Indent indent4 = Debug.logAndIndent("%d: %s", ins.id(), ins)) { ins.forEachState((liveStateOperand, mode, flags) -> { Debug.log("operand=%s", liveStateOperand); return liveStateOperand; }); } } } } if (blockData.get(block).liveKill.get(operandNum)) { definedIn.add(block); try (Indent indent3 = Debug.logAndIndent("defined in block B%d", block.getId())) { for (LIRInstruction ins : ir.getLIRforBlock(block)) { Debug.log("%d: %s", ins.id(), ins); } } } } int[] hitCount = new int[numBlocks]; while (!definedIn.isEmpty()) { AbstractBlock<?> block = definedIn.removeFirst(); usedIn.remove(block); for (AbstractBlock<?> successor : block.getSuccessors()) { if (successor.isLoopHeader()) { if (!block.isLoopEnd()) { definedIn.add(successor); } } else { if (++hitCount[successor.getId()] == successor.getPredecessorCount()) { definedIn.add(successor); } } } } try (Indent indent3 = Debug.logAndIndent("**** offending usages are in: ")) { for (AbstractBlock<?> block : usedIn) { Debug.log("B%d", block.getId()); } } } } } } catch (Throwable e) { throw Debug.handle(e); } } private void verifyLiveness() { // check that fixed intervals are not live at block boundaries // (live set must be empty at fixed intervals) for (AbstractBlock<?> block : sortedBlocks) { for (int j = 0; j <= maxRegisterNumber(); j++) { assert !blockData.get(block).liveIn.get(j) : "liveIn set of fixed register must be empty"; assert !blockData.get(block).liveOut.get(j) : "liveOut set of fixed register must be empty"; assert !blockData.get(block).liveGen.get(j) : "liveGen set of fixed register must be empty"; } } } void addUse(AllocatableValue operand, int from, int to, RegisterPriority registerPriority, LIRKind kind) { if (!isProcessed(operand)) { return; } Interval interval = getOrCreateInterval(operand); if (!kind.equals(LIRKind.Illegal)) { interval.setKind(kind); } interval.addRange(from, to); // Register use position at even instruction id. interval.addUsePos(to & ~1, registerPriority); Debug.log("add use: %s, from %d to %d (%s)", interval, from, to, registerPriority.name()); } void addTemp(AllocatableValue operand, int tempPos, RegisterPriority registerPriority, LIRKind kind) { if (!isProcessed(operand)) { return; } Interval interval = getOrCreateInterval(operand); if (!kind.equals(LIRKind.Illegal)) { interval.setKind(kind); } interval.addRange(tempPos, tempPos + 1); interval.addUsePos(tempPos, registerPriority); interval.addMaterializationValue(null); Debug.log("add temp: %s tempPos %d (%s)", interval, tempPos, RegisterPriority.MustHaveRegister.name()); } boolean isProcessed(Value operand) { return !isRegister(operand) || attributes(asRegister(operand)).isAllocatable(); } void addDef(AllocatableValue operand, LIRInstruction op, RegisterPriority registerPriority, LIRKind kind) { if (!isProcessed(operand)) { return; } int defPos = op.id(); Interval interval = getOrCreateInterval(operand); if (!kind.equals(LIRKind.Illegal)) { interval.setKind(kind); } Range r = interval.first(); if (r.from <= defPos) { // Update the starting point (when a range is first created for a use, its // start is the beginning of the current block until a def is encountered.) r.from = defPos; interval.addUsePos(defPos, registerPriority); } else { // Dead value - make vacuous interval // also add register priority for dead intervals interval.addRange(defPos, defPos + 1); interval.addUsePos(defPos, registerPriority); Debug.log("Warning: def of operand %s at %d occurs without use", operand, defPos); } changeSpillDefinitionPos(interval, defPos); if (registerPriority == RegisterPriority.None && interval.spillState().ordinal() <= SpillState.StartInMemory.ordinal()) { // detection of method-parameters and roundfp-results interval.setSpillState(SpillState.StartInMemory); } interval.addMaterializationValue(LinearScan.getMaterializedValue(op, operand, interval)); Debug.log("add def: %s defPos %d (%s)", interval, defPos, registerPriority.name()); } /** * Determines the register priority for an instruction's output/result operand. */ static RegisterPriority registerPriorityOfOutputOperand(LIRInstruction op) { if (op instanceof MoveOp) { MoveOp move = (MoveOp) op; if (optimizeMethodArgument(move.getInput())) { return RegisterPriority.None; } } // all other operands require a register return RegisterPriority.MustHaveRegister; } /** * Determines the priority which with an instruction's input operand will be allocated a * register. */ static RegisterPriority registerPriorityOfInputOperand(EnumSet<OperandFlag> flags) { if (flags.contains(OperandFlag.STACK)) { return RegisterPriority.ShouldHaveRegister; } // all other operands require a register return RegisterPriority.MustHaveRegister; } private static boolean optimizeMethodArgument(Value value) { /* * Object method arguments that are passed on the stack are currently not optimized because * this requires that the runtime visits method arguments during stack walking. */ return isStackSlot(value) && asStackSlot(value).isInCallerFrame() && value.getKind() != Kind.Object; } /** * Optimizes moves related to incoming stack based arguments. The interval for the destination * of such moves is assigned the stack slot (which is in the caller's frame) as its spill slot. */ void handleMethodArguments(LIRInstruction op) { if (op instanceof MoveOp) { MoveOp move = (MoveOp) op; if (optimizeMethodArgument(move.getInput())) { StackSlot slot = asStackSlot(move.getInput()); if (DetailedAsserts.getValue()) { assert op.id() > 0 : "invalid id"; assert blockForId(op.id()).getPredecessorCount() == 0 : "move from stack must be in first block"; assert isVariable(move.getResult()) : "result of move must be a variable"; Debug.log("found move from stack slot %s to %s", slot, move.getResult()); } Interval interval = intervalFor(move.getResult()); interval.setSpillSlot(slot); interval.assignLocation(slot); } } } void addRegisterHint(final LIRInstruction op, final Value targetValue, OperandMode mode, EnumSet<OperandFlag> flags, final boolean hintAtDef) { if (flags.contains(OperandFlag.HINT) && isVariableOrRegister(targetValue)) { op.forEachRegisterHint(targetValue, mode, (registerHint, valueMode, valueFlags) -> { if (isVariableOrRegister(registerHint)) { Interval from = getOrCreateInterval((AllocatableValue) registerHint); Interval to = getOrCreateInterval((AllocatableValue) targetValue); /* hints always point from def to use */ if (hintAtDef) { to.setLocationHint(from); } else { from.setLocationHint(to); } Debug.log("operation at opId %d: added hint from interval %d to %d", op.id(), from.operandNumber, to.operandNumber); return registerHint; } return null; }); } } void buildIntervals() { try (Indent indent = Debug.logAndIndent("build intervals")) { InstructionValueConsumer outputConsumer = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariableOrRegister(operand)) { addDef((AllocatableValue) operand, op, registerPriorityOfOutputOperand(op), operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, true); } } }; InstructionValueConsumer tempConsumer = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariableOrRegister(operand)) { addTemp((AllocatableValue) operand, op.id(), RegisterPriority.MustHaveRegister, operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, false); } } }; InstructionValueConsumer aliveConsumer = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariableOrRegister(operand)) { RegisterPriority p = registerPriorityOfInputOperand(flags); final int opId = op.id(); final int blockFrom = getFirstLirInstructionId((blockForId(opId))); addUse((AllocatableValue) operand, blockFrom, opId + 1, p, operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, false); } } }; InstructionValueConsumer inputConsumer = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isVariableOrRegister(operand)) { final int opId = op.id(); final int blockFrom = getFirstLirInstructionId((blockForId(opId))); RegisterPriority p = registerPriorityOfInputOperand(flags); addUse((AllocatableValue) operand, blockFrom, opId, p, operand.getLIRKind()); addRegisterHint(op, operand, mode, flags, false); } } }; InstructionValueConsumer stateProc = new InstructionValueConsumer() { @Override public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { final int opId = op.id(); final int blockFrom = getFirstLirInstructionId((blockForId(opId))); addUse((AllocatableValue) operand, blockFrom, opId + 1, RegisterPriority.None, operand.getLIRKind()); } }; // create a list with all caller-save registers (cpu, fpu, xmm) Register[] callerSaveRegs = frameMap.registerConfig.getCallerSaveRegisters(); // iterate all blocks in reverse order for (int i = blockCount() - 1; i >= 0; i--) { AbstractBlock<?> block = blockAt(i); try (Indent indent2 = Debug.logAndIndent("handle block %d", block.getId())) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); final int blockFrom = getFirstLirInstructionId(block); int blockTo = getLastLirInstructionId(block); assert blockFrom == instructions.get(0).id(); assert blockTo == instructions.get(instructions.size() - 1).id(); // Update intervals for operands live at the end of this block; BitSet live = blockData.get(block).liveOut; for (int operandNum = live.nextSetBit(0); operandNum >= 0; operandNum = live.nextSetBit(operandNum + 1)) { assert live.get(operandNum) : "should not stop here otherwise"; AllocatableValue operand = intervalFor(operandNum).operand; Debug.log("live in %d: %s", operandNum, operand); addUse(operand, blockFrom, blockTo + 2, RegisterPriority.None, LIRKind.Illegal); // add special use positions for loop-end blocks when the // interval is used anywhere inside this loop. It's possible // that the block was part of a non-natural loop, so it might // have an invalid loop index. if (block.isLoopEnd() && block.getLoop() != null && isIntervalInLoop(operandNum, block.getLoop().getIndex())) { intervalFor(operandNum).addUsePos(blockTo + 1, RegisterPriority.LiveAtLoopEnd); } } // iterate all instructions of the block in reverse order. // definitions of intervals are processed before uses for (int j = instructions.size() - 1; j >= 0; j--) { final LIRInstruction op = instructions.get(j); final int opId = op.id(); try (Indent indent3 = Debug.logAndIndent("handle inst %d: %s", opId, op)) { // add a temp range for each register if operation destroys // caller-save registers if (op.destroysCallerSavedRegisters()) { for (Register r : callerSaveRegs) { if (attributes(r).isAllocatable()) { addTemp(r.asValue(), opId, RegisterPriority.None, LIRKind.Illegal); } } Debug.log("operation destroys all caller-save registers"); } op.visitEachOutput(outputConsumer); op.visitEachTemp(tempConsumer); op.visitEachAlive(aliveConsumer); op.visitEachInput(inputConsumer); // Add uses of live locals from interpreter's point of view for proper // debug information generation // Treat these operands as temp values (if the live range is extended // to a call site, the value would be in a register at // the call otherwise) op.visitEachState(stateProc); // special steps for some instructions (especially moves) handleMethodArguments(op); } } // end of instruction iteration } } // end of block iteration // add the range [0, 1] to all fixed intervals. // the register allocator need not handle unhandled fixed intervals for (Interval interval : intervals) { if (interval != null && isRegister(interval.operand)) { interval.addRange(0, 1); } } } } // * Phase 5: actual register allocation private static boolean isSorted(Interval[] intervals) { int from = -1; for (Interval interval : intervals) { assert interval != null; assert from <= interval.from(); from = interval.from(); } return true; } static Interval addToList(Interval first, Interval prev, Interval interval) { Interval newFirst = first; if (prev != null) { prev.next = interval; } else { newFirst = interval; } return newFirst; } Interval.Pair createUnhandledLists(IntervalPredicate isList1, IntervalPredicate isList2) { assert isSorted(sortedIntervals) : "interval list is not sorted"; Interval list1 = Interval.EndMarker; Interval list2 = Interval.EndMarker; Interval list1Prev = null; Interval list2Prev = null; Interval v; int n = sortedIntervals.length; for (int i = 0; i < n; i++) { v = sortedIntervals[i]; if (v == null) { continue; } if (isList1.apply(v)) { list1 = addToList(list1, list1Prev, v); list1Prev = v; } else if (isList2 == null || isList2.apply(v)) { list2 = addToList(list2, list2Prev, v); list2Prev = v; } } if (list1Prev != null) { list1Prev.next = Interval.EndMarker; } if (list2Prev != null) { list2Prev.next = Interval.EndMarker; } assert list1Prev == null || list1Prev.next == Interval.EndMarker : "linear list ends not with sentinel"; assert list2Prev == null || list2Prev.next == Interval.EndMarker : "linear list ends not with sentinel"; return new Interval.Pair(list1, list2); } void sortIntervalsBeforeAllocation() { int sortedLen = 0; for (Interval interval : intervals) { if (interval != null) { sortedLen++; } } Interval[] sortedList = new Interval[sortedLen]; int sortedIdx = 0; int sortedFromMax = -1; // special sorting algorithm: the original interval-list is almost sorted, // only some intervals are swapped. So this is much faster than a complete QuickSort for (Interval interval : intervals) { if (interval != null) { int from = interval.from(); if (sortedFromMax <= from) { sortedList[sortedIdx++] = interval; sortedFromMax = interval.from(); } else { // the assumption that the intervals are already sorted failed, // so this interval must be sorted in manually int j; for (j = sortedIdx - 1; j >= 0 && from < sortedList[j].from(); j--) { sortedList[j + 1] = sortedList[j]; } sortedList[j + 1] = interval; sortedIdx++; } } } sortedIntervals = sortedList; } void sortIntervalsAfterAllocation() { if (firstDerivedIntervalIndex == -1) { // no intervals have been added during allocation, so sorted list is already up to date return; } Interval[] oldList = sortedIntervals; Interval[] newList = Arrays.copyOfRange(intervals, firstDerivedIntervalIndex, intervalsSize); int oldLen = oldList.length; int newLen = newList.length; // conventional sort-algorithm for new intervals Arrays.sort(newList, (Interval a, Interval b) -> a.from() - b.from()); // merge old and new list (both already sorted) into one combined list Interval[] combinedList = new Interval[oldLen + newLen]; int oldIdx = 0; int newIdx = 0; while (oldIdx + newIdx < combinedList.length) { if (newIdx >= newLen || (oldIdx < oldLen && oldList[oldIdx].from() <= newList[newIdx].from())) { combinedList[oldIdx + newIdx] = oldList[oldIdx]; oldIdx++; } else { combinedList[oldIdx + newIdx] = newList[newIdx]; newIdx++; } } sortedIntervals = combinedList; } public void allocateRegisters() { try (Indent indent = Debug.logAndIndent("allocate registers")) { Interval precoloredIntervals; Interval notPrecoloredIntervals; Interval.Pair result = createUnhandledLists(IS_PRECOLORED_INTERVAL, IS_VARIABLE_INTERVAL); precoloredIntervals = result.first; notPrecoloredIntervals = result.second; // allocate cpu registers LinearScanWalker lsw; if (OptimizingLinearScanWalker.Options.LSRAOptimization.getValue()) { lsw = new OptimizingLinearScanWalker(this, precoloredIntervals, notPrecoloredIntervals); } else { lsw = new LinearScanWalker(this, precoloredIntervals, notPrecoloredIntervals); } lsw.walk(); lsw.finishAllocation(); } } // * Phase 6: resolve data flow // (insert moves at edges between blocks if intervals have been split) // wrapper for Interval.splitChildAtOpId that performs a bailout in product mode // instead of returning null Interval splitChildAtOpId(Interval interval, int opId, LIRInstruction.OperandMode mode) { Interval result = interval.getSplitChildAtOpId(opId, mode, this); if (result != null) { Debug.log("Split child at pos %d of interval %s is %s", opId, interval, result); return result; } throw new BailoutException("LinearScan: interval is null"); } Interval intervalAtBlockBegin(AbstractBlock<?> block, int operandNumber) { return splitChildAtOpId(intervalFor(operandNumber), getFirstLirInstructionId(block), LIRInstruction.OperandMode.DEF); } Interval intervalAtBlockEnd(AbstractBlock<?> block, int operandNumber) { return splitChildAtOpId(intervalFor(operandNumber), getLastLirInstructionId(block) + 1, LIRInstruction.OperandMode.DEF); } void resolveCollectMappings(AbstractBlock<?> fromBlock, AbstractBlock<?> toBlock, MoveResolver moveResolver) { assert moveResolver.checkEmpty(); int numOperands = operandSize(); BitSet liveAtEdge = blockData.get(toBlock).liveIn; // visit all variables for which the liveAtEdge bit is set for (int operandNum = liveAtEdge.nextSetBit(0); operandNum >= 0; operandNum = liveAtEdge.nextSetBit(operandNum + 1)) { assert operandNum < numOperands : "live information set for not exisiting interval"; assert blockData.get(fromBlock).liveOut.get(operandNum) && blockData.get(toBlock).liveIn.get(operandNum) : "interval not live at this edge"; Interval fromInterval = intervalAtBlockEnd(fromBlock, operandNum); Interval toInterval = intervalAtBlockBegin(toBlock, operandNum); if (fromInterval != toInterval && !fromInterval.location().equals(toInterval.location())) { // need to insert move instruction moveResolver.addMapping(fromInterval, toInterval); } } } void resolveFindInsertPos(AbstractBlock<?> fromBlock, AbstractBlock<?> toBlock, MoveResolver moveResolver) { if (fromBlock.getSuccessorCount() <= 1) { Debug.log("inserting moves at end of fromBlock B%d", fromBlock.getId()); List<LIRInstruction> instructions = ir.getLIRforBlock(fromBlock); LIRInstruction instr = instructions.get(instructions.size() - 1); if (instr instanceof StandardOp.JumpOp) { // insert moves before branch moveResolver.setInsertPosition(instructions, instructions.size() - 1); } else { moveResolver.setInsertPosition(instructions, instructions.size()); } } else { Debug.log("inserting moves at beginning of toBlock B%d", toBlock.getId()); if (DetailedAsserts.getValue()) { assert ir.getLIRforBlock(fromBlock).get(0) instanceof StandardOp.LabelOp : "block does not start with a label"; // because the number of predecessor edges matches the number of // successor edges, blocks which are reached by switch statements // may have be more than one predecessor but it will be guaranteed // that all predecessors will be the same. for (AbstractBlock<?> predecessor : toBlock.getPredecessors()) { assert fromBlock == predecessor : "all critical edges must be broken"; } } moveResolver.setInsertPosition(ir.getLIRforBlock(toBlock), 1); } } /** * Inserts necessary moves (spilling or reloading) at edges between blocks for intervals that * have been split. */ void resolveDataFlow() { try (Indent indent = Debug.logAndIndent("resolve data flow")) { int numBlocks = blockCount(); MoveResolver moveResolver = new MoveResolver(this); BitSet blockCompleted = new BitSet(numBlocks); BitSet alreadyResolved = new BitSet(numBlocks); for (AbstractBlock<?> block : sortedBlocks) { // check if block has only one predecessor and only one successor if (block.getPredecessorCount() == 1 && block.getSuccessorCount() == 1) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); assert instructions.get(0) instanceof StandardOp.LabelOp : "block must start with label"; assert instructions.get(instructions.size() - 1) instanceof StandardOp.JumpOp : "block with successor must end with unconditional jump"; // check if block is empty (only label and branch) if (instructions.size() == 2) { AbstractBlock<?> pred = block.getPredecessors().iterator().next(); AbstractBlock<?> sux = block.getSuccessors().iterator().next(); // prevent optimization of two consecutive blocks if (!blockCompleted.get(pred.getLinearScanNumber()) && !blockCompleted.get(sux.getLinearScanNumber())) { Debug.log(" optimizing empty block B%d (pred: B%d, sux: B%d)", block.getId(), pred.getId(), sux.getId()); blockCompleted.set(block.getLinearScanNumber()); // directly resolve between pred and sux (without looking // at the empty block // between) resolveCollectMappings(pred, sux, moveResolver); if (moveResolver.hasMappings()) { moveResolver.setInsertPosition(instructions, 1); moveResolver.resolveAndAppendMoves(); } } } } } for (AbstractBlock<?> fromBlock : sortedBlocks) { if (!blockCompleted.get(fromBlock.getLinearScanNumber())) { alreadyResolved.clear(); alreadyResolved.or(blockCompleted); for (AbstractBlock<?> toBlock : fromBlock.getSuccessors()) { // check for duplicate edges between the same blocks (can happen with switch // blocks) if (!alreadyResolved.get(toBlock.getLinearScanNumber())) { Debug.log("processing edge between B%d and B%d", fromBlock.getId(), toBlock.getId()); alreadyResolved.set(toBlock.getLinearScanNumber()); // collect all intervals that have been split between // fromBlock and toBlock resolveCollectMappings(fromBlock, toBlock, moveResolver); if (moveResolver.hasMappings()) { resolveFindInsertPos(fromBlock, toBlock, moveResolver); moveResolver.resolveAndAppendMoves(); } } } } } } } // * Phase 7: assign register numbers back to LIR // (includes computation of debug information and oop maps) static StackSlot canonicalSpillOpr(Interval interval) { assert interval.spillSlot() != null : "canonical spill slot not set"; return interval.spillSlot(); } /** * Assigns the allocated location for an LIR instruction operand back into the instruction. * * @param operand an LIR instruction operand * @param opId the id of the LIR instruction using {@code operand} * @param mode the usage mode for {@code operand} by the instruction * @return the location assigned for the operand */ private Value colorLirOperand(Variable operand, int opId, OperandMode mode) { Interval interval = intervalFor(operand); assert interval != null : "interval must exist"; if (opId != -1) { if (DetailedAsserts.getValue()) { AbstractBlock<?> block = blockForId(opId); if (block.getSuccessorCount() <= 1 && opId == getLastLirInstructionId(block)) { // check if spill moves could have been appended at the end of this block, but // before the branch instruction. So the split child information for this branch // would // be incorrect. LIRInstruction instr = ir.getLIRforBlock(block).get(ir.getLIRforBlock(block).size() - 1); if (instr instanceof StandardOp.JumpOp) { if (blockData.get(block).liveOut.get(operandNumber(operand))) { assert false : "can't get split child for the last branch of a block because the information would be incorrect (moves are inserted before the branch in resolveDataFlow)"; } } } } // operands are not changed when an interval is split during allocation, // so search the right interval here interval = splitChildAtOpId(interval, opId, mode); } if (isIllegal(interval.location()) && interval.canMaterialize()) { assert mode != OperandMode.DEF; return interval.getMaterializedValue(); } return interval.location(); } private boolean isMaterialized(AllocatableValue operand, int opId, OperandMode mode) { Interval interval = intervalFor(operand); assert interval != null : "interval must exist"; if (opId != -1) { // operands are not changed when an interval is split during allocation, // so search the right interval here interval = splitChildAtOpId(interval, opId, mode); } return isIllegal(interval.location()) && interval.canMaterialize(); } protected IntervalWalker initIntervalWalker(IntervalPredicate predicate) { // setup lists of potential oops for walking Interval oopIntervals; Interval nonOopIntervals; oopIntervals = createUnhandledLists(predicate, null).first; // intervals that have no oops inside need not to be processed. // to ensure a walking until the last instruction id, add a dummy interval // with a high operation id nonOopIntervals = new Interval(Value.ILLEGAL, -1); nonOopIntervals.addRange(Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1); return new IntervalWalker(this, oopIntervals, nonOopIntervals); } /** * Visits all intervals for a frame state. The frame state use this information to build the OOP * maps. */ void markFrameLocations(IntervalWalker iw, LIRInstruction op, LIRFrameState info) { Debug.log("creating oop map at opId %d", op.id()); // walk before the current operation . intervals that start at // the operation (i.e. output operands of the operation) are not // included in the oop map iw.walkBefore(op.id()); // TODO(je) we could pass this as parameter AbstractBlock<?> block = blockForId(op.id()); // Iterate through active intervals for (Interval interval = iw.activeLists.get(RegisterBinding.Fixed); interval != Interval.EndMarker; interval = interval.next) { Value operand = interval.operand; assert interval.currentFrom() <= op.id() && op.id() <= interval.currentTo() : "interval should not be active otherwise"; assert isVariable(interval.operand) : "fixed interval found"; // Check if this range covers the instruction. Intervals that // start or end at the current operation are not included in the // oop map, except in the case of patching moves. For patching // moves, any intervals which end at this instruction are included // in the oop map since we may safepoint while doing the patch // before we've consumed the inputs. if (op.id() < interval.currentTo() && !isIllegal(interval.location())) { // caller-save registers must not be included into oop-maps at calls assert !op.destroysCallerSavedRegisters() || !isRegister(operand) || !isCallerSave(operand) : "interval is in a caller-save register at a call . register will be overwritten"; info.markLocation(interval.location(), frameMap); // Spill optimization: when the stack value is guaranteed to be always correct, // then it must be added to the oop map even if the interval is currently in a // register int spillPos = interval.spillDefinitionPos(); if (interval.spillState() != SpillState.SpillInDominator) { if (interval.alwaysInMemory() && op.id() > interval.spillDefinitionPos() && !interval.location().equals(interval.spillSlot())) { assert interval.spillDefinitionPos() > 0 : "position not set correctly"; assert spillPos > 0 : "position not set correctly"; assert interval.spillSlot() != null : "no spill slot assigned"; assert !isRegister(interval.operand) : "interval is on stack : so stack slot is registered twice"; info.markLocation(interval.spillSlot(), frameMap); } } else { AbstractBlock<?> spillBlock = blockForId(spillPos); if (interval.alwaysInMemory() && !interval.location().equals(interval.spillSlot())) { if ((spillBlock.equals(block) && op.id() > spillPos) || dominates(spillBlock, block)) { assert spillPos > 0 : "position not set correctly"; assert interval.spillSlot() != null : "no spill slot assigned"; assert !isRegister(interval.operand) : "interval is on stack : so stack slot is registered twice"; info.markLocation(interval.spillSlot(), frameMap); } } } } } } private boolean isCallerSave(Value operand) { return attributes(asRegister(operand)).isCallerSave(); } private InstructionValueProcedure debugInfoProc = (op, operand, valueMode, flags) -> { int tempOpId = op.id(); OperandMode mode = OperandMode.USE; AbstractBlock<?> block = blockForId(tempOpId); if (block.getSuccessorCount() == 1 && tempOpId == getLastLirInstructionId(block)) { // generating debug information for the last instruction of a block. // if this instruction is a branch, spill moves are inserted before this branch // and so the wrong operand would be returned (spill moves at block boundaries // are not // considered in the live ranges of intervals) // Solution: use the first opId of the branch target block instead. final LIRInstruction instr = ir.getLIRforBlock(block).get(ir.getLIRforBlock(block).size() - 1); if (instr instanceof StandardOp.JumpOp) { if (blockData.get(block).liveOut.get(operandNumber(operand))) { tempOpId = getFirstLirInstructionId(block.getSuccessors().iterator().next()); mode = OperandMode.DEF; } } } // Get current location of operand // The operand must be live because debug information is considered when building // the intervals // if the interval is not live, colorLirOperand will cause an assert on failure Value result = colorLirOperand((Variable) operand, tempOpId, mode); assert !hasCall(tempOpId) || isStackSlot(result) || isConstant(result) || !isCallerSave(result) : "cannot have caller-save register operands at calls"; return result; }; private void computeDebugInfo(IntervalWalker iw, final LIRInstruction op, LIRFrameState info) { info.initDebugInfo(frameMap, !op.destroysCallerSavedRegisters() || !callKillsRegisters); markFrameLocations(iw, op, info); info.forEachState(op, debugInfoProc); info.finish(op, frameMap); } private void assignLocations(List<LIRInstruction> instructions, final IntervalWalker iw) { int numInst = instructions.size(); boolean hasDead = false; InstructionValueProcedure assignProc = (op, operand, mode, flags) -> isVariable(operand) ? colorLirOperand((Variable) operand, op.id(), mode) : operand; InstructionStateProcedure stateProc = (op, state) -> computeDebugInfo(iw, op, state); for (int j = 0; j < numInst; j++) { final LIRInstruction op = instructions.get(j); if (op == null) { // this can happen when spill-moves are removed in eliminateSpillMoves hasDead = true; continue; } // remove useless moves MoveOp move = null; if (op instanceof MoveOp) { move = (MoveOp) op; AllocatableValue result = move.getResult(); if (isVariable(result) && isMaterialized(result, op.id(), OperandMode.DEF)) { /* * This happens if a materializable interval is originally not spilled but then * kicked out in LinearScanWalker.splitForSpilling(). When kicking out such an * interval this move operation was already generated. */ instructions.set(j, null); hasDead = true; continue; } } op.forEachInput(assignProc); op.forEachAlive(assignProc); op.forEachTemp(assignProc); op.forEachOutput(assignProc); // compute reference map and debug information op.forEachState(stateProc); // remove useless moves if (move != null) { if (move.getInput().equals(move.getResult())) { instructions.set(j, null); hasDead = true; } } } if (hasDead) { // Remove null values from the list. instructions.removeAll(Collections.singleton(null)); } } private void assignLocations() { IntervalWalker iw = initIntervalWalker(IS_STACK_INTERVAL); try (Indent indent = Debug.logAndIndent("assign locations")) { for (AbstractBlock<?> block : sortedBlocks) { try (Indent indent2 = Debug.logAndIndent("assign locations in block B%d", block.getId())) { assignLocations(ir.getLIRforBlock(block), iw); } } } } public static void allocate(TargetDescription target, LIR lir, FrameMap frameMap) { new LinearScan(target, lir, frameMap).allocate(); } private void allocate() { /* * This is the point to enable debug logging for the whole register allocation. */ try (Indent indent = Debug.logAndIndent("LinearScan allocate")) { try (Scope s = Debug.scope("LifetimeAnalysis")) { numberInstructions(); printLir("Before register allocation", true); computeLocalLiveSets(); computeGlobalLiveSets(); buildIntervals(); sortIntervalsBeforeAllocation(); } catch (Throwable e) { throw Debug.handle(e); } try (Scope s = Debug.scope("RegisterAllocation")) { printIntervals("Before register allocation"); allocateRegisters(); } catch (Throwable e) { throw Debug.handle(e); } if (Options.LSRAOptimizeSpillPosition.getValue()) { try (Scope s = Debug.scope("OptimizeSpillPosition")) { optimizeSpillPosition(); } catch (Throwable e) { throw Debug.handle(e); } } try (Scope s = Debug.scope("ResolveDataFlow")) { resolveDataFlow(); } catch (Throwable e) { throw Debug.handle(e); } try (Scope s = Debug.scope("DebugInfo")) { frameMap.finish(); printIntervals("After register allocation"); printLir("After register allocation", true); sortIntervalsAfterAllocation(); if (DetailedAsserts.getValue()) { verify(); } try (Scope s1 = Debug.scope("EliminateSpillMove")) { eliminateSpillMoves(); } catch (Throwable e) { throw Debug.handle(e); } printLir("After spill move elimination", true); try (Scope s1 = Debug.scope("AssignLocations")) { assignLocations(); } catch (Throwable e) { throw Debug.handle(e); } if (DetailedAsserts.getValue()) { verifyIntervals(); } } catch (Throwable e) { throw Debug.handle(e); } printLir("After register number assignment", true); } } private DebugMetric betterSpillPos = Debug.metric("BetterSpillPosition"); private DebugMetric betterSpillPosWithLowerProbability = Debug.metric("BetterSpillPositionWithLowerProbability"); private void optimizeSpillPosition() { LIRInsertionBuffer[] insertionBuffers = new LIRInsertionBuffer[ir.linearScanOrder().size()]; for (Interval interval : intervals) { if (interval != null && interval.isSplitParent() && interval.spillState() == SpillState.SpillInDominator) { AbstractBlock<?> defBlock = blockForId(interval.spillDefinitionPos()); AbstractBlock<?> spillBlock = null; Interval firstSpillChild = null; try (Indent indent = Debug.logAndIndent("interval %s (%s)", interval, defBlock)) { for (Interval splitChild : interval.getSplitChildren()) { if (isStackSlot(splitChild.location())) { if (firstSpillChild == null || splitChild.from() < firstSpillChild.from()) { firstSpillChild = splitChild; } else { assert firstSpillChild.from() < splitChild.from(); } // iterate all blocks where the interval has use positions for (AbstractBlock<?> splitBlock : blocksForInterval(splitChild)) { if (dominates(defBlock, splitBlock)) { Debug.log("Split interval %s, block %s", splitChild, splitBlock); if (spillBlock == null) { spillBlock = splitBlock; } else { spillBlock = commonDominator(spillBlock, splitBlock); assert spillBlock != null; } } } } } if (spillBlock == null) { // no spill interval interval.setSpillState(SpillState.StoreAtDefinition); } else { // move out of loops if (defBlock.getLoopDepth() < spillBlock.getLoopDepth()) { spillBlock = moveSpillOutOfLoop(defBlock, spillBlock); } /* * If the spill block is the begin of the first split child (aka the value * is on the stack) spill in the dominator. */ assert firstSpillChild != null; if (!defBlock.equals(spillBlock) && spillBlock.equals(blockForId(firstSpillChild.from()))) { AbstractBlock<?> dom = spillBlock.getDominator(); Debug.log("Spill block (%s) is the beginning of a spill child -> use dominator (%s)", spillBlock, dom); spillBlock = dom; } if (!defBlock.equals(spillBlock)) { assert dominates(defBlock, spillBlock); betterSpillPos.increment(); Debug.log("Better spill position found (Block %s)", spillBlock); if (defBlock.probability() <= spillBlock.probability()) { // better spill block has the same probability -> do nothing interval.setSpillState(SpillState.StoreAtDefinition); } else { LIRInsertionBuffer insertionBuffer = insertionBuffers[spillBlock.getId()]; if (insertionBuffer == null) { insertionBuffer = new LIRInsertionBuffer(); insertionBuffers[spillBlock.getId()] = insertionBuffer; insertionBuffer.init(ir.getLIRforBlock(spillBlock)); } int spillOpId = getFirstLirInstructionId(spillBlock); // insert spill move AllocatableValue fromLocation = interval.getSplitChildAtOpId(spillOpId, OperandMode.DEF, this).location(); AllocatableValue toLocation = canonicalSpillOpr(interval); LIRInstruction move = ir.getSpillMoveFactory().createMove(toLocation, fromLocation); move.setId(DOMINATOR_SPILL_MOVE_ID); /* * We can use the insertion buffer directly because we always insert * at position 1. */ insertionBuffer.append(1, move); betterSpillPosWithLowerProbability.increment(); interval.setSpillDefinitionPos(spillOpId); } } else { // definition is the best choice interval.setSpillState(SpillState.StoreAtDefinition); } } } } } for (LIRInsertionBuffer insertionBuffer : insertionBuffers) { if (insertionBuffer != null) { assert insertionBuffer.initialized() : "Insertion buffer is nonnull but not initialized!"; insertionBuffer.finish(); } } } /** * Iterate over all {@link AbstractBlock blocks} of an interval. */ private class IntervalBlockIterator implements Iterator<AbstractBlock<?>> { Range range; AbstractBlock<?> block; public IntervalBlockIterator(Interval interval) { range = interval.first(); block = blockForId(range.from); } public AbstractBlock<?> next() { AbstractBlock<?> currentBlock = block; int nextBlockIndex = block.getLinearScanNumber() + 1; if (nextBlockIndex < sortedBlocks.size()) { block = sortedBlocks.get(nextBlockIndex); if (range.to <= getFirstLirInstructionId(block)) { range = range.next; if (range == Range.EndMarker) { block = null; } else { block = blockForId(range.from); } } } else { block = null; } return currentBlock; } public boolean hasNext() { return block != null; } } private Iterable<AbstractBlock<?>> blocksForInterval(Interval interval) { return new Iterable<AbstractBlock<?>>() { public Iterator<AbstractBlock<?>> iterator() { return new IntervalBlockIterator(interval); } }; } private static AbstractBlock<?> moveSpillOutOfLoop(AbstractBlock<?> defBlock, AbstractBlock<?> spillBlock) { int defLoopDepth = defBlock.getLoopDepth(); for (AbstractBlock<?> block = spillBlock.getDominator(); !defBlock.equals(block); block = block.getDominator()) { assert block != null : "spill block not dominated by definition block?"; if (block.getLoopDepth() <= defLoopDepth) { assert block.getLoopDepth() == defLoopDepth : "Cannot spill an interval outside of the loop where it is defined!"; return block; } } return defBlock; } void printIntervals(String label) { if (Debug.isLogEnabled()) { try (Indent indent = Debug.logAndIndent("intervals %s", label)) { for (Interval interval : intervals) { if (interval != null) { Debug.log("%s", interval.logString(this)); } } try (Indent indent2 = Debug.logAndIndent("Basic Blocks")) { for (int i = 0; i < blockCount(); i++) { AbstractBlock<?> block = blockAt(i); Debug.log("B%d [%d, %d, %s] ", block.getId(), getFirstLirInstructionId(block), getLastLirInstructionId(block), block.getLoop()); } } } } Debug.dump(Arrays.copyOf(intervals, intervalsSize), label); } void printLir(String label, @SuppressWarnings("unused") boolean hirValid) { Debug.dump(ir, label); } boolean verify() { // (check that all intervals have a correct register and that no registers are overwritten) verifyIntervals(); verifyRegisters(); Debug.log("no errors found"); return true; } private void verifyRegisters() { // Enable this logging to get output for the verification process. try (Indent indent = Debug.logAndIndent("verifying register allocation")) { RegisterVerifier verifier = new RegisterVerifier(this); verifier.verify(blockAt(0)); } } void verifyIntervals() { try (Indent indent = Debug.logAndIndent("verifying intervals")) { int len = intervalsSize; for (int i = 0; i < len; i++) { Interval i1 = intervals[i]; if (i1 == null) { continue; } i1.checkSplitChildren(); if (i1.operandNumber != i) { Debug.log("Interval %d is on position %d in list", i1.operandNumber, i); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } if (isVariable(i1.operand) && i1.kind().equals(LIRKind.Illegal)) { Debug.log("Interval %d has no type assigned", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } if (i1.location() == null) { Debug.log("Interval %d has no register assigned", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } if (i1.first() == Range.EndMarker) { Debug.log("Interval %d has no Range", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } for (Range r = i1.first(); r != Range.EndMarker; r = r.next) { if (r.from >= r.to) { Debug.log("Interval %d has zero length range", i1.operandNumber); Debug.log(i1.logString(this)); throw new GraalInternalError(""); } } for (int j = i + 1; j < len; j++) { Interval i2 = intervals[j]; if (i2 == null) { continue; } // special intervals that are created in MoveResolver // . ignore them because the range information has no meaning there if (i1.from() == 1 && i1.to() == 2) { continue; } if (i2.from() == 1 && i2.to() == 2) { continue; } Value l1 = i1.location(); Value l2 = i2.location(); if (i1.intersects(i2) && !isIllegal(l1) && (l1.equals(l2))) { if (DetailedAsserts.getValue()) { Debug.log("Intervals %d and %d overlap and have the same register assigned", i1.operandNumber, i2.operandNumber); Debug.log(i1.logString(this)); Debug.log(i2.logString(this)); } throw new BailoutException(""); } } } } } class CheckConsumer implements ValueConsumer { boolean ok; Interval curInterval; @Override public void visitValue(Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { if (isRegister(operand)) { if (intervalFor(operand) == curInterval) { ok = true; } } } } void verifyNoOopsInFixedIntervals() { try (Indent indent = Debug.logAndIndent("verifying that no oops are in fixed intervals *")) { CheckConsumer checkConsumer = new CheckConsumer(); Interval fixedIntervals; Interval otherIntervals; fixedIntervals = createUnhandledLists(IS_PRECOLORED_INTERVAL, null).first; // to ensure a walking until the last instruction id, add a dummy interval // with a high operation id otherIntervals = new Interval(Value.ILLEGAL, -1); otherIntervals.addRange(Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1); IntervalWalker iw = new IntervalWalker(this, fixedIntervals, otherIntervals); for (AbstractBlock<?> block : sortedBlocks) { List<LIRInstruction> instructions = ir.getLIRforBlock(block); for (int j = 0; j < instructions.size(); j++) { LIRInstruction op = instructions.get(j); if (op.hasState()) { iw.walkBefore(op.id()); boolean checkLive = true; // Make sure none of the fixed registers is live across an // oopmap since we can't handle that correctly. if (checkLive) { for (Interval interval = iw.activeLists.get(RegisterBinding.Fixed); interval != Interval.EndMarker; interval = interval.next) { if (interval.currentTo() > op.id() + 1) { // This interval is live out of this op so make sure // that this interval represents some value that's // referenced by this op either as an input or output. checkConsumer.curInterval = interval; checkConsumer.ok = false; op.visitEachInput(checkConsumer); op.visitEachAlive(checkConsumer); op.visitEachTemp(checkConsumer); op.visitEachOutput(checkConsumer); assert checkConsumer.ok : "fixed intervals should never be live across an oopmap point"; } } } } } } } } /** * Returns a value for a interval definition, which can be used for re-materialization. * * @param op An instruction which defines a value * @param operand The destination operand of the instruction * @param interval The interval for this defined value. * @return Returns the value which is moved to the instruction and which can be reused at all * reload-locations in case the interval of this instruction is spilled. Currently this * can only be a {@link Constant}. */ public static Constant getMaterializedValue(LIRInstruction op, Value operand, Interval interval) { if (op instanceof MoveOp) { MoveOp move = (MoveOp) op; if (move.getInput() instanceof Constant) { /* * Check if the interval has any uses which would accept an stack location (priority * == ShouldHaveRegister). Rematerialization of such intervals can result in a * degradation, because rematerialization always inserts a constant load, even if * the value is not needed in a register. */ Interval.UsePosList usePosList = interval.usePosList(); int numUsePos = usePosList.size(); for (int useIdx = 0; useIdx < numUsePos; useIdx++) { Interval.RegisterPriority priority = usePosList.registerPriority(useIdx); if (priority == Interval.RegisterPriority.ShouldHaveRegister) { return null; } } return (Constant) move.getInput(); } } return null; } }
LSRA: replace anonymous InstructionValueConsumers with Lambdas.
graal/com.oracle.graal.compiler/src/com/oracle/graal/compiler/alloc/LinearScan.java
LSRA: replace anonymous InstructionValueConsumers with Lambdas.
<ide><path>raal/com.oracle.graal.compiler/src/com/oracle/graal/compiler/alloc/LinearScan.java <ide> void buildIntervals() { <ide> <ide> try (Indent indent = Debug.logAndIndent("build intervals")) { <del> InstructionValueConsumer outputConsumer = new InstructionValueConsumer() { <del> <del> @Override <del> public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { <del> if (isVariableOrRegister(operand)) { <del> addDef((AllocatableValue) operand, op, registerPriorityOfOutputOperand(op), operand.getLIRKind()); <del> addRegisterHint(op, operand, mode, flags, true); <del> } <add> InstructionValueConsumer outputConsumer = (op, operand, mode, flags) -> { <add> if (isVariableOrRegister(operand)) { <add> addDef((AllocatableValue) operand, op, registerPriorityOfOutputOperand(op), operand.getLIRKind()); <add> addRegisterHint(op, operand, mode, flags, true); <ide> } <ide> }; <ide> <del> InstructionValueConsumer tempConsumer = new InstructionValueConsumer() { <del> <del> @Override <del> public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { <del> if (isVariableOrRegister(operand)) { <del> addTemp((AllocatableValue) operand, op.id(), RegisterPriority.MustHaveRegister, operand.getLIRKind()); <del> addRegisterHint(op, operand, mode, flags, false); <del> } <add> InstructionValueConsumer tempConsumer = (op, operand, mode, flags) -> { <add> if (isVariableOrRegister(operand)) { <add> addTemp((AllocatableValue) operand, op.id(), RegisterPriority.MustHaveRegister, operand.getLIRKind()); <add> addRegisterHint(op, operand, mode, flags, false); <ide> } <ide> }; <ide> <del> InstructionValueConsumer aliveConsumer = new InstructionValueConsumer() { <del> <del> @Override <del> public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { <del> if (isVariableOrRegister(operand)) { <del> RegisterPriority p = registerPriorityOfInputOperand(flags); <del> final int opId = op.id(); <del> final int blockFrom = getFirstLirInstructionId((blockForId(opId))); <del> addUse((AllocatableValue) operand, blockFrom, opId + 1, p, operand.getLIRKind()); <del> addRegisterHint(op, operand, mode, flags, false); <del> } <add> InstructionValueConsumer aliveConsumer = (op, operand, mode, flags) -> { <add> if (isVariableOrRegister(operand)) { <add> RegisterPriority p = registerPriorityOfInputOperand(flags); <add> int opId = op.id(); <add> int blockFrom = getFirstLirInstructionId((blockForId(opId))); <add> addUse((AllocatableValue) operand, blockFrom, opId + 1, p, operand.getLIRKind()); <add> addRegisterHint(op, operand, mode, flags, false); <ide> } <ide> }; <ide> <del> InstructionValueConsumer inputConsumer = new InstructionValueConsumer() { <del> <del> @Override <del> public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { <del> if (isVariableOrRegister(operand)) { <del> final int opId = op.id(); <del> final int blockFrom = getFirstLirInstructionId((blockForId(opId))); <del> RegisterPriority p = registerPriorityOfInputOperand(flags); <del> addUse((AllocatableValue) operand, blockFrom, opId, p, operand.getLIRKind()); <del> addRegisterHint(op, operand, mode, flags, false); <del> } <add> InstructionValueConsumer inputConsumer = (op, operand, mode, flags) -> { <add> if (isVariableOrRegister(operand)) { <add> int opId = op.id(); <add> int blockFrom = getFirstLirInstructionId((blockForId(opId))); <add> RegisterPriority p = registerPriorityOfInputOperand(flags); <add> addUse((AllocatableValue) operand, blockFrom, opId, p, operand.getLIRKind()); <add> addRegisterHint(op, operand, mode, flags, false); <ide> } <ide> }; <ide> <del> InstructionValueConsumer stateProc = new InstructionValueConsumer() { <del> <del> @Override <del> public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) { <del> final int opId = op.id(); <del> final int blockFrom = getFirstLirInstructionId((blockForId(opId))); <del> addUse((AllocatableValue) operand, blockFrom, opId + 1, RegisterPriority.None, operand.getLIRKind()); <del> } <add> InstructionValueConsumer stateProc = (op, operand, mode, flags) -> { <add> int opId = op.id(); <add> int blockFrom = getFirstLirInstructionId((blockForId(opId))); <add> addUse((AllocatableValue) operand, blockFrom, opId + 1, RegisterPriority.None, operand.getLIRKind()); <ide> }; <ide> <ide> // create a list with all caller-save registers (cpu, fpu, xmm)
JavaScript
mit
efc7f0afa826080e5bd7f0496e34345a0d2996eb
0
atufkas/angular-openweather-app,smugcloud/angular-openweather,smugcloud/angular-openweather,atufkas/angular-openweather-app,atufkas/angular-openweather-app,smugcloud/angular-openweather,atufkas/angular-openweather-app,smugcloud/angular-openweather
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('OpenWeather App', function() { beforeEach(function() { browser().navigateTo('../../app/index.html'); }); it('should automatically redirect to /forecast when location hash/fragment is empty', function() { expect(browser().location().url()).toBe("/forecast"); }); describe('Forecast view', function() { beforeEach(function() { browser().navigateTo('#/forecast'); }); it('should render forecast when user navigates to /forecast', function() { expect(element('[ng-view] form button[type="submit"]').text()).toMatch(/Search!/); }); it('should map the value of an "instant city forecast" button to the input field', function() { element('[ng-view] form .btn-group > button:first-child').click(); expect(element('[ng-view] form input#location').attr('value')).toBe('Hamburg'); }); }); });
test/e2e/scenarios.js
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('OpenWeather App', function() { beforeEach(function() { browser().navigateTo('../../app/index.html'); }); it('should automatically redirect to /forecast when location hash/fragment is empty', function() { expect(browser().location().url()).toBe("/forecast"); }); describe('Forecast view', function() { beforeEach(function() { browser().navigateTo('#/forecast'); }); it('should render forecast when user navigates to /forecast', function() { expect(element('[ng-view] form button[type="submit"]').text()).toMatch(/Search!/); }); it('should display the location value of the first "city button" inside the search field', function() { element('[ng-view] form .btn-group > button:first-child').click(); expect(element('[ng-view] form input#location').attr('value')).toBe('Hamburg'); }); }); });
Improved e2e test description.
test/e2e/scenarios.js
Improved e2e test description.
<ide><path>est/e2e/scenarios.js <ide> expect(element('[ng-view] form button[type="submit"]').text()).toMatch(/Search!/); <ide> }); <ide> <del> it('should display the location value of the first "city button" inside the search field', function() { <add> it('should map the value of an "instant city forecast" button to the input field', function() { <ide> element('[ng-view] form .btn-group > button:first-child').click(); <ide> expect(element('[ng-view] form input#location').attr('value')).toBe('Hamburg'); <ide> });
Java
bsd-3-clause
ac3e79d70f264d7c519320ce4c78481124619516
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.calab.service.login; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.exceptions.CSException; /** * The LoginService authenticates users into the calab system. * * @author doswellj * @param applicationName sets the application name for use by CSM * @param am Authentication Manager for CSM. */ public class LoginService { String applicationName = null; AuthenticationManager am = null; // TODO Make a singleton /** * LoginService Constructor * @param strname name of the application */ public LoginService(String strname) throws Exception { this.applicationName = strname; am = SecurityServiceProvider.getAuthenticationManager(this.applicationName); //TODO Add Role implementation } /** * The login method uses CSM to authenticated the user with LoginId and Password credentials * @param strusername LoginId of the user * @param strpassword Encrypted password of the user * @return boolean identicating whether the user successfully authenticated */ public boolean login(String strUsername, String strPassword ) throws CSException { return am.login( strUsername,strPassword); } /** * The userInfo method sets and authenticated user's information * @param strLoginId LoginId of the authenticated user * @return SecurityBean containing an authenticated user's information */ public UserBean setUserInfo(String strLoginId) { //TODO Implement method to query CSM_USER table and get logged in user's recordset UserBean securityBean = new UserBean(); securityBean.setLoginId(strLoginId); //set remaining info return securityBean; } }
src/gov/nih/nci/calab/service/login/LoginService.java
package gov.nih.nci.calab.service.login; import gov.nih.nci.calab.dto.security.SecurityBean; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.exceptions.CSException; /** * The LoginService authenticates users into the calab system. * * @author doswellj * @param applicationName sets the application name for use by CSM * @param am Authentication Manager for CSM. */ public class LoginService { String applicationName = null; AuthenticationManager am = null; // TODO Make a singleton /** * LoginService Constructor * @param strname name of the application */ public LoginService(String strname) throws Exception { this.applicationName = strname; am = SecurityServiceProvider.getAuthenticationManager(this.applicationName); //TODO Add Role implementation } /** * The login method uses CSM to authenticated the user with LoginId and Password credentials * @param strusername LoginId of the user * @param strpassword Encrypted password of the user * @return boolean identicating whether the user successfully authenticated */ public boolean login(String strUsername, String strPassword ) throws CSException { return am.login( strUsername,strPassword); } /** * The userInfo method sets and authenticated user's information * @param strLoginId LoginId of the authenticated user * @return SecurityBean containing an authenticated user's information */ public SecurityBean setUserInfo(String strLoginId) { //TODO Implement method to query CSM_USER table and get logged in user's recordset SecurityBean securityBean = new SecurityBean(); securityBean.setLoginId(strLoginId); //set remaining info return securityBean; } }
Use UserBean to replace SecurityBean SVN-Revision: 7821
src/gov/nih/nci/calab/service/login/LoginService.java
Use UserBean to replace SecurityBean
<ide><path>rc/gov/nih/nci/calab/service/login/LoginService.java <ide> package gov.nih.nci.calab.service.login; <ide> <del>import gov.nih.nci.calab.dto.security.SecurityBean; <add>import gov.nih.nci.calab.dto.common.UserBean; <ide> import gov.nih.nci.security.AuthenticationManager; <ide> import gov.nih.nci.security.SecurityServiceProvider; <ide> import gov.nih.nci.security.exceptions.CSException; <ide> * @param strLoginId LoginId of the authenticated user <ide> * @return SecurityBean containing an authenticated user's information <ide> */ <del> public SecurityBean setUserInfo(String strLoginId) <add> public UserBean setUserInfo(String strLoginId) <ide> { <ide> //TODO Implement method to query CSM_USER table and get logged in user's recordset <del> SecurityBean securityBean = new SecurityBean(); <add> UserBean securityBean = new UserBean(); <ide> <ide> securityBean.setLoginId(strLoginId); <ide> //set remaining info
Java
apache-2.0
6504e1f91dd20ea3f6630513b7828f5f5d0d00db
0
i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie
package net.i2p.client.streaming; import java.util.Arrays; import net.i2p.I2PAppContext; import net.i2p.data.Base64; import net.i2p.data.ByteArray; import net.i2p.data.DataFormatException; import net.i2p.data.DataHelper; import net.i2p.data.Destination; import net.i2p.data.Signature; import net.i2p.data.SigningPrivateKey; import net.i2p.util.Log; /** * Contain a single packet transferred as part of a streaming connection. * The data format is as follows:<ul> * <li>{@link #getSendStreamId sendStreamId} [4 byte value]</li> * <li>{@link #getReceiveStreamId receiveStreamId} [4 byte value]</li> * <li>{@link #getSequenceNum sequenceNum} [4 byte unsigned integer]</li> * <li>{@link #getAckThrough ackThrough} [4 byte unsigned integer]</li> * <li>number of NACKs [1 byte unsigned integer]</li> * <li>that many {@link #getNacks NACKs}</li> * <li>{@link #getResendDelay resendDelay} [1 byte integer]</li> * <li>flags [2 byte value]</li> * <li>option data size [2 byte integer]</li> * <li>option data specified by those flags [0 or more bytes]</li> * <li>payload [remaining packet size]</li> * </ul> * * <p>The flags field above specifies some metadata about the packet, and in * turn may require certain additional data to be included. The flags are * as follows (with any data structures specified added to the options area * in the given order):</p><ol> * <li>{@link #FLAG_SYNCHRONIZE}: no option data</li> * <li>{@link #FLAG_CLOSE}: no option data</li> * <li>{@link #FLAG_RESET}: no option data</li> * <li>{@link #FLAG_SIGNATURE_INCLUDED}: {@link net.i2p.data.Signature}</li> * <li>{@link #FLAG_SIGNATURE_REQUESTED}: no option data</li> * <li>{@link #FLAG_FROM_INCLUDED}: {@link net.i2p.data.Destination}</li> * <li>{@link #FLAG_DELAY_REQUESTED}: 2 byte integer</li> * <li>{@link #FLAG_MAX_PACKET_SIZE_INCLUDED}: 2 byte integer</li> * <li>{@link #FLAG_PROFILE_INTERACTIVE}: no option data</li> * </ol> * * <p>If the signature is included, it uses the Destination's DSA key * to sign the entire header and payload with the space in the options * for the signature being set to all zeroes.</p> * * <p>If the sequenceNum is 0 and the SYN is not set, this is a plain ACK * packet that should not be ACKed</p> * */ public class Packet { private long _sendStreamId; private long _receiveStreamId; private long _sequenceNum; private long _ackThrough; private long _nacks[]; private int _resendDelay; private int _flags; private ByteArray _payload; // the next four are set only if the flags say so private Signature _optionSignature; private Destination _optionFrom; private int _optionDelay; private int _optionMaxSize; /** * The receiveStreamId will be set to this when the packet doesn't know * what ID will be assigned by the remote peer (aka this is the initial * synchronize packet) * */ public static final long STREAM_ID_UNKNOWN = 0l; public static final long MAX_STREAM_ID = 0xffffffffl; /** * This packet is creating a new socket connection (if the receiveStreamId * is STREAM_ID_UNKNOWN) or it is acknowledging a request to * create a connection and in turn is accepting the socket. * */ public static final int FLAG_SYNCHRONIZE = (1 << 0); /** * The sender of this packet will not be sending any more payload data. */ public static final int FLAG_CLOSE = (1 << 1); /** * This packet is being sent to signify that the socket does not exist * (or, if in response to an initial synchronize packet, that the * connection was refused). * */ public static final int FLAG_RESET = (1 << 2); /** * This packet contains a DSA signature from the packet's sender. This * signature is within the packet options. All synchronize packets must * have this flag set. * */ public static final int FLAG_SIGNATURE_INCLUDED = (1 << 3); /** * This packet wants the recipient to include signatures on subsequent * packets sent to the creator of this packet. */ public static final int FLAG_SIGNATURE_REQUESTED = (1 << 4); /** * This packet includes the full I2P destination of the packet's sender. * The initial synchronize packet must have this flag set. */ public static final int FLAG_FROM_INCLUDED = (1 << 5); /** * This packet includes an explicit request for the recipient to delay * sending any packets with data for a given amount of time. * */ public static final int FLAG_DELAY_REQUESTED = (1 << 6); /** * This packet includes a request that the recipient not send any * subsequent packets with payloads greater than a specific size. * If not set and no prior value was delivered, the maximum value * will be assumed (approximately 32KB). * */ public static final int FLAG_MAX_PACKET_SIZE_INCLUDED = (1 << 7); /** * If set, this packet is travelling as part of an interactive flow, * meaning it is more lag sensitive than throughput sensitive. aka * send data ASAP rather than waiting around to send full packets. * */ public static final int FLAG_PROFILE_INTERACTIVE = (1 << 8); /** * If set, this packet is a ping (if sendStreamId is set) or a * ping reply (if receiveStreamId is set). */ public static final int FLAG_ECHO = (1 << 9); /** * If set, this packet doesn't really want to ack anything */ public static final int FLAG_NO_ACK = (1 << 10); public static final int DEFAULT_MAX_SIZE = 32*1024; protected static final int MAX_DELAY_REQUEST = 65535; public Packet() { } private boolean _sendStreamIdSet = false; /** what stream do we send data to the peer on? * @return stream ID we use to send data */ public long getSendStreamId() { return _sendStreamId; } public void setSendStreamId(long id) { if ( (_sendStreamIdSet) && (_sendStreamId > 0) ) throw new RuntimeException("Send stream ID already set [" + _sendStreamId + ", " + id + "]"); _sendStreamIdSet = true; _sendStreamId = id; } private boolean _receiveStreamIdSet = false; /** * stream the replies should be sent on. this should be 0 if the * connection is still being built. * @return stream ID we use to get data, zero if the connection is still being built. */ public long getReceiveStreamId() { return _receiveStreamId; } public void setReceiveStreamId(long id) { if ( (_receiveStreamIdSet) && (_receiveStreamId > 0) ) throw new RuntimeException("Receive stream ID already set [" + _receiveStreamId + ", " + id + "]"); _receiveStreamIdSet = true; _receiveStreamId = id; } /** 0-indexed sequence number for this Packet in the sendStream * @return 0-indexed sequence number for current Packet in current sendStream */ public long getSequenceNum() { return _sequenceNum; } public void setSequenceNum(long num) { _sequenceNum = num; } /** * The highest packet sequence number that received * on the receiveStreamId. This field is ignored on the initial * connection packet (where receiveStreamId is the unknown id) or * if FLAG_NO_ACK is set. * * @return The highest packet sequence number received on receiveStreamId */ public long getAckThrough() { if (isFlagSet(FLAG_NO_ACK)) return -1; else return _ackThrough; } public void setAckThrough(long id) { if (id < 0) setFlag(FLAG_NO_ACK); _ackThrough = id; } /** * List of packet sequence numbers below the getAckThrough() value * have not been received. this may be null. * * @return List of packet sequence numbers not ACKed, or null if there are none. */ public long[] getNacks() { return _nacks; } public void setNacks(long nacks[]) { _nacks = nacks; } /** * How long is the creator of this packet going to wait before * resending this packet (if it hasn't yet been ACKed). The * value is seconds since the packet was created. * * @return Delay before resending a packet in seconds. */ public int getResendDelay() { return _resendDelay; } public void setResendDelay(int numSeconds) { _resendDelay = numSeconds; } public static final int MAX_PAYLOAD_SIZE = 32*1024; /** get the actual payload of the message. may be null * @return the payload of the message, null if none. */ public ByteArray getPayload() { return _payload; } public void setPayload(ByteArray payload) { _payload = payload; if ( (payload != null) && (payload.getValid() > MAX_PAYLOAD_SIZE) ) throw new IllegalArgumentException("Too large payload: " + payload.getValid()); } public int getPayloadSize() { return (_payload == null ? 0 : _payload.getValid()); } public void releasePayload() { //_payload = null; } public ByteArray acquirePayload() { ByteArray old = _payload; _payload = new ByteArray(new byte[Packet.MAX_PAYLOAD_SIZE]); return _payload; } /** is a particular flag set on this packet? * @param flag bitmask of any flag(s) * @return true if set, false if not. */ public boolean isFlagSet(int flag) { return 0 != (_flags & flag); } public void setFlag(int flag) { _flags |= flag; } public void setFlag(int flag, boolean set) { if (set) _flags |= flag; else _flags &= ~flag; } public void setFlags(int flags) { _flags = flags; } /** the signature on the packet (only included if the flag for it is set) * @return signature on the packet if the flag for signatures is set */ public Signature getOptionalSignature() { return _optionSignature; } public void setOptionalSignature(Signature sig) { setFlag(FLAG_SIGNATURE_INCLUDED, sig != null); _optionSignature = sig; } /** the sender of the packet (only included if the flag for it is set) * @return the sending Destination */ public Destination getOptionalFrom() { return _optionFrom; } public void setOptionalFrom(Destination from) { setFlag(FLAG_FROM_INCLUDED, from != null); if (from == null) throw new RuntimeException("from is null!?"); _optionFrom = from; } /** * How many milliseconds the sender of this packet wants the recipient * to wait before sending any more data (only valid if the flag for it is * set) * @return How long the sender wants the recipient to wait before sending any more data in ms. */ public int getOptionalDelay() { return _optionDelay; } public void setOptionalDelay(int delayMs) { if (delayMs > MAX_DELAY_REQUEST) _optionDelay = MAX_DELAY_REQUEST; else if (delayMs < 0) _optionDelay = 0; else _optionDelay = delayMs; } /** * What is the largest payload the sender of this packet wants to receive? * * @return Maximum payload size sender can receive (MRU) */ public int getOptionalMaxSize() { return _optionMaxSize; } public void setOptionalMaxSize(int numBytes) { setFlag(FLAG_MAX_PACKET_SIZE_INCLUDED, numBytes > 0); _optionMaxSize = numBytes; } /** * Write the packet to the buffer (starting at the offset) and return * the number of bytes written. * * @param buffer bytes to write to a destination * @param offset starting point in the buffer to send * @return Count actually written * @throws IllegalStateException if there is data missing or otherwise b0rked */ public int writePacket(byte buffer[], int offset) throws IllegalStateException { return writePacket(buffer, offset, true); } /** * @param includeSig if true, include the real signature, otherwise put zeroes * in its place. */ private int writePacket(byte buffer[], int offset, boolean includeSig) throws IllegalStateException { int cur = offset; DataHelper.toLong(buffer, cur, 4, (_sendStreamId >= 0 ? _sendStreamId : STREAM_ID_UNKNOWN)); cur += 4; DataHelper.toLong(buffer, cur, 4, (_receiveStreamId >= 0 ? _receiveStreamId : STREAM_ID_UNKNOWN)); cur += 4; DataHelper.toLong(buffer, cur, 4, _sequenceNum > 0 ? _sequenceNum : 0); cur += 4; DataHelper.toLong(buffer, cur, 4, _ackThrough > 0 ? _ackThrough : 0); cur += 4; if (_nacks != null) { DataHelper.toLong(buffer, cur, 1, _nacks.length); cur++; for (int i = 0; i < _nacks.length; i++) { DataHelper.toLong(buffer, cur, 4, _nacks[i]); cur += 4; } } else { DataHelper.toLong(buffer, cur, 1, 0); cur++; } DataHelper.toLong(buffer, cur, 1, _resendDelay > 0 ? _resendDelay : 0); cur++; DataHelper.toLong(buffer, cur, 2, _flags); cur += 2; int optionSize = 0; if (isFlagSet(FLAG_DELAY_REQUESTED)) optionSize += 2; if (isFlagSet(FLAG_FROM_INCLUDED)) optionSize += _optionFrom.size(); if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) optionSize += 2; if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) optionSize += Signature.SIGNATURE_BYTES; DataHelper.toLong(buffer, cur, 2, optionSize); cur += 2; if (isFlagSet(FLAG_DELAY_REQUESTED)) { DataHelper.toLong(buffer, cur, 2, _optionDelay > 0 ? _optionDelay : 0); cur += 2; } if (isFlagSet(FLAG_FROM_INCLUDED)) { cur += _optionFrom.writeBytes(buffer, cur); } if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) { DataHelper.toLong(buffer, cur, 2, _optionMaxSize > 0 ? _optionMaxSize : DEFAULT_MAX_SIZE); cur += 2; } if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) { if (includeSig) System.arraycopy(_optionSignature.getData(), 0, buffer, cur, Signature.SIGNATURE_BYTES); else // we're signing (or validating) Arrays.fill(buffer, cur, cur+Signature.SIGNATURE_BYTES, (byte)0x0); cur += Signature.SIGNATURE_BYTES; } if (_payload != null) { try { System.arraycopy(_payload.getData(), _payload.getOffset(), buffer, cur, _payload.getValid()); } catch (ArrayIndexOutOfBoundsException aioobe) { System.err.println("payload.length: " + _payload.getValid() + " buffer.length: " + buffer.length + " cur: " + cur); throw aioobe; } cur += _payload.getValid(); } return cur - offset; } /** * how large would this packet be if we wrote it * @return How large the current packet would be * @throws IllegalStateException */ public int writtenSize() throws IllegalStateException { int size = 0; size += 4; // _sendStreamId.length; size += 4; // _receiveStreamId.length; size += 4; // sequenceNum size += 4; // ackThrough if (_nacks != null) { size++; // nacks length size += 4 * _nacks.length; } else { size++; // nacks length } size++; // resendDelay size += 2; // flags if (isFlagSet(FLAG_DELAY_REQUESTED)) size += 2; if (isFlagSet(FLAG_FROM_INCLUDED)) size += _optionFrom.size(); if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) size += 2; if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) size += Signature.SIGNATURE_BYTES; size += 2; // option size if (_payload != null) { size += _payload.getValid(); } return size; } /** * Read the packet from the buffer (starting at the offset) and return * the number of bytes read. * * @param buffer packet buffer containing the data * @param offset index into the buffer to start readign * @param length how many bytes within the buffer past the offset are * part of the packet? * * @throws IllegalArgumentException if the data is b0rked */ public void readPacket(byte buffer[], int offset, int length) throws IllegalArgumentException { if (buffer.length - offset < length) throw new IllegalArgumentException("len=" + buffer.length + " off=" + offset + " length=" + length); if (length < 22) // min header size throw new IllegalArgumentException("Too small: len=" + buffer.length); int cur = offset; setSendStreamId(DataHelper.fromLong(buffer, cur, 4)); cur += 4; setReceiveStreamId(DataHelper.fromLong(buffer, cur, 4)); cur += 4; setSequenceNum(DataHelper.fromLong(buffer, cur, 4)); cur += 4; setAckThrough(DataHelper.fromLong(buffer, cur, 4)); cur += 4; int numNacks = (int)DataHelper.fromLong(buffer, cur, 1); cur++; if (length < 22 + numNacks*4) throw new IllegalArgumentException("Too small with " + numNacks + " nacks: " + length); if (numNacks > 0) { long nacks[] = new long[numNacks]; for (int i = 0; i < numNacks; i++) { nacks[i] = DataHelper.fromLong(buffer, cur, 4); cur += 4; } setNacks(nacks); } else { setNacks(null); } setResendDelay((int)DataHelper.fromLong(buffer, cur, 1)); cur++; setFlags((int)DataHelper.fromLong(buffer, cur, 2)); cur += 2; int optionSize = (int)DataHelper.fromLong(buffer, cur, 2); cur += 2; if (length < 22 + numNacks*4 + optionSize) throw new IllegalArgumentException("Too small with " + numNacks + " nacks and " + optionSize + " options: " + length); int payloadBegin = cur + optionSize; int payloadSize = length - payloadBegin; if ( (payloadSize < 0) || (payloadSize > MAX_PAYLOAD_SIZE) ) throw new IllegalArgumentException("length: " + length + " offset: " + offset + " begin: " + payloadBegin); // skip ahead to the payload //_payload = new ByteArray(new byte[payloadSize]); _payload = new ByteArray(buffer, payloadBegin, payloadSize); //System.arraycopy(buffer, payloadBegin, _payload.getData(), 0, payloadSize); //_payload.setValid(payloadSize); //_payload.setOffset(0); // ok now lets go back and deal with the options if (isFlagSet(FLAG_DELAY_REQUESTED)) { setOptionalDelay((int)DataHelper.fromLong(buffer, cur, 2)); cur += 2; } if (isFlagSet(FLAG_FROM_INCLUDED)) { Destination optionFrom = new Destination(); try { cur += optionFrom.readBytes(buffer, cur); setOptionalFrom(optionFrom); } catch (DataFormatException dfe) { throw new IllegalArgumentException("Bad from field: " + dfe.getMessage()); } } if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) { setOptionalMaxSize((int)DataHelper.fromLong(buffer, cur, 2)); cur += 2; } if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) { Signature optionSignature = new Signature(); byte buf[] = new byte[Signature.SIGNATURE_BYTES]; System.arraycopy(buffer, cur, buf, 0, Signature.SIGNATURE_BYTES); optionSignature.setData(buf); setOptionalSignature(optionSignature); cur += Signature.SIGNATURE_BYTES; } } /** * Determine whether the signature on the data is valid. * * @param ctx Application context * @param from the Destination the data came from * @param buffer data to validate with signature * @return true if the signature exists and validates against the data, * false otherwise. */ public boolean verifySignature(I2PAppContext ctx, Destination from, byte buffer[]) { if (!isFlagSet(FLAG_SIGNATURE_INCLUDED)) return false; if (_optionSignature == null) return false; // prevent receiveNewSyn() ... !active ... sendReset() ... verifySignature ... NPE if (from == null) return false; int size = writtenSize(); if (buffer == null) buffer = new byte[size]; int written = writePacket(buffer, 0, false); if (written != size) { ctx.logManager().getLog(Packet.class).error("Written " + written + " size " + size + " for " + toString(), new Exception("moo")); return false; } boolean ok = ctx.dsa().verifySignature(_optionSignature, buffer, 0, size, from.getSigningPublicKey()); if (!ok) { Log l = ctx.logManager().getLog(Packet.class); if (l.shouldLog(Log.WARN)) l.warn("Signature failed on " + toString(), new Exception("moo")); if (false) { l.error(Base64.encode(buffer, 0, size)); l.error("Signature: " + Base64.encode(_optionSignature.getData())); } } return ok; } /** * Sign and write the packet to the buffer (starting at the offset) and return * the number of bytes written. * * @param buffer data to be written * @param offset starting point in the buffer * @param ctx Application Context * @param key signing key * @return Count of bytes written * @throws IllegalStateException if there is data missing or otherwise b0rked */ public int writeSignedPacket(byte buffer[], int offset, I2PAppContext ctx, SigningPrivateKey key) throws IllegalStateException { setFlag(FLAG_SIGNATURE_INCLUDED); int size = writePacket(buffer, offset, false); _optionSignature = ctx.dsa().sign(buffer, offset, size, key); if (false) { Log l = ctx.logManager().getLog(Packet.class); l.error("Signing: " + toString()); l.error(Base64.encode(buffer, 0, size)); l.error("Signature: " + Base64.encode(_optionSignature.getData())); } // jump into the signed data and inject the signature where we // previously placed a bunch of zeroes int signatureOffset = offset + 4 // sendStreamId + 4 // receiveStreamId + 4 // sequenceNum + 4 // ackThrough + (_nacks != null ? 4*_nacks.length + 1 : 1) + 1 // resendDelay + 2 // flags + 2 // optionSize + (isFlagSet(FLAG_DELAY_REQUESTED) ? 2 : 0) + (isFlagSet(FLAG_FROM_INCLUDED) ? _optionFrom.size() : 0) + (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED) ? 2 : 0); System.arraycopy(_optionSignature.getData(), 0, buffer, signatureOffset, Signature.SIGNATURE_BYTES); return size; } @Override public String toString() { StringBuffer str = formatAsString(); return str.toString(); } protected StringBuffer formatAsString() { StringBuffer buf = new StringBuffer(64); buf.append(toId(_sendStreamId)); //buf.append("<-->"); buf.append(toId(_receiveStreamId)).append(": #").append(_sequenceNum); if (_sequenceNum < 10) buf.append(" \t"); // so the tab lines up right else buf.append('\t'); buf.append(toFlagString()); buf.append(" ACK ").append(getAckThrough()); if (_nacks != null) { buf.append(" NACK"); for (int i = 0; i < _nacks.length; i++) { buf.append(" ").append(_nacks[i]); } } if ( (_payload != null) && (_payload.getValid() > 0) ) buf.append(" data: ").append(_payload.getValid()); return buf; } static final String toId(long id) { return Base64.encode(DataHelper.toLong(4, id)); } private final String toFlagString() { StringBuffer buf = new StringBuffer(32); if (isFlagSet(FLAG_CLOSE)) buf.append(" CLOSE"); if (isFlagSet(FLAG_DELAY_REQUESTED)) buf.append(" DELAY ").append(_optionDelay); if (isFlagSet(FLAG_ECHO)) buf.append(" ECHO"); if (isFlagSet(FLAG_FROM_INCLUDED)) buf.append(" FROM"); if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) buf.append(" MS ").append(_optionMaxSize); if (isFlagSet(FLAG_PROFILE_INTERACTIVE)) buf.append(" INTERACTIVE"); if (isFlagSet(FLAG_RESET)) buf.append(" RESET"); if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) buf.append(" SIG"); if (isFlagSet(FLAG_SIGNATURE_REQUESTED)) buf.append(" SIGREQ"); if (isFlagSet(FLAG_SYNCHRONIZE)) buf.append(" SYN"); return buf.toString(); } }
apps/streaming/java/src/net/i2p/client/streaming/Packet.java
package net.i2p.client.streaming; import java.util.Arrays; import net.i2p.I2PAppContext; import net.i2p.data.Base64; import net.i2p.data.ByteArray; import net.i2p.data.DataFormatException; import net.i2p.data.DataHelper; import net.i2p.data.Destination; import net.i2p.data.Signature; import net.i2p.data.SigningPrivateKey; import net.i2p.util.Log; /** * Contain a single packet transferred as part of a streaming connection. * The data format is as follows:<ul> * <li>{@link #getSendStreamId sendStreamId} [4 byte value]</li> * <li>{@link #getReceiveStreamId receiveStreamId} [4 byte value]</li> * <li>{@link #getSequenceNum sequenceNum} [4 byte unsigned integer]</li> * <li>{@link #getAckThrough ackThrough} [4 byte unsigned integer]</li> * <li>number of NACKs [1 byte unsigned integer]</li> * <li>that many {@link #getNacks NACKs}</li> * <li>{@link #getResendDelay resendDelay} [1 byte integer]</li> * <li>flags [2 byte value]</li> * <li>option data size [2 byte integer]</li> * <li>option data specified by those flags [0 or more bytes]</li> * <li>payload [remaining packet size]</li> * </ul> * * <p>The flags field above specifies some metadata about the packet, and in * turn may require certain additional data to be included. The flags are * as follows (with any data structures specified added to the options area * in the given order):</p><ol> * <li>{@link #FLAG_SYNCHRONIZE}: no option data</li> * <li>{@link #FLAG_CLOSE}: no option data</li> * <li>{@link #FLAG_RESET}: no option data</li> * <li>{@link #FLAG_SIGNATURE_INCLUDED}: {@link net.i2p.data.Signature}</li> * <li>{@link #FLAG_SIGNATURE_REQUESTED}: no option data</li> * <li>{@link #FLAG_FROM_INCLUDED}: {@link net.i2p.data.Destination}</li> * <li>{@link #FLAG_DELAY_REQUESTED}: 2 byte integer</li> * <li>{@link #FLAG_MAX_PACKET_SIZE_INCLUDED}: 2 byte integer</li> * <li>{@link #FLAG_PROFILE_INTERACTIVE}: no option data</li> * </ol> * * <p>If the signature is included, it uses the Destination's DSA key * to sign the entire header and payload with the space in the options * for the signature being set to all zeroes.</p> * * <p>If the sequenceNum is 0 and the SYN is not set, this is a plain ACK * packet that should not be ACKed</p> * */ public class Packet { private long _sendStreamId; private long _receiveStreamId; private long _sequenceNum; private long _ackThrough; private long _nacks[]; private int _resendDelay; private int _flags; private ByteArray _payload; // the next four are set only if the flags say so private Signature _optionSignature; private Destination _optionFrom; private int _optionDelay; private int _optionMaxSize; /** * The receiveStreamId will be set to this when the packet doesn't know * what ID will be assigned by the remote peer (aka this is the initial * synchronize packet) * */ public static final long STREAM_ID_UNKNOWN = 0l; public static final long MAX_STREAM_ID = 0xffffffffl; /** * This packet is creating a new socket connection (if the receiveStreamId * is STREAM_ID_UNKNOWN) or it is acknowledging a request to * create a connection and in turn is accepting the socket. * */ public static final int FLAG_SYNCHRONIZE = (1 << 0); /** * The sender of this packet will not be sending any more payload data. */ public static final int FLAG_CLOSE = (1 << 1); /** * This packet is being sent to signify that the socket does not exist * (or, if in response to an initial synchronize packet, that the * connection was refused). * */ public static final int FLAG_RESET = (1 << 2); /** * This packet contains a DSA signature from the packet's sender. This * signature is within the packet options. All synchronize packets must * have this flag set. * */ public static final int FLAG_SIGNATURE_INCLUDED = (1 << 3); /** * This packet wants the recipient to include signatures on subsequent * packets sent to the creator of this packet. */ public static final int FLAG_SIGNATURE_REQUESTED = (1 << 4); /** * This packet includes the full I2P destination of the packet's sender. * The initial synchronize packet must have this flag set. */ public static final int FLAG_FROM_INCLUDED = (1 << 5); /** * This packet includes an explicit request for the recipient to delay * sending any packets with data for a given amount of time. * */ public static final int FLAG_DELAY_REQUESTED = (1 << 6); /** * This packet includes a request that the recipient not send any * subsequent packets with payloads greater than a specific size. * If not set and no prior value was delivered, the maximum value * will be assumed (approximately 32KB). * */ public static final int FLAG_MAX_PACKET_SIZE_INCLUDED = (1 << 7); /** * If set, this packet is travelling as part of an interactive flow, * meaning it is more lag sensitive than throughput sensitive. aka * send data ASAP rather than waiting around to send full packets. * */ public static final int FLAG_PROFILE_INTERACTIVE = (1 << 8); /** * If set, this packet is a ping (if sendStreamId is set) or a * ping reply (if receiveStreamId is set). */ public static final int FLAG_ECHO = (1 << 9); /** * If set, this packet doesn't really want to ack anything */ public static final int FLAG_NO_ACK = (1 << 10); public static final int DEFAULT_MAX_SIZE = 32*1024; private static final int MAX_DELAY_REQUEST = 65535; public Packet() { } private boolean _sendStreamIdSet = false; /** what stream do we send data to the peer on? * @return stream ID we use to send data */ public long getSendStreamId() { return _sendStreamId; } public void setSendStreamId(long id) { if ( (_sendStreamIdSet) && (_sendStreamId > 0) ) throw new RuntimeException("Send stream ID already set [" + _sendStreamId + ", " + id + "]"); _sendStreamIdSet = true; _sendStreamId = id; } private boolean _receiveStreamIdSet = false; /** * stream the replies should be sent on. this should be 0 if the * connection is still being built. * @return stream ID we use to get data, zero if the connection is still being built. */ public long getReceiveStreamId() { return _receiveStreamId; } public void setReceiveStreamId(long id) { if ( (_receiveStreamIdSet) && (_receiveStreamId > 0) ) throw new RuntimeException("Receive stream ID already set [" + _receiveStreamId + ", " + id + "]"); _receiveStreamIdSet = true; _receiveStreamId = id; } /** 0-indexed sequence number for this Packet in the sendStream * @return 0-indexed sequence number for current Packet in current sendStream */ public long getSequenceNum() { return _sequenceNum; } public void setSequenceNum(long num) { _sequenceNum = num; } /** * The highest packet sequence number that received * on the receiveStreamId. This field is ignored on the initial * connection packet (where receiveStreamId is the unknown id) or * if FLAG_NO_ACK is set. * * @return The highest packet sequence number received on receiveStreamId */ public long getAckThrough() { if (isFlagSet(FLAG_NO_ACK)) return -1; else return _ackThrough; } public void setAckThrough(long id) { if (id < 0) setFlag(FLAG_NO_ACK); _ackThrough = id; } /** * List of packet sequence numbers below the getAckThrough() value * have not been received. this may be null. * * @return List of packet sequence numbers not ACKed, or null if there are none. */ public long[] getNacks() { return _nacks; } public void setNacks(long nacks[]) { _nacks = nacks; } /** * How long is the creator of this packet going to wait before * resending this packet (if it hasn't yet been ACKed). The * value is seconds since the packet was created. * * @return Delay before resending a packet in seconds. */ public int getResendDelay() { return _resendDelay; } public void setResendDelay(int numSeconds) { _resendDelay = numSeconds; } public static final int MAX_PAYLOAD_SIZE = 32*1024; /** get the actual payload of the message. may be null * @return the payload of the message, null if none. */ public ByteArray getPayload() { return _payload; } public void setPayload(ByteArray payload) { _payload = payload; if ( (payload != null) && (payload.getValid() > MAX_PAYLOAD_SIZE) ) throw new IllegalArgumentException("Too large payload: " + payload.getValid()); } public int getPayloadSize() { return (_payload == null ? 0 : _payload.getValid()); } public void releasePayload() { //_payload = null; } public ByteArray acquirePayload() { ByteArray old = _payload; _payload = new ByteArray(new byte[Packet.MAX_PAYLOAD_SIZE]); return _payload; } /** is a particular flag set on this packet? * @param flag bitmask of any flag(s) * @return true if set, false if not. */ public boolean isFlagSet(int flag) { return 0 != (_flags & flag); } public void setFlag(int flag) { _flags |= flag; } public void setFlag(int flag, boolean set) { if (set) _flags |= flag; else _flags &= ~flag; } public void setFlags(int flags) { _flags = flags; } /** the signature on the packet (only included if the flag for it is set) * @return signature on the packet if the flag for signatures is set */ public Signature getOptionalSignature() { return _optionSignature; } public void setOptionalSignature(Signature sig) { setFlag(FLAG_SIGNATURE_INCLUDED, sig != null); _optionSignature = sig; } /** the sender of the packet (only included if the flag for it is set) * @return the sending Destination */ public Destination getOptionalFrom() { return _optionFrom; } public void setOptionalFrom(Destination from) { setFlag(FLAG_FROM_INCLUDED, from != null); if (from == null) throw new RuntimeException("from is null!?"); _optionFrom = from; } /** * How many milliseconds the sender of this packet wants the recipient * to wait before sending any more data (only valid if the flag for it is * set) * @return How long the sender wants the recipient to wait before sending any more data in ms. */ public int getOptionalDelay() { return _optionDelay; } public void setOptionalDelay(int delayMs) { if (delayMs > MAX_DELAY_REQUEST) _optionDelay = MAX_DELAY_REQUEST; else if (delayMs < 0) _optionDelay = 0; else _optionDelay = delayMs; } /** * What is the largest payload the sender of this packet wants to receive? * * @return Maximum payload size sender can receive (MRU) */ public int getOptionalMaxSize() { return _optionMaxSize; } public void setOptionalMaxSize(int numBytes) { setFlag(FLAG_MAX_PACKET_SIZE_INCLUDED, numBytes > 0); _optionMaxSize = numBytes; } /** * Write the packet to the buffer (starting at the offset) and return * the number of bytes written. * * @param buffer bytes to write to a destination * @param offset starting point in the buffer to send * @return Count actually written * @throws IllegalStateException if there is data missing or otherwise b0rked */ public int writePacket(byte buffer[], int offset) throws IllegalStateException { return writePacket(buffer, offset, true); } /** * @param includeSig if true, include the real signature, otherwise put zeroes * in its place. */ private int writePacket(byte buffer[], int offset, boolean includeSig) throws IllegalStateException { int cur = offset; DataHelper.toLong(buffer, cur, 4, (_sendStreamId >= 0 ? _sendStreamId : STREAM_ID_UNKNOWN)); cur += 4; DataHelper.toLong(buffer, cur, 4, (_receiveStreamId >= 0 ? _receiveStreamId : STREAM_ID_UNKNOWN)); cur += 4; DataHelper.toLong(buffer, cur, 4, _sequenceNum > 0 ? _sequenceNum : 0); cur += 4; DataHelper.toLong(buffer, cur, 4, _ackThrough > 0 ? _ackThrough : 0); cur += 4; if (_nacks != null) { DataHelper.toLong(buffer, cur, 1, _nacks.length); cur++; for (int i = 0; i < _nacks.length; i++) { DataHelper.toLong(buffer, cur, 4, _nacks[i]); cur += 4; } } else { DataHelper.toLong(buffer, cur, 1, 0); cur++; } DataHelper.toLong(buffer, cur, 1, _resendDelay > 0 ? _resendDelay : 0); cur++; DataHelper.toLong(buffer, cur, 2, _flags); cur += 2; int optionSize = 0; if (isFlagSet(FLAG_DELAY_REQUESTED)) optionSize += 2; if (isFlagSet(FLAG_FROM_INCLUDED)) optionSize += _optionFrom.size(); if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) optionSize += 2; if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) optionSize += Signature.SIGNATURE_BYTES; DataHelper.toLong(buffer, cur, 2, optionSize); cur += 2; if (isFlagSet(FLAG_DELAY_REQUESTED)) { DataHelper.toLong(buffer, cur, 2, _optionDelay > 0 ? _optionDelay : 0); cur += 2; } if (isFlagSet(FLAG_FROM_INCLUDED)) { cur += _optionFrom.writeBytes(buffer, cur); } if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) { DataHelper.toLong(buffer, cur, 2, _optionMaxSize > 0 ? _optionMaxSize : DEFAULT_MAX_SIZE); cur += 2; } if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) { if (includeSig) System.arraycopy(_optionSignature.getData(), 0, buffer, cur, Signature.SIGNATURE_BYTES); else // we're signing (or validating) Arrays.fill(buffer, cur, cur+Signature.SIGNATURE_BYTES, (byte)0x0); cur += Signature.SIGNATURE_BYTES; } if (_payload != null) { try { System.arraycopy(_payload.getData(), _payload.getOffset(), buffer, cur, _payload.getValid()); } catch (ArrayIndexOutOfBoundsException aioobe) { System.err.println("payload.length: " + _payload.getValid() + " buffer.length: " + buffer.length + " cur: " + cur); throw aioobe; } cur += _payload.getValid(); } return cur - offset; } /** * how large would this packet be if we wrote it * @return How large the current packet would be * @throws IllegalStateException */ public int writtenSize() throws IllegalStateException { int size = 0; size += 4; // _sendStreamId.length; size += 4; // _receiveStreamId.length; size += 4; // sequenceNum size += 4; // ackThrough if (_nacks != null) { size++; // nacks length size += 4 * _nacks.length; } else { size++; // nacks length } size++; // resendDelay size += 2; // flags if (isFlagSet(FLAG_DELAY_REQUESTED)) size += 2; if (isFlagSet(FLAG_FROM_INCLUDED)) size += _optionFrom.size(); if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) size += 2; if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) size += Signature.SIGNATURE_BYTES; size += 2; // option size if (_payload != null) { size += _payload.getValid(); } return size; } /** * Read the packet from the buffer (starting at the offset) and return * the number of bytes read. * * @param buffer packet buffer containing the data * @param offset index into the buffer to start readign * @param length how many bytes within the buffer past the offset are * part of the packet? * * @throws IllegalArgumentException if the data is b0rked */ public void readPacket(byte buffer[], int offset, int length) throws IllegalArgumentException { if (buffer.length - offset < length) throw new IllegalArgumentException("len=" + buffer.length + " off=" + offset + " length=" + length); if (length < 22) // min header size throw new IllegalArgumentException("Too small: len=" + buffer.length); int cur = offset; setSendStreamId(DataHelper.fromLong(buffer, cur, 4)); cur += 4; setReceiveStreamId(DataHelper.fromLong(buffer, cur, 4)); cur += 4; setSequenceNum(DataHelper.fromLong(buffer, cur, 4)); cur += 4; setAckThrough(DataHelper.fromLong(buffer, cur, 4)); cur += 4; int numNacks = (int)DataHelper.fromLong(buffer, cur, 1); cur++; if (length < 22 + numNacks*4) throw new IllegalArgumentException("Too small with " + numNacks + " nacks: " + length); if (numNacks > 0) { long nacks[] = new long[numNacks]; for (int i = 0; i < numNacks; i++) { nacks[i] = DataHelper.fromLong(buffer, cur, 4); cur += 4; } setNacks(nacks); } else { setNacks(null); } setResendDelay((int)DataHelper.fromLong(buffer, cur, 1)); cur++; setFlags((int)DataHelper.fromLong(buffer, cur, 2)); cur += 2; int optionSize = (int)DataHelper.fromLong(buffer, cur, 2); cur += 2; if (length < 22 + numNacks*4 + optionSize) throw new IllegalArgumentException("Too small with " + numNacks + " nacks and " + optionSize + " options: " + length); int payloadBegin = cur + optionSize; int payloadSize = length - payloadBegin; if ( (payloadSize < 0) || (payloadSize > MAX_PAYLOAD_SIZE) ) throw new IllegalArgumentException("length: " + length + " offset: " + offset + " begin: " + payloadBegin); // skip ahead to the payload //_payload = new ByteArray(new byte[payloadSize]); _payload = new ByteArray(buffer, payloadBegin, payloadSize); //System.arraycopy(buffer, payloadBegin, _payload.getData(), 0, payloadSize); //_payload.setValid(payloadSize); //_payload.setOffset(0); // ok now lets go back and deal with the options if (isFlagSet(FLAG_DELAY_REQUESTED)) { setOptionalDelay((int)DataHelper.fromLong(buffer, cur, 2)); cur += 2; } if (isFlagSet(FLAG_FROM_INCLUDED)) { Destination optionFrom = new Destination(); try { cur += optionFrom.readBytes(buffer, cur); setOptionalFrom(optionFrom); } catch (DataFormatException dfe) { throw new IllegalArgumentException("Bad from field: " + dfe.getMessage()); } } if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) { setOptionalMaxSize((int)DataHelper.fromLong(buffer, cur, 2)); cur += 2; } if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) { Signature optionSignature = new Signature(); byte buf[] = new byte[Signature.SIGNATURE_BYTES]; System.arraycopy(buffer, cur, buf, 0, Signature.SIGNATURE_BYTES); optionSignature.setData(buf); setOptionalSignature(optionSignature); cur += Signature.SIGNATURE_BYTES; } } /** * Determine whether the signature on the data is valid. * * @param ctx Application context * @param from the Destination the data came from * @param buffer data to validate with signature * @return true if the signature exists and validates against the data, * false otherwise. */ public boolean verifySignature(I2PAppContext ctx, Destination from, byte buffer[]) { if (!isFlagSet(FLAG_SIGNATURE_INCLUDED)) return false; if (_optionSignature == null) return false; // prevent receiveNewSyn() ... !active ... sendReset() ... verifySignature ... NPE if (from == null) return false; int size = writtenSize(); if (buffer == null) buffer = new byte[size]; int written = writePacket(buffer, 0, false); if (written != size) { ctx.logManager().getLog(Packet.class).error("Written " + written + " size " + size + " for " + toString(), new Exception("moo")); return false; } boolean ok = ctx.dsa().verifySignature(_optionSignature, buffer, 0, size, from.getSigningPublicKey()); if (!ok) { Log l = ctx.logManager().getLog(Packet.class); if (l.shouldLog(Log.WARN)) l.warn("Signature failed on " + toString(), new Exception("moo")); if (false) { l.error(Base64.encode(buffer, 0, size)); l.error("Signature: " + Base64.encode(_optionSignature.getData())); } } return ok; } /** * Sign and write the packet to the buffer (starting at the offset) and return * the number of bytes written. * * @param buffer data to be written * @param offset starting point in the buffer * @param ctx Application Context * @param key signing key * @return Count of bytes written * @throws IllegalStateException if there is data missing or otherwise b0rked */ public int writeSignedPacket(byte buffer[], int offset, I2PAppContext ctx, SigningPrivateKey key) throws IllegalStateException { setFlag(FLAG_SIGNATURE_INCLUDED); int size = writePacket(buffer, offset, false); _optionSignature = ctx.dsa().sign(buffer, offset, size, key); if (false) { Log l = ctx.logManager().getLog(Packet.class); l.error("Signing: " + toString()); l.error(Base64.encode(buffer, 0, size)); l.error("Signature: " + Base64.encode(_optionSignature.getData())); } // jump into the signed data and inject the signature where we // previously placed a bunch of zeroes int signatureOffset = offset + 4 // sendStreamId + 4 // receiveStreamId + 4 // sequenceNum + 4 // ackThrough + (_nacks != null ? 4*_nacks.length + 1 : 1) + 1 // resendDelay + 2 // flags + 2 // optionSize + (isFlagSet(FLAG_DELAY_REQUESTED) ? 2 : 0) + (isFlagSet(FLAG_FROM_INCLUDED) ? _optionFrom.size() : 0) + (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED) ? 2 : 0); System.arraycopy(_optionSignature.getData(), 0, buffer, signatureOffset, Signature.SIGNATURE_BYTES); return size; } @Override public String toString() { StringBuffer str = formatAsString(); return str.toString(); } protected StringBuffer formatAsString() { StringBuffer buf = new StringBuffer(64); buf.append(toId(_sendStreamId)); //buf.append("<-->"); buf.append(toId(_receiveStreamId)).append(": #").append(_sequenceNum); if (_sequenceNum < 10) buf.append(" \t"); // so the tab lines up right else buf.append('\t'); buf.append(toFlagString()); buf.append(" ACK ").append(getAckThrough()); if (_nacks != null) { buf.append(" NACK"); for (int i = 0; i < _nacks.length; i++) { buf.append(" ").append(_nacks[i]); } } if ( (_payload != null) && (_payload.getValid() > 0) ) buf.append(" data: ").append(_payload.getValid()); return buf; } static final String toId(long id) { return Base64.encode(DataHelper.toLong(4, id)); } private final String toFlagString() { StringBuffer buf = new StringBuffer(32); if (isFlagSet(FLAG_CLOSE)) buf.append(" CLOSE"); if (isFlagSet(FLAG_DELAY_REQUESTED)) buf.append(" DELAY ").append(_optionDelay); if (isFlagSet(FLAG_ECHO)) buf.append(" ECHO"); if (isFlagSet(FLAG_FROM_INCLUDED)) buf.append(" FROM"); if (isFlagSet(FLAG_MAX_PACKET_SIZE_INCLUDED)) buf.append(" MS ").append(_optionMaxSize); if (isFlagSet(FLAG_PROFILE_INTERACTIVE)) buf.append(" INTERACTIVE"); if (isFlagSet(FLAG_RESET)) buf.append(" RESET"); if (isFlagSet(FLAG_SIGNATURE_INCLUDED)) buf.append(" SIG"); if (isFlagSet(FLAG_SIGNATURE_REQUESTED)) buf.append(" SIGREQ"); if (isFlagSet(FLAG_SYNCHRONIZE)) buf.append(" SYN"); return buf.toString(); } }
export symbol
apps/streaming/java/src/net/i2p/client/streaming/Packet.java
export symbol
<ide><path>pps/streaming/java/src/net/i2p/client/streaming/Packet.java <ide> public static final int FLAG_NO_ACK = (1 << 10); <ide> <ide> public static final int DEFAULT_MAX_SIZE = 32*1024; <del> private static final int MAX_DELAY_REQUEST = 65535; <add> protected static final int MAX_DELAY_REQUEST = 65535; <ide> <ide> public Packet() { } <ide>
Java
apache-2.0
adaa8cd947d82d1e6e0d9ecdcfeea0ca078b874d
0
theanuradha/cubeon
/* * Copyright 2008 Anuradha. * * 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. * under the License. */ package org.netbeans.cubeon.jira.repository; import com.dolby.jira.net.soap.jira.RemoteFieldValue; import com.dolby.jira.net.soap.jira.RemoteIssue; import java.util.ArrayList; import java.util.List; import org.netbeans.cubeon.jira.repository.attributes.JiraProject.Component; import org.netbeans.cubeon.jira.repository.attributes.JiraProject.Version; import org.netbeans.cubeon.jira.tasks.JiraTask; import org.netbeans.cubeon.tasks.spi.task.TaskPriority; import org.netbeans.cubeon.tasks.spi.task.TaskResolution; import org.netbeans.cubeon.tasks.spi.task.TaskType; /** * * @author Anuradha */ public class JiraUtils { public static RemoteFieldValue[] changedFieldValues(RemoteIssue issue, JiraTask task) { List<RemoteFieldValue> fieldValues = new ArrayList<RemoteFieldValue>(); String description = task.getDescription(); if (!issue.getDescription().equals(description)) { fieldValues.add(new RemoteFieldValue("description", new String[]{description})); } String environment = task.getEnvironment(); if (!issue.getEnvironment().equals(environment)) { fieldValues.add(new RemoteFieldValue("environment", new String[]{environment})); } String name = task.getName(); if (!name.equals(issue.getSummary())) { fieldValues.add(new RemoteFieldValue("summary", new String[]{name})); } TaskType type = task.getType(); if (type != null && !type.getId().equals(issue.getType())) { fieldValues.add(new RemoteFieldValue("issuetype", new String[]{type.getId()})); } TaskPriority priority = task.getPriority(); if (priority != null && !priority.getId().equals(issue.getPriority())) { fieldValues.add(new RemoteFieldValue("priority", new String[]{priority.getId()})); } TaskResolution resolution = task.getResolution(); if (resolution != null && !resolution.getId().equals(issue.getResolution())) { fieldValues.add(new RemoteFieldValue("resolution", new String[]{resolution.getId()})); } List<Component> components = task.getComponents(); List<String> componentIds = new ArrayList<String>(); for (Component component : components) { componentIds.add(component.getId()); } fieldValues.add(new RemoteFieldValue("components", componentIds.toArray(new String[componentIds.size()]))); //---------------------------- List<Version> affectedVersions = task.getAffectedVersions(); List<String> affectedVersionIds = new ArrayList<String>(); for (Version version : affectedVersions) { affectedVersionIds.add(version.getId()); } fieldValues.add(new RemoteFieldValue("versions", affectedVersionIds.toArray(new String[affectedVersionIds.size()]))); //---------------------------- List<Version> fixVersions = task.getFixVersions(); List<String> fixVersionsIds = new ArrayList<String>(); for (Version version : fixVersions) { fixVersionsIds.add(version.getId()); } fieldValues.add(new RemoteFieldValue("fixVersions", fixVersionsIds.toArray(new String[fixVersionsIds.size()]))); return fieldValues.toArray(new RemoteFieldValue[fieldValues.size()]); } }
connectors/jira/core/src/main/java/org/netbeans/cubeon/jira/repository/JiraUtils.java
/* * Copyright 2008 Anuradha. * * 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. * under the License. */ package org.netbeans.cubeon.jira.repository; import com.dolby.jira.net.soap.jira.RemoteFieldValue; import com.dolby.jira.net.soap.jira.RemoteIssue; import java.util.ArrayList; import java.util.List; import org.netbeans.cubeon.jira.repository.attributes.JiraProject.Component; import org.netbeans.cubeon.jira.repository.attributes.JiraProject.Version; import org.netbeans.cubeon.jira.tasks.JiraTask; import org.netbeans.cubeon.tasks.spi.task.TaskPriority; import org.netbeans.cubeon.tasks.spi.task.TaskResolution; import org.netbeans.cubeon.tasks.spi.task.TaskStatus; import org.netbeans.cubeon.tasks.spi.task.TaskType; /** * * @author Anuradha */ public class JiraUtils { public static RemoteFieldValue[] changedFieldValues(RemoteIssue issue, JiraTask task) { List<RemoteFieldValue> fieldValues = new ArrayList<RemoteFieldValue>(); String description = task.getDescription(); if (!issue.getDescription().equals(description)) { fieldValues.add(new RemoteFieldValue("description", new String[]{description})); } String environment = task.getEnvironment(); if (!issue.getEnvironment().equals(environment)) { fieldValues.add(new RemoteFieldValue("environment", new String[]{environment})); } String name = task.getName(); if (!name.equals(issue.getSummary())) { fieldValues.add(new RemoteFieldValue("summary", new String[]{name})); } TaskType type = task.getType(); if (type != null && !type.getId().equals(issue.getType())) { fieldValues.add(new RemoteFieldValue("issuetype", new String[]{type.getId()})); } TaskPriority priority = task.getPriority(); if (priority != null && !priority.getId().equals(issue.getPriority())) { fieldValues.add(new RemoteFieldValue("priority", new String[]{priority.getId()})); } TaskResolution resolution = task.getResolution(); if (resolution != null && !resolution.getId().equals(issue.getResolution())) { fieldValues.add(new RemoteFieldValue("resolution", new String[]{resolution.getId()})); } List<Component> components = task.getComponents(); List<String> componentIds = new ArrayList<String>(); for (Component component : components) { componentIds.add(component.getId()); } fieldValues.add(new RemoteFieldValue("components", componentIds.toArray(new String[componentIds.size()]))); //---------------------------- List<Version> affectedVersions = task.getAffectedVersions(); List<String> affectedVersionIds = new ArrayList<String>(); for (Version version : affectedVersions) { affectedVersionIds.add(version.getId()); } fieldValues.add(new RemoteFieldValue("versions", affectedVersionIds.toArray(new String[affectedVersionIds.size()]))); //---------------------------- List<Version> fixVersions = task.getFixVersions(); List<String> fixVersionsIds = new ArrayList<String>(); for (Version version : fixVersions) { fixVersionsIds.add(version.getId()); } fieldValues.add(new RemoteFieldValue("fixVersions", fixVersionsIds.toArray(new String[fixVersionsIds.size()]))); return fieldValues.toArray(new RemoteFieldValue[fieldValues.size()]); } }
LOCAL-102 : Remove set status from spi and move realted actions to local repository
connectors/jira/core/src/main/java/org/netbeans/cubeon/jira/repository/JiraUtils.java
LOCAL-102 : Remove set status from spi and move realted actions to local repository
<ide><path>onnectors/jira/core/src/main/java/org/netbeans/cubeon/jira/repository/JiraUtils.java <ide> import org.netbeans.cubeon.jira.tasks.JiraTask; <ide> import org.netbeans.cubeon.tasks.spi.task.TaskPriority; <ide> import org.netbeans.cubeon.tasks.spi.task.TaskResolution; <del>import org.netbeans.cubeon.tasks.spi.task.TaskStatus; <ide> import org.netbeans.cubeon.tasks.spi.task.TaskType; <ide> <ide> /**
JavaScript
mit
946d0690c373a09f870f78d508e2c364b949b9af
0
AtuyL/stylsprite
'use strict'; var fs = require('fs'), exec = require('child_process').exec, async = require('async'), chalk = require('chalk'), Lab = require('lab'), lab = Lab.script(), suite = lab.suite, test = lab.test, before = lab.before, after = lab.after, expect = Lab.expect; exports.lab = lab; lab.experiment('standalone use', function () { var stylsprite = require('../lib'); lab.before(function (done) { var readFilesDeep = require('../lib/utils/fs').readFilesDeep; /*jslint unparam: true */ readFilesDeep('test/public', null, null, function (error, result) { var array = require('../lib/utils/array'), flatten = array.flatten; async.each(flatten(result), fs.unlink, function () { done(); }); }); /*jslint unparam: false */ }); lab.test('absolute', function (done) { var src = fs.createReadStream('test/src/stylus/absolute.styl', { flags: 'r', encoding: 'utf8', fd: null, // mode: 0666, autoClose: false }), dest = fs.createWriteStream('test/public/css/absolute.css'), transform = stylsprite.transform(src.path, { root: 'test/public', imgsrc: 'test/src/imgsrc', padding: 2 }); src .pipe(transform) .pipe(dest); dest.on('unpipe', function () { done(); }); }); }); lab.experiment('utils', function () { var flatten = require('../lib/utils/array').flatten, uniq = require('../lib/utils/array').uniq, readFilesDeep = require('../lib/utils/fs').readFilesDeep; lab.test('array.flatten', function (done) { var cases = [ null, [1], 2, [ [3, 4], 5 ], [ [ [] ] ], [ [ [6] ] ], 7, 8, [], null ]; cases = flatten(cases); // console.log(JSON.stringify(cases, null, ' ')); expect(cases.join(',')).to.equal(',1,2,3,4,5,6,7,8,'); done(); }); lab.test('array.uniq', function (done) { var cases = ['a', 'b', 'a', null, undefined, null, undefined, NaN], equal = ['a', 'b', null, undefined], result; cases = uniq(cases); result = cases.every(function (value, index) { return equal[index] === value; }); expect(result).to.equal(true); done(); }); lab.test('fs.readFilesDeep', function (done) { /*jslint unparam: true */ readFilesDeep('test/public', null, null, function (error, result) { // console.log(''); // console.log(JSON.stringify(result, null, ' ')); // result = flatten(result); // console.log(JSON.stringify(result, null, ' ')); async.each(flatten(result), fs.unlink, function () { done(); }); }); /*jslint unparam: false */ }); }); lab.experiment('middleware', function () { var express = require('express'), stylus = require('stylus'), stylsprite = require('../lib'); lab.beforeEach(function (done) { var readFilesDeep = require('../lib/utils/fs').readFilesDeep; /*jslint unparam: true */ readFilesDeep('test/public', null, null, function (error, result) { var array = require('../lib/utils/array'), flatten = array.flatten; async.each(flatten(result), fs.unlink, function () { done(); }); }); /*jslint unparam: false */ }); lab.test('curl requests', function (done) { var app = express(), options = { src: 'test/src/stylus', dest: 'test/public/css', root: 'test/public', imgsrc: 'test/src/imgsrc' }, stylsprite_mw = stylsprite.middleware(options, { padding: 2 }), stylus_mw = stylus.middleware(options); app.set('views', __dirname + '/src'); app.set('view engine', 'jade'); app.use('/css', stylsprite_mw); app.use('/css', stylus_mw); app.use(express["static"](__dirname + '/public')); /*jslint unparam: true */ app.get('/', function (req, res) { return res.render('index'); }); app.listen(8080, function () { async.series([ function (next) { exec('curl http://localhost:8080/css/relative.css', function (error, stdout, stderr) { next(error); }); }, function (next) { exec('curl http://localhost:8080/css/absolute.css', function (error, stdout, stderr) { next(error); }); } ], function (error) { done(error); }); }); /*jslint unparam: false */ }); lab.test('onestop option', function (done) { var app = express(), options = { src: 'test/src/stylus', dest: 'test/public/css', root: 'test/public', imgsrc: 'test/src/imgsrc' }, stylsprite_mw = stylsprite.middleware(options, { padding: 2, onestop: true }); app.set('views', __dirname + '/src'); app.set('view engine', 'jade'); app.use('/css', stylsprite_mw); app.use(express["static"](__dirname + '/public')); /*jslint unparam: true */ app.get('/', function (req, res) { return res.render('index'); }); app.listen(8888, function () { async.series([ function (next) { exec('curl http://localhost:8888/css/relative.css', function (error, stdout, stderr) { next(error); }); }, function (next) { exec('curl http://localhost:8888/css/absolute.css', function (error, stdout, stderr) { next(error); }); } ], function (error) { done(error); }); }); /*jslint unparam: false */ }); });
test/index.js
'use strict'; var fs = require('fs'), exec = require('child_process').exec, async = require('async'), chalk = require('chalk'), Lab = require('lab'), lab = Lab.script(), suite = lab.suite, test = lab.test, before = lab.before, after = lab.after, expect = Lab.expect; exports.lab = lab; lab.experiment('standalone use', function () { var stylsprite = require('../lib'); lab.before(function (done) { var readFilesDeep = require('../lib/utils/fs').readFilesDeep; /*jslint unparam: true */ readFilesDeep('test/public', null, null, function (error, result) { var array = require('../lib/utils/array'), flatten = array.flatten; async.each(flatten(result), fs.unlink, function () { done(); }); }); /*jslint unparam: false */ }); lab.test('absolute', function (done) { var src = fs.createReadStream('test/src/stylus/absolute.styl', { flags: 'r', encoding: 'utf8', fd: null, // mode: 0666, autoClose: false }), dest = fs.createWriteStream('test/public/css/absolute.css'), transform = stylsprite.transform(src.path, { root: 'test/public', imgsrc: 'test/src/imgsrc', padding: 2 }); src .pipe(transform) .pipe(dest); dest.on('unpipe', function () { done(); }); }); }); lab.experiment('utils', function () { var flatten = require('../lib/utils/array').flatten, uniq = require('../lib/utils/array').uniq, readFilesDeep = require('../lib/utils/fs').readFilesDeep; lab.test('array.flatten', function (done) { var cases = [ null, [1], 2, [ [3, 4], 5 ], [ [ [] ] ], [ [ [6] ] ], 7, 8, [], null ]; cases = flatten(cases); // console.log(JSON.stringify(cases, null, ' ')); expect(cases.join(',')).to.equal(',1,2,3,4,5,6,7,8,'); done(); }); lab.test('array.uniq', function (done) { var cases = ['a', 'b', 'a', null, undefined, null, undefined, NaN], equal = ['a', 'b', null, undefined], result; cases = uniq(cases); result = cases.every(function (value, index) { return equal[index] === value; }); expect(result).to.equal(true); done(); }); lab.test('fs.readFilesDeep', function (done) { /*jslint unparam: true */ readFilesDeep('test/public', null, null, function (error, result) { // console.log(''); // console.log(JSON.stringify(result, null, ' ')); // result = flatten(result); // console.log(JSON.stringify(result, null, ' ')); async.each(flatten(result), fs.unlink, function () { done(); }); }); /*jslint unparam: false */ }); }); lab.experiment('middleware', function () { var express = require('express'), stylus = require('stylus'), stylsprite = require('../lib'); lab.beforeEach(function (done) { var readFilesDeep = require('../lib/utils/fs').readFilesDeep; /*jslint unparam: true */ readFilesDeep('test/public', null, null, function (error, result) { var array = require('../lib/utils/array'), flatten = array.flatten; async.each(flatten(result), fs.unlink, function () { done(); }); }); /*jslint unparam: false */ }); lab.test('curl requests', function (done) { var app = express(), options = { src: 'test/src/stylus', dest: 'test/public/css', root: 'test/public', imgsrc: 'test/src/imgsrc' }, stylsprite_mw = stylsprite.middleware(options, { padding: 2 }), stylus_mw = stylus.middleware(options); app.set('views', __dirname + '/src'); app.set('view engine', 'jade'); app.use('/css', stylsprite_mw); app.use('/css', stylus_mw); app.use(express["static"](__dirname + '/public')); /*jslint unparam: true */ app.get('/', function (req, res) { return res.render('index'); }); app.listen(8080, function () { exec('curl http://localhost:8080/css/absolute.css', function (error, stdout, stderr) { done(error); }); }); /*jslint unparam: false */ }); lab.test('onestop option', function (done) { var app = express(), options = { src: 'test/src/stylus', dest: 'test/public/css', root: 'test/public', imgsrc: 'test/src/imgsrc' }, stylsprite_mw = stylsprite.middleware(options, { padding: 2, onestop: true }); app.set('views', __dirname + '/src'); app.set('view engine', 'jade'); app.use('/css', stylsprite_mw); app.use(express["static"](__dirname + '/public')); /*jslint unparam: true */ app.get('/', function (req, res) { return res.render('index'); }); app.listen(8888, function () { exec('curl http://localhost:8888/css/absolute.css', function (error, stdout, stderr) { done(error); }); }); /*jslint unparam: false */ }); });
added: test case.
test/index.js
added: test case.
<ide><path>est/index.js <ide> return res.render('index'); <ide> }); <ide> app.listen(8080, function () { <del> exec('curl http://localhost:8080/css/absolute.css', function (error, stdout, stderr) { <add> async.series([ <add> function (next) { <add> exec('curl http://localhost:8080/css/relative.css', function (error, stdout, stderr) { <add> next(error); <add> }); <add> }, <add> function (next) { <add> exec('curl http://localhost:8080/css/absolute.css', function (error, stdout, stderr) { <add> next(error); <add> }); <add> } <add> ], function (error) { <ide> done(error); <ide> }); <ide> }); <ide> return res.render('index'); <ide> }); <ide> app.listen(8888, function () { <del> exec('curl http://localhost:8888/css/absolute.css', function (error, stdout, stderr) { <add> async.series([ <add> function (next) { <add> exec('curl http://localhost:8888/css/relative.css', function (error, stdout, stderr) { <add> next(error); <add> }); <add> }, <add> function (next) { <add> exec('curl http://localhost:8888/css/absolute.css', function (error, stdout, stderr) { <add> next(error); <add> }); <add> } <add> ], function (error) { <ide> done(error); <ide> }); <ide> });
Java
apache-2.0
405a76c4ce91d2ce811d7f6e7f373c3650ac98ec
0
apache/lenya,apache/lenya,apache/lenya,apache/lenya
/* * Copyright 1999-2004 The Apache Software Foundation * * 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.apache.lenya.cms.publication; import java.io.IOException; import org.apache.lenya.xml.NamespaceHelper; import org.apache.lenya.xml.DocumentHelper; import org.apache.lenya.xml.XLink; import org.apache.log4j.Category; import org.w3c.dom.Element; /** * Implementation of a Collection. In the collection are xlink inserted. */ public class XlinkCollection extends CollectionImpl { private static final Category log = Category.getInstance(XlinkCollection.class); /** * Ctor. * @param publication A publication. * @param id The document ID. * @param area The area the document belongs to. * @throws DocumentException when something went wrong. */ public XlinkCollection(Publication publication, String id, String area) throws DocumentException { super(publication, id, area); } /** * Ctor. * @param publication A publication. * @param id The document ID. * @param area The area the document belongs to. * @param language The language of the document. * @throws DocumentException when something went wrong. */ public XlinkCollection(Publication publication, String id, String area, String language) throws DocumentException { super(publication, id, area, language); } /** (non-Javadoc) * @see org.apache.lenya.cms.publication.CollectionImpl#createDocumentElement(org.apache.lenya.cms.publication.Document, org.apache.lenya.xml.NamespaceHelper) **/ protected Element createDocumentElement(Document document, NamespaceHelper helper) throws DocumentException { Element element = super.createDocumentElement(document, helper); String path = null; try { path = document.getFile().getCanonicalPath(); } catch (IOException e) { log.error("Couldn't found the file path for the document: " + document.getId()); } element.setAttributeNS(XLink.XLINK_NAMESPACE, "xlink:href", path); element.setAttributeNS(XLink.XLINK_NAMESPACE, "xlink:show", "embed"); return element; } /** * Saves the XML source of this collection. * @throws DocumentException when something went wrong. */ public void save() throws DocumentException { try { NamespaceHelper helper = getNamespaceHelper(); Element collectionElement = helper.getDocument().getDocumentElement(); if ((collectionElement.getAttribute("xmlns:xlink") == null) | (!collectionElement .getAttribute("xmlns:xlink") .equals("http://www.w3.org/1999/xlink"))) { collectionElement.setAttribute("xmlns:xlink", XLink.XLINK_NAMESPACE); } DocumentHelper.writeDocument(helper.getDocument(), getFile()); super.save(); } catch (DocumentException e) { throw e; } catch (Exception e) { throw new DocumentException(e); } } }
src/java/org/apache/lenya/cms/publication/XlinkCollection.java
/* * Copyright 1999-2004 The Apache Software Foundation * * 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.apache.lenya.cms.publication; import java.io.IOException; import org.apache.lenya.xml.NamespaceHelper; import org.apache.lenya.xml.DocumentHelper; import org.apache.log4j.Category; import org.w3c.dom.Element; /** * Implementation of a Collection. In the collection are xlink inserted. */ public class XlinkCollection extends CollectionImpl { private static final Category log = Category.getInstance(XlinkCollection.class); /** * Ctor. * @param publication A publication. * @param id The document ID. * @param area The area the document belongs to. * @throws DocumentException when something went wrong. */ public XlinkCollection(Publication publication, String id, String area) throws DocumentException { super(publication, id, area); } /** * Ctor. * @param publication A publication. * @param id The document ID. * @param area The area the document belongs to. * @param language The language of the document. * @throws DocumentException when something went wrong. */ public XlinkCollection(Publication publication, String id, String area, String language) throws DocumentException { super(publication, id, area, language); } /** (non-Javadoc) * @see org.apache.lenya.cms.publication.CollectionImpl#createDocumentElement(org.apache.lenya.cms.publication.Document, org.apache.lenya.xml.NamespaceHelper) **/ protected Element createDocumentElement(Document document, NamespaceHelper helper) throws DocumentException { Element element = super.createDocumentElement(document, helper); String path = null; try { path = document.getFile().getCanonicalPath(); } catch (IOException e) { log.error("Couldn't found the file path for the document: "+document.getId()); } element.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", path); element.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:show", "embed"); return element; } /** * Saves the XML source of this collection. * @throws DocumentException when something went wrong. */ public void save() throws DocumentException { try { NamespaceHelper helper = getNamespaceHelper(); Element collectionElement = helper.getDocument().getDocumentElement(); if ((collectionElement.getAttribute("xmlns:xlink") == null) | (!collectionElement.getAttribute("xmlns:xlink").equals("http://www.w3.org/1999/xlink"))) { collectionElement.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"); } DocumentHelper.writeDocument(helper.getDocument(), getFile()); super.save(); } catch (DocumentException e) { throw e; } catch (Exception e) { throw new DocumentException(e); } } }
using constant for XLink namespace URI git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@42835 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/lenya/cms/publication/XlinkCollection.java
using constant for XLink namespace URI
<ide><path>rc/java/org/apache/lenya/cms/publication/XlinkCollection.java <ide> <ide> import java.io.IOException; <ide> <del> <ide> import org.apache.lenya.xml.NamespaceHelper; <ide> import org.apache.lenya.xml.DocumentHelper; <add>import org.apache.lenya.xml.XLink; <ide> import org.apache.log4j.Category; <ide> import org.w3c.dom.Element; <ide> <ide> * Implementation of a Collection. In the collection are xlink inserted. <ide> */ <ide> public class XlinkCollection extends CollectionImpl { <del> <add> <ide> private static final Category log = Category.getInstance(XlinkCollection.class); <ide> <ide> /** <ide> * @param area The area the document belongs to. <ide> * @throws DocumentException when something went wrong. <ide> */ <del> public XlinkCollection(Publication publication, String id, String area) throws DocumentException { <add> public XlinkCollection(Publication publication, String id, String area) <add> throws DocumentException { <ide> super(publication, id, area); <ide> } <ide> <ide> * @param language The language of the document. <ide> * @throws DocumentException when something went wrong. <ide> */ <del> public XlinkCollection(Publication publication, String id, String area, String language) throws DocumentException { <add> public XlinkCollection(Publication publication, String id, String area, String language) <add> throws DocumentException { <ide> super(publication, id, area, language); <ide> } <ide> <ide> /** (non-Javadoc) <del> * @see org.apache.lenya.cms.publication.CollectionImpl#createDocumentElement(org.apache.lenya.cms.publication.Document, org.apache.lenya.xml.NamespaceHelper) <del> **/ <del> protected Element createDocumentElement(Document document, NamespaceHelper helper) <add> * @see org.apache.lenya.cms.publication.CollectionImpl#createDocumentElement(org.apache.lenya.cms.publication.Document, org.apache.lenya.xml.NamespaceHelper) <add> **/ <add> protected Element createDocumentElement(Document document, NamespaceHelper helper) <ide> throws DocumentException { <ide> Element element = super.createDocumentElement(document, helper); <ide> String path = null; <ide> try { <del> path = document.getFile().getCanonicalPath(); <del> } catch (IOException e) { <del> log.error("Couldn't found the file path for the document: "+document.getId()); <del> } <del> element.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", path); <del> element.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:show", "embed"); <del> <add> path = document.getFile().getCanonicalPath(); <add> } catch (IOException e) { <add> log.error("Couldn't found the file path for the document: " + document.getId()); <add> } <add> element.setAttributeNS(XLink.XLINK_NAMESPACE, "xlink:href", path); <add> element.setAttributeNS(XLink.XLINK_NAMESPACE, "xlink:show", "embed"); <add> <ide> return element; <ide> } <ide> <ide> */ <ide> public void save() throws DocumentException { <ide> try { <del> <ide> NamespaceHelper helper = getNamespaceHelper(); <ide> Element collectionElement = helper.getDocument().getDocumentElement(); <del> <del> if ((collectionElement.getAttribute("xmlns:xlink") == null) | (!collectionElement.getAttribute("xmlns:xlink").equals("http://www.w3.org/1999/xlink"))) { <del> collectionElement.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"); <add> <add> if ((collectionElement.getAttribute("xmlns:xlink") == null) <add> | (!collectionElement <add> .getAttribute("xmlns:xlink") <add> .equals("http://www.w3.org/1999/xlink"))) { <add> collectionElement.setAttribute("xmlns:xlink", XLink.XLINK_NAMESPACE); <ide> } <ide> DocumentHelper.writeDocument(helper.getDocument(), getFile()); <ide> super.save();
JavaScript
apache-2.0
c1ab15d9aaaa8e4b78b4aaa6dff98f6ca037de12
0
dainst/chronontology-frontend,dainst/chronontology-frontend
'use strict'; // language-specific notation of dates (so far only years): // year 1 to the present: 1950 becomes 1950 CE // year -9999 to year -1: -776 becomes 776 BCE // before year -10000: -12.000 becomes 12.000 BCE or 12,000 BCE etc. // // CE / BCE is acceptable both in English and German // CE is acceptable even for recent dates // a year 0 in the data is always wrong; however, the system // would simply display it as 0 CE // we make no case distinction for dates bigger than 10.000, // i.e. at least than 8000 years into the future angular.module('chronontology.filters') .filter('transl8Year', ['language',function(language){ var filterFunction = function(nu) { if (typeof nu == 'undefined') return undefined; if (typeof nu === 'string' && isNaN(nu)) return nu; var num = (typeof nu === 'string' && !isNaN(nu)) ? +nu : nu; if (num >= 0) { return num.toString()+" CE"; } num = Math.abs(num); if (num < 10000) { return num.toString()+" BCE"; } if (language.currentLanguage()==COMPONENTS_GERMAN_LANG) { return num.toLocaleString(COMPONENTS_GERMAN_LANG+"-DE")+" BCE"; } else { return num.toLocaleString(COMPONENTS_ENGLISH_LANG+"-US")+" BCE"; } }; filterFunction.$stateful=true; return filterFunction; }]);
js/filters/transl8Year.js
'use strict'; angular.module('chronontology.filters') .filter('transl8Year', ['language',function(language){ var filterFunction = function(nu) { if (typeof nu == 'undefined') return undefined; if (typeof nu === 'string' && isNaN(nu)) return nu; var num = (typeof nu === 'string' && !isNaN(nu)) ? +nu : nu; if (Math.abs(num) < 10000) return num.toString(); if (language.currentLanguage()==COMPONENTS_GERMAN_LANG) { return num.toLocaleString(COMPONENTS_GERMAN_LANG+"-DE"); } else { return num.toLocaleString(COMPONENTS_ENGLISH_LANG+"-US"); } }; filterFunction.$stateful=true; return filterFunction; }]);
use BCE / CE in dates
js/filters/transl8Year.js
use BCE / CE in dates
<ide><path>s/filters/transl8Year.js <ide> 'use strict'; <add> <add>// language-specific notation of dates (so far only years): <add>// year 1 to the present: 1950 becomes 1950 CE <add>// year -9999 to year -1: -776 becomes 776 BCE <add>// before year -10000: -12.000 becomes 12.000 BCE or 12,000 BCE etc. <add>// <add>// CE / BCE is acceptable both in English and German <add>// CE is acceptable even for recent dates <add>// a year 0 in the data is always wrong; however, the system <add>// would simply display it as 0 CE <add>// we make no case distinction for dates bigger than 10.000, <add>// i.e. at least than 8000 years into the future <add> <ide> <ide> angular.module('chronontology.filters') <ide> <ide> <ide> var num = (typeof nu === 'string' && !isNaN(nu)) ? +nu : nu; <ide> <del> if (Math.abs(num) < 10000) return num.toString(); <add> if (num >= 0) { <add> return num.toString()+" CE"; <add> } <add> <add> num = Math.abs(num); <ide> <del> if (language.currentLanguage()==COMPONENTS_GERMAN_LANG) { <del> return num.toLocaleString(COMPONENTS_GERMAN_LANG+"-DE"); <add> if (num < 10000) { <add> return num.toString()+" BCE"; <add> } <add> if (language.currentLanguage()==COMPONENTS_GERMAN_LANG) { <add> return num.toLocaleString(COMPONENTS_GERMAN_LANG+"-DE")+" BCE"; <ide> } else { <del> return num.toLocaleString(COMPONENTS_ENGLISH_LANG+"-US"); <add> return num.toLocaleString(COMPONENTS_ENGLISH_LANG+"-US")+" BCE"; <ide> } <ide> }; <ide> filterFunction.$stateful=true;
Java
apache-2.0
5e7fc5f27df24998cebe41620444661c86b351da
0
99soft/Hazelmap
package org.nnsoft.hazelmap; /* * Copyright 2011 The 99 Software Foundation * * 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. */ import java.io.Serializable; import org.nnsoft.hazelmap.builder.MapReduceInvoker; import org.nnsoft.hazelmap.builder.MapperBuilder; import org.nnsoft.hazelmap.builder.ReducerBuilder; import com.hazelcast.core.MultiMap; public final class Hazelmap { public static <K extends Serializable, V extends Serializable> MapperBuilder<K, V> processInput( InputReader<K, V> inputReader ) { if ( inputReader == null ) { throw new IllegalArgumentException( "The inputReader cannot be null" ); } return new DefaultMapperBuilder<K, V>( inputReader ); } /** * Hidden constructor, this class must not be instantiated directly. */ private Hazelmap() { // do nothing } private static final class DefaultMapperBuilder<IK extends Serializable, IV extends Serializable> implements MapperBuilder<IK, IV> { private final InputReader<IK, IV> inputReader; DefaultMapperBuilder( InputReader<IK, IV> inputReader ) { this.inputReader = inputReader; } public <OK extends Serializable, OV extends Serializable> ReducerBuilder<IK, IV, OK, OV> usingMapper( Mapper<IK, IV, OK, OV> mapper ) { return new DefaultReducerBuilder<IK, IV, OK, OV>(); } } private static final class DefaultReducerBuilder<IK extends Serializable, IV extends Serializable, OK extends Serializable, OV extends Serializable> implements ReducerBuilder<IK, IV, OK, OV> { public MapReduceInvoker<IK, IV, OK, OV> withReducer( Reducer<OK, OV> reducer ) { return new DefaultMapReduceInvoker<IK, IV, OK, OV>(); } } private static final class DefaultMapReduceInvoker<IK extends Serializable, IV extends Serializable, OK extends Serializable, OV extends Serializable> implements MapReduceInvoker<IK, IV, OK, OV> { public MultiMap<OK, OV> invoke() { return null; } public <O> O invoke( OutputWriter<OK, OV, O> outputWriter ) { return null; } } }
src/main/java/org/nnsoft/hazelmap/Hazelmap.java
package org.nnsoft.hazelmap; /* * Copyright 2011 The 99 Software Foundation * * 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. */ import java.io.Serializable; import org.nnsoft.hazelmap.builder.MapperBuilder; public final class Hazelmap { public static <K extends Serializable, V extends Serializable> MapperBuilder<K, V> processInput( InputReader<K, V> inputReader ) { if ( inputReader == null ) { throw new IllegalArgumentException( "The inputReader cannot be null" ); } return null; } /** * Hidden constructor, this class must not be instantiated directly. */ private Hazelmap() { // do nothing } }
a first step of fluent APIs implementation
src/main/java/org/nnsoft/hazelmap/Hazelmap.java
a first step of fluent APIs implementation
<ide><path>rc/main/java/org/nnsoft/hazelmap/Hazelmap.java <ide> <ide> import java.io.Serializable; <ide> <add>import org.nnsoft.hazelmap.builder.MapReduceInvoker; <ide> import org.nnsoft.hazelmap.builder.MapperBuilder; <add>import org.nnsoft.hazelmap.builder.ReducerBuilder; <add> <add>import com.hazelcast.core.MultiMap; <ide> <ide> public final class Hazelmap <ide> { <ide> throw new IllegalArgumentException( "The inputReader cannot be null" ); <ide> } <ide> <del> return null; <add> return new DefaultMapperBuilder<K, V>( inputReader ); <ide> } <ide> <ide> /** <ide> // do nothing <ide> } <ide> <add> private static final class DefaultMapperBuilder<IK extends Serializable, IV extends Serializable> <add> implements MapperBuilder<IK, IV> <add> { <add> <add> private final InputReader<IK, IV> inputReader; <add> <add> DefaultMapperBuilder( InputReader<IK, IV> inputReader ) <add> { <add> this.inputReader = inputReader; <add> } <add> <add> public <OK extends Serializable, OV extends Serializable> ReducerBuilder<IK, IV, OK, OV> usingMapper( Mapper<IK, IV, OK, OV> mapper ) <add> { <add> return new DefaultReducerBuilder<IK, IV, OK, OV>(); <add> } <add> <add> } <add> <add> private static final class DefaultReducerBuilder<IK extends Serializable, IV extends Serializable, OK extends Serializable, OV extends Serializable> <add> implements ReducerBuilder<IK, IV, OK, OV> <add> { <add> <add> public MapReduceInvoker<IK, IV, OK, OV> withReducer( Reducer<OK, OV> reducer ) <add> { <add> return new DefaultMapReduceInvoker<IK, IV, OK, OV>(); <add> } <add> <add> } <add> <add> private static final class DefaultMapReduceInvoker<IK extends Serializable, IV extends Serializable, OK extends Serializable, OV extends Serializable> <add> implements MapReduceInvoker<IK, IV, OK, OV> <add> { <add> <add> public MultiMap<OK, OV> invoke() <add> { <add> return null; <add> } <add> <add> public <O> O invoke( OutputWriter<OK, OV, O> outputWriter ) <add> { <add> return null; <add> } <add> <add> } <add> <ide> }
Java
apache-2.0
fb15e68206688a6f7981f91308da02034736e22b
0
PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr
/** * 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.solr.cloud; import java.io.File; import java.io.IOException; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.core.CoreContainer; import org.apache.solr.util.AbstractSolrTestCase; import org.apache.solr.util.ExternalPaths; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestMultiCoreConfBootstrap extends SolrTestCaseJ4 { protected static Logger log = LoggerFactory.getLogger(TestMultiCoreConfBootstrap.class); protected CoreContainer cores = null; private String home; protected static ZkTestServer zkServer; protected static String zkDir; @BeforeClass public static void beforeClass() throws Exception { createTempDir(); } @AfterClass public static void afterClass() throws IOException { } @Override @Before public void setUp() throws Exception { super.setUp(); home = ExternalPaths.EXAMPLE_MULTICORE_HOME; System.setProperty("solr.solr.home", home); zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; zkServer = new ZkTestServer(zkDir); zkServer.run(); SolrZkClient zkClient = new SolrZkClient(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT); zkClient.makePath("/solr", false, true); zkClient.close(); System.setProperty("zkHost", zkServer.getZkAddress()); } @Override @After public void tearDown() throws Exception { System.clearProperty("bootstrap_conf"); System.clearProperty("zkHost"); System.clearProperty("solr.solr.home"); if (cores != null) cores.shutdown(); zkServer.shutdown(); File dataDir1 = new File(home + File.separator + "core0","data"); File dataDir2 = new File(home + File.separator + "core1","data"); String skip = System.getProperty("solr.test.leavedatadir"); if (null != skip && 0 != skip.trim().length()) { log.info("NOTE: per solr.test.leavedatadir, dataDir will not be removed: " + dataDir.getAbsolutePath()); } else { if (!AbstractSolrTestCase.recurseDelete(dataDir1)) { log.warn("!!!! WARNING: best effort to remove " + dataDir.getAbsolutePath() + " FAILED !!!!!"); } if (!AbstractSolrTestCase.recurseDelete(dataDir2)) { log.warn("!!!! WARNING: best effort to remove " + dataDir.getAbsolutePath() + " FAILED !!!!!"); } } super.tearDown(); } @Test public void testMultiCoreConfBootstrap() throws Exception { System.setProperty("bootstrap_conf", "true"); cores = new CoreContainer(home, new File(home, "solr.xml")); SolrZkClient zkclient = cores.getZkController().getZkClient(); // zkclient.printLayoutToStdOut(); assertTrue(zkclient.exists("/configs/core1/solrconfig.xml", true)); assertTrue(zkclient.exists("/configs/core1/schema.xml", true)); assertTrue(zkclient.exists("/configs/core0/solrconfig.xml", true)); assertTrue(zkclient.exists("/configs/core1/schema.xml", true)); } }
solr/core/src/test/org/apache/solr/cloud/TestMultiCoreConfBootstrap.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.solr.cloud; import java.io.File; import java.io.IOException; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.core.CoreContainer; import org.apache.solr.util.AbstractSolrTestCase; import org.apache.solr.util.ExternalPaths; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestMultiCoreConfBootstrap extends SolrTestCaseJ4 { protected static Logger log = LoggerFactory.getLogger(TestMultiCoreConfBootstrap.class); protected CoreContainer cores = null; private String home; protected static ZkTestServer zkServer; protected static String zkDir; @BeforeClass public static void beforeClass() throws Exception { createTempDir(); } @AfterClass public static void afterClass() throws IOException { } @Override @Before public void setUp() throws Exception { super.setUp(); home = ExternalPaths.EXAMPLE_MULTICORE_HOME; System.setProperty("solr.solr.home", home); zkDir = dataDir.getAbsolutePath() + File.separator + "zookeeper/server1/data"; zkServer = new ZkTestServer(zkDir); zkServer.run(); SolrZkClient zkClient = new SolrZkClient(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT); zkClient.makePath("/solr", false, true); zkClient.close(); System.setProperty("zkHost", zkServer.getZkAddress()); } @Override @After public void tearDown() throws Exception { System.clearProperty("bootstrap_confdir"); System.clearProperty("zkHost"); System.clearProperty("solr.solr.home"); if (cores != null) cores.shutdown(); zkServer.shutdown(); File dataDir1 = new File(home + File.separator + "core0","data"); File dataDir2 = new File(home + File.separator + "core1","data"); String skip = System.getProperty("solr.test.leavedatadir"); if (null != skip && 0 != skip.trim().length()) { log.info("NOTE: per solr.test.leavedatadir, dataDir will not be removed: " + dataDir.getAbsolutePath()); } else { if (!AbstractSolrTestCase.recurseDelete(dataDir1)) { log.warn("!!!! WARNING: best effort to remove " + dataDir.getAbsolutePath() + " FAILED !!!!!"); } if (!AbstractSolrTestCase.recurseDelete(dataDir2)) { log.warn("!!!! WARNING: best effort to remove " + dataDir.getAbsolutePath() + " FAILED !!!!!"); } } super.tearDown(); } @Test public void testMultiCoreConfBootstrap() throws Exception { System.setProperty("bootstrap_conf", "true"); cores = new CoreContainer(home, new File(home, "solr.xml")); SolrZkClient zkclient = cores.getZkController().getZkClient(); // zkclient.printLayoutToStdOut(); assertTrue(zkclient.exists("/configs/core1/solrconfig.xml", true)); assertTrue(zkclient.exists("/configs/core1/schema.xml", true)); assertTrue(zkclient.exists("/configs/core0/solrconfig.xml", true)); assertTrue(zkclient.exists("/configs/core1/schema.xml", true)); } }
clear the right sys prop git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1294187 13f79535-47bb-0310-9956-ffa450edef68
solr/core/src/test/org/apache/solr/cloud/TestMultiCoreConfBootstrap.java
clear the right sys prop
<ide><path>olr/core/src/test/org/apache/solr/cloud/TestMultiCoreConfBootstrap.java <ide> @Override <ide> @After <ide> public void tearDown() throws Exception { <del> System.clearProperty("bootstrap_confdir"); <add> System.clearProperty("bootstrap_conf"); <ide> System.clearProperty("zkHost"); <ide> System.clearProperty("solr.solr.home"); <ide>
Java
epl-1.0
9e12f726e8510d7f0a540e016bebd0f946b80f71
0
jdufner/fitnesse,amolenaar/fitnesse,rbevers/fitnesse,jdufner/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,jdufner/fitnesse,amolenaar/fitnesse,amolenaar/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,hansjoachim/fitnesse
package fitnesse.responders.run; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.xml.sax.InputSource; import fitnesse.responders.run.JavaFormatter.FolderResultsRepository; public class JavaFormatterFolderResultsRepositoryTest { private static final String TEST_NAME = "testName"; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private FolderResultsRepository repository; @Before public void prepareFolder() throws Exception { String tempDir = temporaryFolder.getRoot().getAbsolutePath(); repository = new JavaFormatter.FolderResultsRepository(tempDir, "."); } @Test public void usesTestNameAsHeadingWithinValidHtmlStructure() throws Exception { repository.open(TEST_NAME); repository.close(); String heading = evaluateXPathAgainstOutputHtml("/html/body/header/h2/text()"); assertEquals(TEST_NAME, heading); } @Test public void usesUtf8Encoding() throws Exception { repository.open(TEST_NAME); repository.write("someContent\u263a"); repository.close(); String outputHtml = readOutputHtml("utf8"); assertTrue(outputHtml.contains("someContent\u263a")); assertTrue(outputHtml.contains("<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>")); } private String evaluateXPathAgainstOutputHtml(String expression) throws Exception { XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource(getHtmlOutputStream()); return xpath.evaluate(expression, inputSource); } private String readOutputHtml(String encoding) throws Exception { Reader reader = new InputStreamReader(getHtmlOutputStream(), encoding); StringBuilder result = new StringBuilder(); char[] buffer = new char[1000]; while (reader.read(buffer) > 0) { result.append(buffer); } return result.toString(); } private InputStream getHtmlOutputStream() throws FileNotFoundException { File outputHtml = new File(temporaryFolder.getRoot(), TEST_NAME + ".html"); InputStream outputHtmlStream = new FileInputStream(outputHtml); return outputHtmlStream; } }
src/fitnesse/responders/run/JavaFormatterFolderResultsRepositoryTest.java
package fitnesse.responders.run; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.xml.sax.InputSource; import fitnesse.responders.run.JavaFormatter.FolderResultsRepository; public class JavaFormatterFolderResultsRepositoryTest { private static final String TEST_NAME = "testName"; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private FolderResultsRepository repository; @Before public void prepareFolder() throws Exception { String tempDir = temporaryFolder.getRoot().getAbsolutePath(); repository = new JavaFormatter.FolderResultsRepository(tempDir, "."); } @Test public void usesTestNameAsHeadingWithinValidHtmlStructure() throws Exception { repository.open(TEST_NAME); repository.close(); String heading = evaluateXPathAgainstOutputHtml("/html/body/h2/text()"); assertEquals(TEST_NAME, heading); } @Test public void usesUtf8Encoding() throws Exception { repository.open(TEST_NAME); repository.write("someContent\u263a"); repository.close(); String outputHtml = readOutputHtml("utf8"); assertTrue(outputHtml.contains("someContent\u263a")); assertTrue(outputHtml.contains("<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>")); } private String evaluateXPathAgainstOutputHtml(String expression) throws Exception { XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource(getHtmlOutputStream()); return xpath.evaluate(expression, inputSource); } private String readOutputHtml(String encoding) throws Exception { Reader reader = new InputStreamReader(getHtmlOutputStream(), encoding); StringBuilder result = new StringBuilder(); char[] buffer = new char[1000]; while (reader.read(buffer) > 0) { result.append(buffer); } return result.toString(); } private InputStream getHtmlOutputStream() throws FileNotFoundException { File outputHtml = new File(temporaryFolder.getRoot(), TEST_NAME + ".html"); InputStream outputHtmlStream = new FileInputStream(outputHtml); return outputHtmlStream; } }
HTML fixes for JavaFormatter Forget to commit failing Unit test
src/fitnesse/responders/run/JavaFormatterFolderResultsRepositoryTest.java
HTML fixes for JavaFormatter
<ide><path>rc/fitnesse/responders/run/JavaFormatterFolderResultsRepositoryTest.java <ide> repository.open(TEST_NAME); <ide> repository.close(); <ide> <del> String heading = evaluateXPathAgainstOutputHtml("/html/body/h2/text()"); <add> String heading = evaluateXPathAgainstOutputHtml("/html/body/header/h2/text()"); <ide> assertEquals(TEST_NAME, heading); <ide> } <ide>
Java
apache-2.0
ad1b8c5cc99fac9e9b0c9968037de55f4672cd16
0
Kodehawa/imageboard-api
/* * Copyright 2017 Kodehawa * * 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 net.kodehawa.lib.imageboards; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import net.kodehawa.lib.imageboards.boards.Board; import net.kodehawa.lib.imageboards.boards.DefaultBoards; import net.kodehawa.lib.imageboards.entities.BoardImage; import net.kodehawa.lib.imageboards.entities.Rating; import net.kodehawa.lib.imageboards.entities.exceptions.QueryFailedException; import net.kodehawa.lib.imageboards.entities.exceptions.QueryParseException; import net.kodehawa.lib.imageboards.requests.RequestAction; import net.kodehawa.lib.imageboards.requests.RequestFactory; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; /** * Image board API instance. * @param <T> Board image return type. * * @author Avarel * @author Kodehawa */ public class ImageBoard<T extends BoardImage> { private static final Logger log = LoggerFactory.getLogger(ImageBoard.class); /** * Current version of the image board library. */ public static final String VERSION = "@version@"; /** * User agent to send to the services we request data from. */ public static final String userAgent = "ImageboardAPI/@version@/https://github.com/Kodehawa/imageboard-api"; /** * Requester client. */ private final RequestFactory requestFactory; /** * Image board's endpoint. */ private final Board board; /** * Deserialization target. */ private final Class<T> cls; /** * GET return format of the board. */ private final ResponseFormat responseFormat; /** * Changes whether we're gonna throw exceptions on EOF or no */ public static boolean throwExceptionOnEOF = true; /** * Create a new image board instance. * * @param landing Board {@link Board API landing}. * @param cls The class this refers to. */ public ImageBoard(Board landing, Class<T> cls) { this(landing, ResponseFormat.JSON, cls); } /** * Create a new image board instance. * * @param landing Board {@link Board API landing}. * @param responseFormat Response format of the board. * @param cls The class this refers to. */ public ImageBoard(Board landing, ResponseFormat responseFormat, Class<T> cls) { this(new OkHttpClient.Builder() .readTimeout(2, TimeUnit.SECONDS) .build(), landing, responseFormat, cls); } /** * Create a new image board instance. * * @param client {@link RequestFactory}'s request client. * @param landing Board {@link Board API landing}. * @param cls The class this refers to. */ public ImageBoard(OkHttpClient client, Board landing, Class<T> cls) { this(client, landing, ResponseFormat.JSON, cls); } /** * Create a new image board instance. * * @param client {@link RequestFactory}'s request client. * @param landing Board {@link Board API landing}. * @param responseFormat Response format of the board. * @param cls The class this refers to. */ public ImageBoard(OkHttpClient client, Board landing, ResponseFormat responseFormat, Class<T> cls) { this.requestFactory = new RequestFactory(client); this.board = landing; this.responseFormat = responseFormat; this.cls = cls; } /** * Get the board landing of this instance. * @return Board type. */ public Board getBoardType() { return board; } /** * Get the image return type of this board. * @return A java class of the image return type. */ public Class<T> getImageType() { return cls; } /** * Get first page results of the image board, limited at 60 images. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get() { return get(60); } /** * Get first page results of the image board. * * @param limit Maximum number of images. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int limit) { return get(0, limit); } /** * Get the provided page's results of the image board. * * @param page Page number. * @param limit Maximum number of images. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int page, int limit) { return get(page, limit, null); } /** * Get the provided page's results of the image board. * * @param page Page number. * @param limit Maximum number of images. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int page, int limit, Rating rating) { return makeRequest(page, limit, "", rating); } /** * Get the provided page's results of the image board. * * @param limit Maximum number of images. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int limit, Rating rating) { return get(0, limit, rating); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param search Image tags. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(String search) { return search(60, search); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param limit Maximum number of images. * @param search Image tags. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(int limit, String search) { return search(0, limit, search); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param page Page number. * @param limit Maximum number of images. * @param search Image tags. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(int page, int limit, String search) { return makeRequest(page, limit, search, null); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param page Page number. * @param limit Maximum number of images. * @param search Image tags. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(int page, int limit, String search, Rating rating) { return makeRequest(page, limit, search, rating); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param search Image tags. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(String search, Rating rating) { return search(0, 60, search, rating); } private RequestAction<List<T>> makeRequest(int page, int limit, String search, Rating rating) throws QueryParseException, QueryFailedException { HttpUrl.Builder urlBuilder = new HttpUrl.Builder() .scheme(board.getScheme()) .host(board.getHost()) .addPathSegments(board.getPath()) .query(board.getQuery()) .addQueryParameter("limit", String.valueOf(limit)); if (page != 0) urlBuilder.addQueryParameter(board.getPageMarker(), String.valueOf(page)); if (search != null) { StringBuilder tags = new StringBuilder(search.toLowerCase().trim()); if(rating != null) { //Fuck you gelbooru you're the only one doing this :( tags.append(" rating:").append(board == DefaultBoards.GELBOORU ? rating.getLongName() : rating.getShortName()); } urlBuilder.addQueryParameter("tags", tags.toString()); } HttpUrl url = urlBuilder.build(); return requestFactory.makeRequest(url, response -> { log.debug("Making request to {} (Response format: {}, Imageboard: {}, Target: {})", url.toString(), responseFormat, board, cls); try (ResponseBody body = response.body()) { if (body == null) { if(throwExceptionOnEOF) { throw new QueryParseException(new NullPointerException("Received an empty body from the imageboard URL. (From board: " + board + ", Target: " + cls + ")")); } else { return Collections.emptyList(); } } ObjectMapper mapper = responseFormat.mapper; List<T> images; InputStream inputStream = body.byteStream(); if(board.getOuterObject() != null) { String posts = mapper.writeValueAsString(mapper.readTree(inputStream).get(board.getOuterObject())); images = mapper.readValue(posts, mapper.getTypeFactory().constructCollectionType(List.class, cls)); } else { images = mapper.readValue(inputStream, mapper.getTypeFactory().constructCollectionType(List.class, cls)); } body.close(); return images; } catch (IOException e) { if(e.getMessage().contains("No content to map due to end-of-input") && !throwExceptionOnEOF) { return Collections.emptyList(); } throw new QueryParseException(e); } }); } /** * The type of the specified Imageboard. * This is important because if you specify the wrong type, it'll be impossible to deserialize it properly. */ public enum ResponseFormat { /** JSON response type. */ JSON(new ObjectMapper()), /** XML response type. */ XML(new XmlMapper()); private final ObjectMapper mapper; ResponseFormat(ObjectMapper mapper) { this.mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private <T> T readValue(String p, JavaType valueType) { try { return mapper.readValue(p, valueType); } catch (IOException e) { throw new RuntimeException(e); } } } }
src/main/java/net/kodehawa/lib/imageboards/ImageBoard.java
/* * Copyright 2017 Kodehawa * * 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 net.kodehawa.lib.imageboards; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import net.kodehawa.lib.imageboards.boards.Board; import net.kodehawa.lib.imageboards.boards.DefaultBoards; import net.kodehawa.lib.imageboards.entities.BoardImage; import net.kodehawa.lib.imageboards.entities.Rating; import net.kodehawa.lib.imageboards.entities.exceptions.QueryFailedException; import net.kodehawa.lib.imageboards.entities.exceptions.QueryParseException; import net.kodehawa.lib.imageboards.requests.RequestAction; import net.kodehawa.lib.imageboards.requests.RequestFactory; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; /** * Image board API instance. * @param <T> Board image return type. * * @author Avarel * @author Kodehawa */ public class ImageBoard<T extends BoardImage> { private static final Logger log = LoggerFactory.getLogger(ImageBoard.class); /** * Current version of the image board library. */ public static final String VERSION = "@version@"; /** * User agent to send to the services we request data from. */ public static final String userAgent = "ImageboardAPI/@version@/https://github.com/Kodehawa/imageboard-api"; /** * Requester client. */ private final RequestFactory requestFactory; /** * Image board's endpoint. */ private Board board; /** * Deserialization target. */ private Class<T> cls; /** * GET return format of the board. */ private ResponseFormat responseFormat; /** * Changes whether we're gonna throw exceptions on EOF or no */ public static boolean throwExceptionOnEOF = true; /** * Create a new image board instance. * * @param landing Board {@link Board API landing}. * @param cls The class this refers to. */ public ImageBoard(Board landing, Class<T> cls) { this(landing, ResponseFormat.JSON, cls); } /** * Create a new image board instance. * * @param landing Board {@link Board API landing}. * @param responseFormat Response format of the board. * @param cls The class this refers to. */ public ImageBoard(Board landing, ResponseFormat responseFormat, Class<T> cls) { this(new OkHttpClient.Builder() .readTimeout(2, TimeUnit.SECONDS) .build(), landing, responseFormat, cls); } /** * Create a new image board instance. * * @param client {@link RequestFactory}'s request client. * @param landing Board {@link Board API landing}. * @param cls The class this refers to. */ public ImageBoard(OkHttpClient client, Board landing, Class<T> cls) { this(client, landing, ResponseFormat.JSON, cls); } /** * Create a new image board instance. * * @param client {@link RequestFactory}'s request client. * @param landing Board {@link Board API landing}. * @param responseFormat Response format of the board. * @param cls The class this refers to. */ public ImageBoard(OkHttpClient client, Board landing, ResponseFormat responseFormat, Class<T> cls) { this.requestFactory = new RequestFactory(client); this.board = landing; this.responseFormat = responseFormat; this.cls = cls; } /** * Get the board landing of this instance. * @return Board type. */ public Board getBoardType() { return board; } /** * Get the image return type of this board. * @return A java class of the image return type. */ public Class<T> getImageType() { return cls; } /** * Get first page results of the image board, limited at 60 images. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get() { return get(60); } /** * Get first page results of the image board. * * @param limit Maximum number of images. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int limit) { return get(0, limit); } /** * Get the provided page's results of the image board. * * @param page Page number. * @param limit Maximum number of images. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int page, int limit) { return get(page, limit, null); } /** * Get the provided page's results of the image board. * * @param page Page number. * @param limit Maximum number of images. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int page, int limit, Rating rating) { return makeRequest(page, limit, "", rating); } /** * Get the provided page's results of the image board. * * @param limit Maximum number of images. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> get(int limit, Rating rating) { return get(0, limit, rating); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param search Image tags. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(String search) { return search(60, search); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param limit Maximum number of images. * @param search Image tags. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(int limit, String search) { return search(0, limit, search); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param page Page number. * @param limit Maximum number of images. * @param search Image tags. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(int page, int limit, String search) { return makeRequest(page, limit, search, null); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param page Page number. * @param limit Maximum number of images. * @param search Image tags. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(int page, int limit, String search, Rating rating) { return makeRequest(page, limit, search, rating); } /** * Get the first page's results from the image board search, limited at 60 images. * * @param search Image tags. * @param rating The rating to look for. * @return A {@link RequestAction request action} that returns a list of images. */ public RequestAction<List<T>> search(String search, Rating rating) { return search(0, 60, search, rating); } public RequestAction<List<T>> search(List<String> search, Rating rating) { return search(0, 60, String.join(" ", search), rating); } public RequestAction<List<T>> search(String[] search, Rating rating) { return search(0, 60, String.join(" ", search), rating); } public RequestAction<List<T>> search(Rating rating, String... search) { return search(0, 60, String.join(" ", search), rating); } private RequestAction<List<T>> makeRequest(int page, int limit, String search, Rating rating) throws QueryParseException, QueryFailedException { HttpUrl.Builder urlBuilder = new HttpUrl.Builder() .scheme(board.getScheme()) .host(board.getHost()) .addPathSegments(board.getPath()) .query(board.getQuery()) .addQueryParameter("limit", String.valueOf(limit)); if (page != 0) urlBuilder.addQueryParameter(board.getPageMarker(), String.valueOf(page)); if (search != null) { StringBuilder tags = new StringBuilder(search.toLowerCase().trim()); if(rating != null) { //Fuck you gelbooru you're the only one doing this :( tags.append(" rating:").append(board == DefaultBoards.GELBOORU ? rating.getLongName() : rating.getShortName()); } urlBuilder.addQueryParameter("tags", tags.toString()); } HttpUrl url = urlBuilder.build(); return requestFactory.makeRequest(url, response -> { log.debug("Making request to {} (Response format: {}, Imageboard: {}, Target: {})", url.toString(), responseFormat, board, cls); try (ResponseBody body = response.body()) { if (body == null) { if(throwExceptionOnEOF) { throw new QueryParseException(new NullPointerException("Received an empty body from the imageboard URL. (From board: " + board + ", Target: " + cls + ")")); } else { return Collections.emptyList(); } } ObjectMapper mapper = responseFormat.mapper; List<T> images; InputStream inputStream = body.byteStream(); if(board.getOuterObject() != null) { String posts = mapper.writeValueAsString(mapper.readTree(inputStream).get(board.getOuterObject())); images = mapper.readValue(posts, mapper.getTypeFactory().constructCollectionType(List.class, cls)); } else { images = mapper.readValue(inputStream, mapper.getTypeFactory().constructCollectionType(List.class, cls)); } body.close(); if (images != null) { return images; } else { return null; } } catch (IOException e) { if(e.getMessage().contains("No content to map due to end-of-input") && !throwExceptionOnEOF) { return Collections.emptyList(); } throw new QueryParseException(e); } }); } /** * The type of the specified Imageboard. * This is important because if you specify the wrong type, it'll be impossible to deserialize it properly. */ public enum ResponseFormat { /** JSON response type. */ JSON(new ObjectMapper()), /** XML response type. */ XML(new XmlMapper()); private final ObjectMapper mapper; ResponseFormat(ObjectMapper mapper) { this.mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private <T> T readValue(String p, JavaType valueType) { try { return mapper.readValue(p, valueType); } catch (IOException e) { throw new RuntimeException(e); } } } }
Simplify some stuff and remove unused methods.
src/main/java/net/kodehawa/lib/imageboards/ImageBoard.java
Simplify some stuff and remove unused methods.
<ide><path>rc/main/java/net/kodehawa/lib/imageboards/ImageBoard.java <ide> /** <ide> * Image board's endpoint. <ide> */ <del> private Board board; <add> private final Board board; <ide> <ide> /** <ide> * Deserialization target. <ide> */ <del> private Class<T> cls; <add> private final Class<T> cls; <ide> <ide> /** <ide> * GET return format of the board. <ide> */ <del> private ResponseFormat responseFormat; <add> private final ResponseFormat responseFormat; <ide> <ide> /** <ide> * Changes whether we're gonna throw exceptions on EOF or no <ide> */ <ide> public RequestAction<List<T>> search(String search, Rating rating) { <ide> return search(0, 60, search, rating); <del> } <del> <del> public RequestAction<List<T>> search(List<String> search, Rating rating) { <del> return search(0, 60, String.join(" ", search), rating); <del> } <del> <del> public RequestAction<List<T>> search(String[] search, Rating rating) { <del> return search(0, 60, String.join(" ", search), rating); <del> } <del> <del> public RequestAction<List<T>> search(Rating rating, String... search) { <del> return search(0, 60, String.join(" ", search), rating); <ide> } <ide> <ide> private RequestAction<List<T>> makeRequest(int page, int limit, String search, Rating rating) throws QueryParseException, QueryFailedException { <ide> <ide> body.close(); <ide> <del> if (images != null) { <del> return images; <del> } else { <del> return null; <del> } <add> return images; <ide> } catch (IOException e) { <ide> if(e.getMessage().contains("No content to map due to end-of-input") && !throwExceptionOnEOF) { <ide> return Collections.emptyList();
Java
apache-2.0
959cfe06d54b2ad45e2965e8e9351a676aea80f8
0
pentaho/pentaho-kettle,pentaho/pentaho-kettle,bmorrise/pentaho-kettle,bmorrise/pentaho-kettle,pedrofvteixeira/pentaho-kettle,bmorrise/pentaho-kettle,skofra0/pentaho-kettle,kurtwalker/pentaho-kettle,mbatchelor/pentaho-kettle,e-cuellar/pentaho-kettle,pentaho/pentaho-kettle,ccaspanello/pentaho-kettle,ddiroma/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pminutillo/pentaho-kettle,kurtwalker/pentaho-kettle,mkambol/pentaho-kettle,roboguy/pentaho-kettle,e-cuellar/pentaho-kettle,lgrill-pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,bmorrise/pentaho-kettle,pminutillo/pentaho-kettle,mkambol/pentaho-kettle,graimundo/pentaho-kettle,ccaspanello/pentaho-kettle,rmansoor/pentaho-kettle,tmcsantos/pentaho-kettle,ddiroma/pentaho-kettle,HiromuHota/pentaho-kettle,HiromuHota/pentaho-kettle,e-cuellar/pentaho-kettle,tmcsantos/pentaho-kettle,mkambol/pentaho-kettle,skofra0/pentaho-kettle,tkafalas/pentaho-kettle,pminutillo/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,roboguy/pentaho-kettle,pedrofvteixeira/pentaho-kettle,kurtwalker/pentaho-kettle,mbatchelor/pentaho-kettle,dkincade/pentaho-kettle,tmcsantos/pentaho-kettle,pminutillo/pentaho-kettle,rmansoor/pentaho-kettle,HiromuHota/pentaho-kettle,graimundo/pentaho-kettle,skofra0/pentaho-kettle,wseyler/pentaho-kettle,mkambol/pentaho-kettle,skofra0/pentaho-kettle,lgrill-pentaho/pentaho-kettle,roboguy/pentaho-kettle,dkincade/pentaho-kettle,DFieldFL/pentaho-kettle,marcoslarsen/pentaho-kettle,tkafalas/pentaho-kettle,DFieldFL/pentaho-kettle,kurtwalker/pentaho-kettle,rmansoor/pentaho-kettle,roboguy/pentaho-kettle,DFieldFL/pentaho-kettle,mbatchelor/pentaho-kettle,tkafalas/pentaho-kettle,ccaspanello/pentaho-kettle,wseyler/pentaho-kettle,lgrill-pentaho/pentaho-kettle,DFieldFL/pentaho-kettle,dkincade/pentaho-kettle,pedrofvteixeira/pentaho-kettle,graimundo/pentaho-kettle,rmansoor/pentaho-kettle,mbatchelor/pentaho-kettle,graimundo/pentaho-kettle,marcoslarsen/pentaho-kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,dkincade/pentaho-kettle,ccaspanello/pentaho-kettle,tmcsantos/pentaho-kettle,ddiroma/pentaho-kettle,tkafalas/pentaho-kettle,pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,HiromuHota/pentaho-kettle,e-cuellar/pentaho-kettle
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.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 org.pentaho.di.trans.steps.getxmldata; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.http.client.methods.HttpGet; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import org.dom4j.tree.AbstractNode; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.HttpClientManager; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.fileinput.FileInputList; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaFactory; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLParserFactoryProducer; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Read XML files, parse them and convert them to rows and writes these to one or more output streams. * * @author Samatar,Brahim * @since 20-06-2007 */ public class GetXMLData extends BaseStep implements StepInterface { private static Class<?> PKG = GetXMLDataMeta.class; // for i18n purposes, needed by Translator2!! private GetXMLDataMeta meta; private GetXMLDataData data; private Object[] prevRow = null; // A pre-allocated spot for the previous row public GetXMLData( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } protected boolean setDocument( String StringXML, FileObject file, boolean IsInXMLField, boolean readurl ) throws KettleException { this.prevRow = buildEmptyRow(); // pre-allocate previous row try { SAXReader reader = XMLParserFactoryProducer.getSAXReader( null ); data.stopPruning = false; // Validate XML against specified schema? if ( meta.isValidating() ) { reader.setValidation( true ); reader.setFeature( "http://apache.org/xml/features/validation/schema", true ); } else { // Ignore DTD declarations reader.setEntityResolver( new IgnoreDTDEntityResolver() ); } // Ignore comments? if ( meta.isIgnoreComments() ) { reader.setIgnoreComments( true ); } if ( data.prunePath != null ) { // when pruning is on: reader.read() below will wait until all is processed in the handler if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.Activated" ) ); } if ( data.PathValue.equals( data.prunePath ) ) { // Edge case, but if true, there will only ever be one item in the list data.an = new ArrayList<>( 1 ); // pre-allocate array and sizes data.an.add( null ); } reader.addHandler( data.prunePath, new ElementHandler() { public void onStart( ElementPath path ) { // do nothing here... } public void onEnd( ElementPath path ) { if ( isStopped() ) { // when a large file is processed and it should be stopped it is still reading the hole thing // the only solution I see is to prune / detach the document and this will lead into a // NPE or other errors depending on the parsing location - this will be treated in the catch part below // any better idea is welcome if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.Stopped" ) ); } data.stopPruning = true; path.getCurrent().getDocument().detach(); // trick to stop reader return; } // process a ROW element if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.StartProcessing" ) ); } Element row = path.getCurrent(); try { // Pass over the row instead of just the document. If // if there's only one row, there's no need to // go back to the whole document. processStreaming( row ); } catch ( Exception e ) { // catch the KettleException or others and forward to caller, e.g. when applyXPath() has a problem throw new RuntimeException( e ); } // prune the tree row.detach(); if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.EndProcessing" ) ); } } } ); } if ( IsInXMLField ) { // read string to parse data.document = reader.read( new StringReader( StringXML ) ); } else if ( readurl && KettleVFS.startsWithScheme( StringXML ) ) { data.document = reader.read( KettleVFS.getInputStream( StringXML ) ); } else if ( readurl ) { // read url as source HttpClient client = HttpClientManager.getInstance().createDefaultClient(); HttpGet method = new HttpGet( StringXML ); method.addHeader( "Accept-Encoding", "gzip" ); HttpResponse response = client.execute( method ); Header contentEncoding = response.getFirstHeader( "Content-Encoding" ); HttpEntity responseEntity = response.getEntity(); if ( responseEntity != null ) { if ( contentEncoding != null ) { String acceptEncodingValue = contentEncoding.getValue(); if ( acceptEncodingValue.contains( "gzip" ) ) { GZIPInputStream in = new GZIPInputStream( responseEntity.getContent() ); data.document = reader.read( in ); } } else { data.document = reader.read( responseEntity.getContent() ); } } } else { // get encoding. By default UTF-8 String encoding = "UTF-8"; if ( !Utils.isEmpty( meta.getEncoding() ) ) { encoding = meta.getEncoding(); } InputStream is = KettleVFS.getInputStream( file ); try { data.document = reader.read( is, encoding ); } finally { BaseStep.closeQuietly( is ); } } if ( meta.isNamespaceAware() ) { prepareNSMap( data.document.getRootElement() ); } } catch ( Exception e ) { if ( data.stopPruning ) { // ignore error when pruning return false; } else { throw new KettleException( e ); } } return true; } /** * Process chunk of data in streaming mode. Called only by the handler when pruning is true. Not allowed in * combination with meta.getIsInFields(), but could be redesigned later on. * */ private void processStreaming( Element row ) throws KettleException { data.document = row.getDocument(); if ( meta.isNamespaceAware() ) { prepareNSMap( data.document.getRootElement() ); } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ApplyXPath" ) ); } // If the prune path and the path are the same, then // we're processing one row at a time through here. if ( data.PathValue.equals( data.prunePath ) ) { data.an.set( 0, (AbstractNode) row ); data.nodesize = 1; // it's always just one row. data.nodenr = 0; if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ProcessingRows" ) ); } Object[] r = getXMLRowPutRowWithErrorhandling(); if ( !data.errorInRowButContinue ) { // do not put out the row but continue putRowOut( r ); // false when limit is reached, functionality is there but we can not stop reading the hole file // (slow but works) } data.nodesize = 0; data.nodenr = 0; return; } else { if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } } // main loop through the data until limit is reached or transformation is stopped // similar functionality like in BaseStep.runStepThread if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ProcessingRows" ) ); } boolean cont = true; while ( data.nodenr < data.nodesize && cont && !isStopped() ) { Object[] r = getXMLRowPutRowWithErrorhandling(); if ( data.errorInRowButContinue ) { continue; // do not put out the row but continue } cont = putRowOut( r ); // false when limit is reached, functionality is there but we can not stop reading the hole // file (slow but works) } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.FreeMemory" ) ); } // free allocated memory data.an.clear(); data.nodesize = data.an.size(); data.nodenr = 0; } public void prepareNSMap( Element l ) { @SuppressWarnings( "unchecked" ) List<Namespace> namespacesList = l.declaredNamespaces(); for ( Namespace ns : namespacesList ) { if ( ns.getPrefix().trim().length() == 0 ) { data.NAMESPACE.put( "pre" + data.NSPath.size(), ns.getURI() ); String path = ""; Element element = l; while ( element != null ) { if ( element.getNamespacePrefix() != null && element.getNamespacePrefix().length() > 0 ) { path = GetXMLDataMeta.N0DE_SEPARATOR + element.getNamespacePrefix() + ":" + element.getName() + path; } else { path = GetXMLDataMeta.N0DE_SEPARATOR + element.getName() + path; } element = element.getParent(); } data.NSPath.add( path ); } else { data.NAMESPACE.put( ns.getPrefix(), ns.getURI() ); } } @SuppressWarnings( "unchecked" ) List<Element> elementsList = l.elements(); for ( Element e : elementsList ) { prepareNSMap( e ); } } /** * Build an empty row based on the meta-data. * * @return empty row built */ private Object[] buildEmptyRow() { return RowDataUtil.allocateRowData( data.outputRowMeta.size() ); } private void handleMissingFiles() throws KettleException { List<FileObject> nonExistantFiles = data.files.getNonExistantFiles(); if ( nonExistantFiles.size() != 0 ) { String message = FileInputList.getRequiredFilesDescription( nonExistantFiles ); logError( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesTitle" ), BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFiles", message ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesMissing", message ) ); } List<FileObject> nonAccessibleFiles = data.files.getNonAccessibleFiles(); if ( nonAccessibleFiles.size() != 0 ) { String message = FileInputList.getRequiredFilesDescription( nonAccessibleFiles ); logError( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesTitle" ), BaseMessages.getString( PKG, "GetXMLData.Log.RequiredNotAccessibleFiles", message ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredNotAccessibleFilesMissing", message ) ); } } private boolean ReadNextString() { try { // Grab another row ... data.readrow = getRow(); if ( data.readrow == null ) { // finished processing! if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FinishedProcessing" ) ); } return false; } if ( first ) { first = false; data.nrReadRow = getInputRowMeta().size(); data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = data.inputRowMeta.clone(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore ); // Get total previous fields data.totalpreviousfields = data.inputRowMeta.size(); // Create convert meta-data objects that will contain Date & Number formatters data.convertRowMeta = new RowMeta(); for ( ValueMetaInterface valueMeta : data.convertRowMeta.getValueMetaList() ) { data.convertRowMeta .addValueMeta( ValueMetaFactory.cloneValueMeta( valueMeta, ValueMetaInterface.TYPE_STRING ) ); } // For String to <type> conversions, we allocate a conversion meta data row as well... // data.convertRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING ); // Check is XML field is provided if ( Utils.isEmpty( meta.getXMLField() ) ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.NoField" ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.NoField" ) ); } // cache the position of the field if ( data.indexOfXmlField < 0 ) { data.indexOfXmlField = getInputRowMeta().indexOfValue( meta.getXMLField() ); if ( data.indexOfXmlField < 0 ) { // The field is unreachable ! logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorFindingField", meta.getXMLField() ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Exception.CouldnotFindField", meta .getXMLField() ) ); } } } if ( meta.isInFields() ) { // get XML field value String Fieldvalue = getInputRowMeta().getString( data.readrow, data.indexOfXmlField ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.XMLStream", meta.getXMLField(), Fieldvalue ) ); } if ( meta.getIsAFile() ) { FileObject file = null; try { // XML source is a file. file = KettleVFS.getFileObject( environmentSubstitute( Fieldvalue ), getTransMeta() ); if ( meta.isIgnoreEmptyFile() && file.getContent().getSize() == 0 ) { logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + file.getName() ) ); return ReadNextString(); } // Open the XML document if ( !setDocument( null, file, false, false ) ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) ); } if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } addFileToResultFilesname( file ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize, file .getName().getBaseName() ) ); } } catch ( Exception e ) { throw new KettleException( e ); } finally { try { if ( file != null ) { file.close(); } } catch ( Exception e ) { // Ignore close errors } } } else { boolean url = false; boolean xmltring = true; if ( meta.isReadUrl() ) { url = true; xmltring = false; } // Open the XML document if ( !setDocument( Fieldvalue, null, xmltring, url ) ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) ); } // Apply XPath and set node list if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize ) ); } } } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.UnexpectedError", e.toString() ) ); stopAll(); logError( Const.getStackTracker( e ) ); setErrors( 1 ); return false; } return true; } private void addFileToResultFilesname( FileObject file ) throws Exception { if ( meta.addResultFile() ) { // Add this to the result file names... ResultFile resultFile = new ResultFile( ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname() ); resultFile.setComment( BaseMessages.getString( PKG, "GetXMLData.Log.FileAddedResult" ) ); addResultFile( resultFile ); } } public String addNSPrefix( String path, String loopPath ) { if ( data.NSPath.size() > 0 ) { String fullPath = loopPath; if ( !path.equals( fullPath ) ) { for ( String tmp : path.split( GetXMLDataMeta.N0DE_SEPARATOR ) ) { if ( tmp.equals( ".." ) ) { fullPath = fullPath.substring( 0, fullPath.lastIndexOf( GetXMLDataMeta.N0DE_SEPARATOR ) ); } else { fullPath += GetXMLDataMeta.N0DE_SEPARATOR + tmp; } } } int[] indexs = new int[fullPath.split( GetXMLDataMeta.N0DE_SEPARATOR ).length - 1]; java.util.Arrays.fill( indexs, -1 ); int length = 0; for ( int i = 0; i < data.NSPath.size(); i++ ) { if ( data.NSPath.get( i ).length() > length && fullPath.startsWith( data.NSPath.get( i ) ) ) { java.util.Arrays.fill( indexs, data.NSPath.get( i ).split( GetXMLDataMeta.N0DE_SEPARATOR ).length - 2, indexs.length, i ); length = data.NSPath.get( i ).length(); } } StringBuilder newPath = new StringBuilder(); String[] pathStrs = path.split( GetXMLDataMeta.N0DE_SEPARATOR ); for ( int i = 0; i < pathStrs.length; i++ ) { String tmp = pathStrs[i]; if ( newPath.length() > 0 ) { newPath.append( GetXMLDataMeta.N0DE_SEPARATOR ); } if ( tmp.length() > 0 && !tmp.contains( ":" ) && !tmp.contains( "." ) && !tmp.contains( GetXMLDataMeta.AT ) ) { int index = indexs[i + indexs.length - pathStrs.length]; if ( index >= 0 ) { newPath.append( "pre" ).append( index ).append( ":" ).append( tmp ); } else { newPath.append( tmp ); } } else { newPath.append( tmp ); } } return newPath.toString(); } return path; } @SuppressWarnings( "unchecked" ) private boolean applyXPath() { try { XPath xpath = data.document.createXPath( data.PathValue ); if ( meta.isNamespaceAware() ) { xpath = data.document.createXPath( addNSPrefix( data.PathValue, data.PathValue ) ); xpath.setNamespaceURIs( data.NAMESPACE ); } // get nodes list data.an = xpath.selectNodes( data.document ); data.nodesize = data.an.size(); data.nodenr = 0; } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage() ) ); return false; } return true; } private boolean openNextFile() { try { if ( data.filenr >= data.files.nrOfFiles() ) { // finished processing! if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FinishedProcessing" ) ); } return false; } // get file data.file = data.files.getFile( data.filenr ); data.filename = KettleVFS.getFilename( data.file ); // Add additional fields? if ( meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0 ) { data.shortFilename = data.file.getName().getBaseName(); } if ( meta.getPathField() != null && meta.getPathField().length() > 0 ) { data.path = KettleVFS.getFilename( data.file.getParent() ); } if ( meta.isHiddenField() != null && meta.isHiddenField().length() > 0 ) { data.hidden = data.file.isHidden(); } if ( meta.getExtensionField() != null && meta.getExtensionField().length() > 0 ) { data.extension = data.file.getName().getExtension(); } if ( meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0 ) { data.lastModificationDateTime = new Date( data.file.getContent().getLastModifiedTime() ); } if ( meta.getUriField() != null && meta.getUriField().length() > 0 ) { data.uriName = data.file.getName().getURI(); } if ( meta.getRootUriField() != null && meta.getRootUriField().length() > 0 ) { data.rootUriName = data.file.getName().getRootURI(); } // Check if file is empty long fileSize; try { fileSize = data.file.getContent().getSize(); } catch ( FileSystemException e ) { fileSize = -1; } if ( meta.getSizeField() != null && meta.getSizeField().length() > 0 ) { data.size = fileSize; } // Move file pointer ahead! data.filenr++; if ( meta.isIgnoreEmptyFile() && fileSize == 0 ) { // log only basic as a warning (was before logError) logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + data.file.getName() ) ); openNextFile(); } else { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.OpeningFile", data.file.toString() ) ); } // Open the XML document if ( !setDocument( null, data.file, false, false ) ) { if ( data.stopPruning ) { return false; // ignore error when stopped while pruning } throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) ); } // Apply XPath and set node list if ( data.prunePath == null ) { // this was already done in processStreaming() if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } } addFileToResultFilesname( data.file ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FileOpened", data.file.toString() ) ); logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize, data.file .getName().getBaseName() ) ); } } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.UnableToOpenFile", "" + data.filenr, data.file.toString(), e.toString() ) ); stopAll(); setErrors( 1 ); return false; } return true; } public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException { if ( first && !meta.isInFields() ) { first = false; data.files = meta.getFiles( this ); if ( !meta.isdoNotFailIfNoFile() && data.files.nrOfFiles() == 0 ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.NoFiles" ) ); } handleMissingFiles(); // Create the output row meta-data data.outputRowMeta = new RowMeta(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore ); // Create convert meta-data objects that will contain Date & Number formatters // For String to <type> conversions, we allocate a conversion meta data row as well... // data.convertRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING ); } // Grab a row Object[] r = getXMLRow(); if ( data.errorInRowButContinue ) { return true; // continue without putting the row out } if ( r == null ) { setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } return putRowOut( r ); } private boolean putRowOut( Object[] r ) throws KettleException { if ( log.isRowLevel() ) { logRowlevel( BaseMessages.getString( PKG, "GetXMLData.Log.ReadRow", data.outputRowMeta.getString( r ) ) ); } incrementLinesInput(); data.rownr++; putRow( data.outputRowMeta, r ); // copy row to output rowset(s); if ( meta.getRowLimit() > 0 && data.rownr > meta.getRowLimit() ) { // limit has been reached: stop now. setOutputDone(); return false; } return true; } private Object[] getXMLRow() throws KettleException { if ( !meta.isInFields() ) { while ( ( data.nodenr >= data.nodesize || data.file == null ) ) { if ( !openNextFile() ) { data.errorInRowButContinue = false; // stop in all cases return null; } } } return getXMLRowPutRowWithErrorhandling(); } private Object[] getXMLRowPutRowWithErrorhandling() throws KettleException { // Build an empty row based on the meta-data Object[] r; data.errorInRowButContinue = false; try { if ( meta.isInFields() ) { while ( ( data.nodenr >= data.nodesize || data.readrow == null ) ) { if ( !ReadNextString() ) { return null; } if ( data.readrow == null ) { return null; } } } r = processPutRow( data.an.get( data.nodenr ) ); } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Error.UnableReadFile" ), e ); } return r; } private Object[] processPutRow( Node node ) throws KettleException { // Create new row... Object[] outputRowData = buildEmptyRow(); // Create new row or clone if ( meta.isInFields() ) { System.arraycopy( data.readrow, 0, outputRowData, 0, data.nrReadRow ); } try { data.nodenr++; // Read fields... for ( int i = 0; i < data.nrInputFields; i++ ) { // Get field GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Get the Path to look for String XPathValue = xmlDataField.getResolvedXPath(); if ( meta.isuseToken() ) { // See if user use Token inside path field // The syntax is : @_Fieldname- // PDI will search for Fieldname value and replace it // Fieldname must be defined before the current node XPathValue = substituteToken( XPathValue, outputRowData ); if ( isDetailed() ) { logDetailed( XPathValue ); } } // Get node value String nodevalue; // Handle namespaces if ( meta.isNamespaceAware() ) { XPath xpathField = node.createXPath( addNSPrefix( XPathValue, data.PathValue ) ); xpathField.setNamespaceURIs( data.NAMESPACE ); if ( xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF ) { nodevalue = xpathField.valueOf( node ); } else { // nodevalue=xpathField.selectSingleNode(node).asXML(); Node n = xpathField.selectSingleNode( node ); if ( n != null ) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } else { if ( xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF ) { nodevalue = node.valueOf( XPathValue ); } else { // nodevalue=node.selectSingleNode(XPathValue).asXML(); Node n = node.selectSingleNode( XPathValue ); if ( n != null ) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } // Do trimming switch ( xmlDataField.getTrimType() ) { case GetXMLDataField.TYPE_TRIM_LEFT: nodevalue = Const.ltrim( nodevalue ); break; case GetXMLDataField.TYPE_TRIM_RIGHT: nodevalue = Const.rtrim( nodevalue ); break; case GetXMLDataField.TYPE_TRIM_BOTH: nodevalue = Const.trim( nodevalue ); break; default: break; } // Do conversions // ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta( data.totalpreviousfields + i ); ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta( data.totalpreviousfields + i ); outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData( sourceValueMeta, nodevalue ); // Do we need to repeat this field if it is null? if ( meta.getInputFields()[i].isRepeated() ) { if ( data.previousRow != null && Utils.isEmpty( nodevalue ) ) { outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields + i]; } } } // End of loop over fields... int rowIndex = data.totalpreviousfields + data.nrInputFields; // See if we need to add the filename to the row... if ( meta.includeFilename() && !Utils.isEmpty( meta.getFilenameField() ) ) { outputRowData[rowIndex++] = data.filename; } // See if we need to add the row number to the row... if ( meta.includeRowNumber() && !Utils.isEmpty( meta.getRowNumberField() ) ) { outputRowData[rowIndex++] = data.rownr; } // Possibly add short filename... if ( meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0 ) { outputRowData[rowIndex++] = data.shortFilename; } // Add Extension if ( meta.getExtensionField() != null && meta.getExtensionField().length() > 0 ) { outputRowData[rowIndex++] = data.extension; } // add path if ( meta.getPathField() != null && meta.getPathField().length() > 0 ) { outputRowData[rowIndex++] = data.path; } // Add Size if ( meta.getSizeField() != null && meta.getSizeField().length() > 0 ) { outputRowData[rowIndex++] = data.size; } // add Hidden if ( meta.isHiddenField() != null && meta.isHiddenField().length() > 0 ) { outputRowData[rowIndex++] = Boolean.valueOf( data.path ); } // Add modification date if ( meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0 ) { outputRowData[rowIndex++] = data.lastModificationDateTime; } // Add Uri if ( meta.getUriField() != null && meta.getUriField().length() > 0 ) { outputRowData[rowIndex++] = data.uriName; } // Add RootUri if ( meta.getRootUriField() != null && meta.getRootUriField().length() > 0 ) { outputRowData[rowIndex] = data.rootUriName; } RowMetaInterface irow = getInputRowMeta(); if ( irow == null ) { data.previousRow = outputRowData; } else { // clone to previously allocated array to make sure next step doesn't // change it in between... System.arraycopy( outputRowData, 0, this.prevRow, 0, outputRowData.length ); // Pick up everything else that needs a real deep clone data.previousRow = irow.cloneRow( outputRowData, this.prevRow ); } } catch ( Exception e ) { if ( getStepMeta().isDoingErrorHandling() ) { // Simply add this row to the error row putError( data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001" ); data.errorInRowButContinue = true; return null; } else { logError( e.toString() ); throw new KettleException( e.toString() ); } } return outputRowData; } public String substituteToken( String aString, Object[] outputRowData ) { if ( aString == null ) { return null; } StringBuilder buffer = new StringBuilder(); String rest = aString; // search for closing string int i = rest.indexOf( data.tokenStart ); while ( i > -1 ) { int j = rest.indexOf( data.tokenEnd, i + data.tokenStart.length() ); // search for closing string if ( j > -1 ) { String varName = rest.substring( i + data.tokenStart.length(), j ); Object Value = varName; for ( int k = 0; k < data.nrInputFields; k++ ) { GetXMLDataField Tmp_xmlInputField = meta.getInputFields()[k]; if ( Tmp_xmlInputField.getName().equalsIgnoreCase( varName ) ) { Value = "'" + outputRowData[data.totalpreviousfields + k] + "'"; } } buffer.append( rest.substring( 0, i ) ); buffer.append( Value ); rest = rest.substring( j + data.tokenEnd.length() ); } else { // no closing tag found; end the search buffer.append( rest ); rest = ""; } // keep searching i = rest.indexOf( data.tokenEnd ); } buffer.append( rest ); return buffer.toString(); } public boolean init( StepMetaInterface smi, StepDataInterface sdi ) { meta = (GetXMLDataMeta) smi; data = (GetXMLDataData) sdi; if ( super.init( smi, sdi ) ) { data.rownr = 1L; data.nrInputFields = meta.getInputFields().length; // correct attribute path if needed // do it once for ( int i = 0; i < data.nrInputFields; i++ ) { GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Resolve variable substitution String XPathValue = environmentSubstitute( xmlDataField.getXPath() ); if ( xmlDataField.getElementType() == GetXMLDataField.ELEMENT_TYPE_ATTRIBUT ) { // We have an attribute // do we need to add leading @? // Only put @ to the last element in path, not in front at all int last = XPathValue.lastIndexOf( GetXMLDataMeta.N0DE_SEPARATOR ); if ( last > -1 ) { last++; String attribut = XPathValue.substring( last, XPathValue.length() ); if ( !attribut.startsWith( GetXMLDataMeta.AT ) ) { XPathValue = XPathValue.substring( 0, last ) + GetXMLDataMeta.AT + attribut; } } else { if ( !XPathValue.startsWith( GetXMLDataMeta.AT ) ) { XPathValue = GetXMLDataMeta.AT + XPathValue; } } } xmlDataField.setResolvedXPath( XPathValue ); } data.PathValue = environmentSubstitute( meta.getLoopXPath() ); if ( Utils.isEmpty( data.PathValue ) ) { logError( BaseMessages.getString( PKG, "GetXMLData.Error.EmptyPath" ) ); return false; } if ( !data.PathValue.substring( 0, 1 ).equals( GetXMLDataMeta.N0DE_SEPARATOR ) ) { data.PathValue = GetXMLDataMeta.N0DE_SEPARATOR + data.PathValue; } if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopXPath", data.PathValue ) ); } data.prunePath = environmentSubstitute( meta.getPrunePath() ); if ( data.prunePath != null ) { if ( Utils.isEmpty( data.prunePath.trim() ) ) { data.prunePath = null; } else { // ensure a leading slash if ( !data.prunePath.startsWith( GetXMLDataMeta.N0DE_SEPARATOR ) ) { data.prunePath = GetXMLDataMeta.N0DE_SEPARATOR + data.prunePath; } // check if other conditions apply that do not allow pruning if ( meta.isInFields() ) { data.prunePath = null; // not possible by design, could be changed later on } } } return true; } return false; } public void dispose( StepMetaInterface smi, StepDataInterface sdi ) { meta = (GetXMLDataMeta) smi; data = (GetXMLDataData) sdi; if ( data.file != null ) { try { data.file.close(); } catch ( Exception e ) { // Ignore close errors } } if ( data.an != null ) { data.an.clear(); data.an = null; } if ( data.NAMESPACE != null ) { data.NAMESPACE.clear(); data.NAMESPACE = null; } if ( data.NSPath != null ) { data.NSPath.clear(); data.NSPath = null; } if ( data.readrow != null ) { data.readrow = null; } if ( data.document != null ) { data.document = null; } if ( data.fr != null ) { BaseStep.closeQuietly( data.fr ); } if ( data.is != null ) { BaseStep.closeQuietly( data.is ); } if ( data.files != null ) { data.files = null; } super.dispose( smi, sdi ); } }
plugins/xml/core/src/main/java/org/pentaho/di/trans/steps/getxmldata/GetXMLData.java
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.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 org.pentaho.di.trans.steps.getxmldata; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.http.client.methods.HttpGet; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.ElementPath; import org.dom4j.Namespace; import org.dom4j.Node; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import org.dom4j.tree.AbstractNode; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.HttpClientManager; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.fileinput.FileInputList; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaFactory; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLParserFactoryProducer; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Read XML files, parse them and convert them to rows and writes these to one or more output streams. * * @author Samatar,Brahim * @since 20-06-2007 */ public class GetXMLData extends BaseStep implements StepInterface { private static Class<?> PKG = GetXMLDataMeta.class; // for i18n purposes, needed by Translator2!! private GetXMLDataMeta meta; private GetXMLDataData data; private Object[] prevRow = null; // A pre-allocated spot for the previous row public GetXMLData( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } protected boolean setDocument( String StringXML, FileObject file, boolean IsInXMLField, boolean readurl ) throws KettleException { this.prevRow = buildEmptyRow(); // pre-allocate previous row try { SAXReader reader = XMLParserFactoryProducer.getSAXReader( null ); data.stopPruning = false; // Validate XML against specified schema? if ( meta.isValidating() ) { reader.setValidation( true ); reader.setFeature( "http://apache.org/xml/features/validation/schema", true ); } else { // Ignore DTD declarations reader.setEntityResolver( new IgnoreDTDEntityResolver() ); } // Ignore comments? if ( meta.isIgnoreComments() ) { reader.setIgnoreComments( true ); } if ( data.prunePath != null ) { // when pruning is on: reader.read() below will wait until all is processed in the handler if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.Activated" ) ); } if ( data.PathValue.equals( data.prunePath ) ) { // Edge case, but if true, there will only ever be one item in the list data.an = new ArrayList<>( 1 ); // pre-allocate array and sizes data.an.add( null ); } reader.addHandler( data.prunePath, new ElementHandler() { public void onStart( ElementPath path ) { // do nothing here... } public void onEnd( ElementPath path ) { if ( isStopped() ) { // when a large file is processed and it should be stopped it is still reading the hole thing // the only solution I see is to prune / detach the document and this will lead into a // NPE or other errors depending on the parsing location - this will be treated in the catch part below // any better idea is welcome if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.Stopped" ) ); } data.stopPruning = true; path.getCurrent().getDocument().detach(); // trick to stop reader return; } // process a ROW element if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.StartProcessing" ) ); } Element row = path.getCurrent(); try { // Pass over the row instead of just the document. If // if there's only one row, there's no need to // go back to the whole document. processStreaming( row ); } catch ( Exception e ) { // catch the KettleException or others and forward to caller, e.g. when applyXPath() has a problem throw new RuntimeException( e ); } // prune the tree row.detach(); if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.EndProcessing" ) ); } } } ); } if ( IsInXMLField ) { // read string to parse data.document = reader.read( new StringReader( StringXML ) ); } else if ( readurl && KettleVFS.startsWithScheme( StringXML ) ) { data.document = reader.read( KettleVFS.getInputStream( StringXML ) ); } else if ( readurl ) { // read url as source HttpClient client = HttpClientManager.getInstance().createDefaultClient(); HttpGet method = new HttpGet( StringXML ); method.addHeader( "Accept-Encoding", "gzip" ); HttpResponse response = client.execute( method ); Header contentEncoding = response.getFirstHeader( "Content-Encoding" ); HttpEntity responseEntity = response.getEntity(); if ( responseEntity != null ) { if ( contentEncoding != null ) { String acceptEncodingValue = contentEncoding.getValue(); if ( acceptEncodingValue.contains( "gzip" ) ) { GZIPInputStream in = new GZIPInputStream( responseEntity.getContent() ); data.document = reader.read( in ); } } else { data.document = reader.read( responseEntity.getContent() ); } } } else { // get encoding. By default UTF-8 String encoding = "UTF-8"; if ( !Utils.isEmpty( meta.getEncoding() ) ) { encoding = meta.getEncoding(); } InputStream is = KettleVFS.getInputStream( file ); try { data.document = reader.read( is, encoding ); } finally { BaseStep.closeQuietly( is ); } } if ( meta.isNamespaceAware() ) { prepareNSMap( data.document.getRootElement() ); } } catch ( Exception e ) { if ( data.stopPruning ) { // ignore error when pruning return false; } else { throw new KettleException( e ); } } return true; } /** * Process chunk of data in streaming mode. Called only by the handler when pruning is true. Not allowed in * combination with meta.getIsInFields(), but could be redesigned later on. * */ private void processStreaming( Element row ) throws KettleException { data.document = row.getDocument(); if ( meta.isNamespaceAware() ) { prepareNSMap( data.document.getRootElement() ); } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ApplyXPath" ) ); } // If the prune path and the path are the same, then // we're processing one row at a time through here. if ( data.PathValue.equals( data.prunePath ) ) { data.an.set( 0, (AbstractNode) row ); data.nodesize = 1; // it's always just one row. data.nodenr = 0; if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ProcessingRows" ) ); } Object[] r = getXMLRowPutRowWithErrorhandling(); if ( !data.errorInRowButContinue ) { // do not put out the row but continue putRowOut( r ); // false when limit is reached, functionality is there but we can not stop reading the hole file // (slow but works) } data.nodesize = 0; data.nodenr = 0; return; } else { if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } } // main loop through the data until limit is reached or transformation is stopped // similar functionality like in BaseStep.runStepThread if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.ProcessingRows" ) ); } boolean cont = true; while ( data.nodenr < data.nodesize && cont && !isStopped() ) { Object[] r = getXMLRowPutRowWithErrorhandling(); if ( data.errorInRowButContinue ) { continue; // do not put out the row but continue } cont = putRowOut( r ); // false when limit is reached, functionality is there but we can not stop reading the hole // file (slow but works) } if ( log.isDebug() ) { logDebug( BaseMessages.getString( PKG, "GetXMLData.Log.StreamingMode.FreeMemory" ) ); } // free allocated memory data.an.clear(); data.nodesize = data.an.size(); data.nodenr = 0; } public void prepareNSMap( Element l ) { @SuppressWarnings( "unchecked" ) List<Namespace> namespacesList = l.declaredNamespaces(); for ( Namespace ns : namespacesList ) { if ( ns.getPrefix().trim().length() == 0 ) { data.NAMESPACE.put( "pre" + data.NSPath.size(), ns.getURI() ); String path = ""; Element element = l; while ( element != null ) { if ( element.getNamespacePrefix() != null && element.getNamespacePrefix().length() > 0 ) { path = GetXMLDataMeta.N0DE_SEPARATOR + element.getNamespacePrefix() + ":" + element.getName() + path; } else { path = GetXMLDataMeta.N0DE_SEPARATOR + element.getName() + path; } element = element.getParent(); } data.NSPath.add( path ); } else { data.NAMESPACE.put( ns.getPrefix(), ns.getURI() ); } } @SuppressWarnings( "unchecked" ) List<Element> elementsList = l.elements(); for ( Element e : elementsList ) { prepareNSMap( e ); } } /** * Build an empty row based on the meta-data. * * @return empty row built */ private Object[] buildEmptyRow() { return RowDataUtil.allocateRowData( data.outputRowMeta.size() ); } private void handleMissingFiles() throws KettleException { List<FileObject> nonExistantFiles = data.files.getNonExistantFiles(); if ( nonExistantFiles.size() != 0 ) { String message = FileInputList.getRequiredFilesDescription( nonExistantFiles ); logError( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesTitle" ), BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFiles", message ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesMissing", message ) ); } List<FileObject> nonAccessibleFiles = data.files.getNonAccessibleFiles(); if ( nonAccessibleFiles.size() != 0 ) { String message = FileInputList.getRequiredFilesDescription( nonAccessibleFiles ); logError( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredFilesTitle" ), BaseMessages.getString( PKG, "GetXMLData.Log.RequiredNotAccessibleFiles", message ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.RequiredNotAccessibleFilesMissing", message ) ); } } private boolean ReadNextString() { try { // Grab another row ... data.readrow = getRow(); if ( data.readrow == null ) { // finished processing! if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FinishedProcessing" ) ); } return false; } if ( first ) { first = false; data.nrReadRow = getInputRowMeta().size(); data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = data.inputRowMeta.clone(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore ); // Get total previous fields data.totalpreviousfields = data.inputRowMeta.size(); // Create convert meta-data objects that will contain Date & Number formatters data.convertRowMeta = new RowMeta(); for ( ValueMetaInterface valueMeta : data.convertRowMeta.getValueMetaList() ) { data.convertRowMeta .addValueMeta( ValueMetaFactory.cloneValueMeta( valueMeta, ValueMetaInterface.TYPE_STRING ) ); } // For String to <type> conversions, we allocate a conversion meta data row as well... // data.convertRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING ); // Check is XML field is provided if ( Utils.isEmpty( meta.getXMLField() ) ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.NoField" ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.NoField" ) ); } // cache the position of the field if ( data.indexOfXmlField < 0 ) { data.indexOfXmlField = getInputRowMeta().indexOfValue( meta.getXMLField() ); if ( data.indexOfXmlField < 0 ) { // The field is unreachable ! logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorFindingField", meta.getXMLField() ) ); throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Exception.CouldnotFindField", meta .getXMLField() ) ); } } } if ( meta.isInFields() ) { // get XML field value String Fieldvalue = getInputRowMeta().getString( data.readrow, data.indexOfXmlField ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.XMLStream", meta.getXMLField(), Fieldvalue ) ); } if ( meta.getIsAFile() ) { FileObject file = null; try { // XML source is a file. file = KettleVFS.getFileObject( Fieldvalue, getTransMeta() ); if ( meta.isIgnoreEmptyFile() && file.getContent().getSize() == 0 ) { logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + file.getName() ) ); return ReadNextString(); } // Open the XML document if ( !setDocument( null, file, false, false ) ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) ); } if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } addFileToResultFilesname( file ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize, file .getName().getBaseName() ) ); } } catch ( Exception e ) { throw new KettleException( e ); } finally { try { if ( file != null ) { file.close(); } } catch ( Exception e ) { // Ignore close errors } } } else { boolean url = false; boolean xmltring = true; if ( meta.isReadUrl() ) { url = true; xmltring = false; } // Open the XML document if ( !setDocument( Fieldvalue, null, xmltring, url ) ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) ); } // Apply XPath and set node list if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize ) ); } } } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.UnexpectedError", e.toString() ) ); stopAll(); logError( Const.getStackTracker( e ) ); setErrors( 1 ); return false; } return true; } private void addFileToResultFilesname( FileObject file ) throws Exception { if ( meta.addResultFile() ) { // Add this to the result file names... ResultFile resultFile = new ResultFile( ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname() ); resultFile.setComment( BaseMessages.getString( PKG, "GetXMLData.Log.FileAddedResult" ) ); addResultFile( resultFile ); } } public String addNSPrefix( String path, String loopPath ) { if ( data.NSPath.size() > 0 ) { String fullPath = loopPath; if ( !path.equals( fullPath ) ) { for ( String tmp : path.split( GetXMLDataMeta.N0DE_SEPARATOR ) ) { if ( tmp.equals( ".." ) ) { fullPath = fullPath.substring( 0, fullPath.lastIndexOf( GetXMLDataMeta.N0DE_SEPARATOR ) ); } else { fullPath += GetXMLDataMeta.N0DE_SEPARATOR + tmp; } } } int[] indexs = new int[fullPath.split( GetXMLDataMeta.N0DE_SEPARATOR ).length - 1]; java.util.Arrays.fill( indexs, -1 ); int length = 0; for ( int i = 0; i < data.NSPath.size(); i++ ) { if ( data.NSPath.get( i ).length() > length && fullPath.startsWith( data.NSPath.get( i ) ) ) { java.util.Arrays.fill( indexs, data.NSPath.get( i ).split( GetXMLDataMeta.N0DE_SEPARATOR ).length - 2, indexs.length, i ); length = data.NSPath.get( i ).length(); } } StringBuilder newPath = new StringBuilder(); String[] pathStrs = path.split( GetXMLDataMeta.N0DE_SEPARATOR ); for ( int i = 0; i < pathStrs.length; i++ ) { String tmp = pathStrs[i]; if ( newPath.length() > 0 ) { newPath.append( GetXMLDataMeta.N0DE_SEPARATOR ); } if ( tmp.length() > 0 && !tmp.contains( ":" ) && !tmp.contains( "." ) && !tmp.contains( GetXMLDataMeta.AT ) ) { int index = indexs[i + indexs.length - pathStrs.length]; if ( index >= 0 ) { newPath.append( "pre" ).append( index ).append( ":" ).append( tmp ); } else { newPath.append( tmp ); } } else { newPath.append( tmp ); } } return newPath.toString(); } return path; } @SuppressWarnings( "unchecked" ) private boolean applyXPath() { try { XPath xpath = data.document.createXPath( data.PathValue ); if ( meta.isNamespaceAware() ) { xpath = data.document.createXPath( addNSPrefix( data.PathValue, data.PathValue ) ); xpath.setNamespaceURIs( data.NAMESPACE ); } // get nodes list data.an = xpath.selectNodes( data.document ); data.nodesize = data.an.size(); data.nodenr = 0; } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage() ) ); return false; } return true; } private boolean openNextFile() { try { if ( data.filenr >= data.files.nrOfFiles() ) { // finished processing! if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FinishedProcessing" ) ); } return false; } // get file data.file = data.files.getFile( data.filenr ); data.filename = KettleVFS.getFilename( data.file ); // Add additional fields? if ( meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0 ) { data.shortFilename = data.file.getName().getBaseName(); } if ( meta.getPathField() != null && meta.getPathField().length() > 0 ) { data.path = KettleVFS.getFilename( data.file.getParent() ); } if ( meta.isHiddenField() != null && meta.isHiddenField().length() > 0 ) { data.hidden = data.file.isHidden(); } if ( meta.getExtensionField() != null && meta.getExtensionField().length() > 0 ) { data.extension = data.file.getName().getExtension(); } if ( meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0 ) { data.lastModificationDateTime = new Date( data.file.getContent().getLastModifiedTime() ); } if ( meta.getUriField() != null && meta.getUriField().length() > 0 ) { data.uriName = data.file.getName().getURI(); } if ( meta.getRootUriField() != null && meta.getRootUriField().length() > 0 ) { data.rootUriName = data.file.getName().getRootURI(); } // Check if file is empty long fileSize; try { fileSize = data.file.getContent().getSize(); } catch ( FileSystemException e ) { fileSize = -1; } if ( meta.getSizeField() != null && meta.getSizeField().length() > 0 ) { data.size = fileSize; } // Move file pointer ahead! data.filenr++; if ( meta.isIgnoreEmptyFile() && fileSize == 0 ) { // log only basic as a warning (was before logError) logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + data.file.getName() ) ); openNextFile(); } else { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.OpeningFile", data.file.toString() ) ); } // Open the XML document if ( !setDocument( null, data.file, false, false ) ) { if ( data.stopPruning ) { return false; // ignore error when stopped while pruning } throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableCreateDocument" ) ); } // Apply XPath and set node list if ( data.prunePath == null ) { // this was already done in processStreaming() if ( !applyXPath() ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.UnableApplyXPath" ) ); } } addFileToResultFilesname( data.file ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.FileOpened", data.file.toString() ) ); logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopFileOccurences", "" + data.nodesize, data.file .getName().getBaseName() ) ); } } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "GetXMLData.Log.UnableToOpenFile", "" + data.filenr, data.file.toString(), e.toString() ) ); stopAll(); setErrors( 1 ); return false; } return true; } public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException { if ( first && !meta.isInFields() ) { first = false; data.files = meta.getFiles( this ); if ( !meta.isdoNotFailIfNoFile() && data.files.nrOfFiles() == 0 ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Log.NoFiles" ) ); } handleMissingFiles(); // Create the output row meta-data data.outputRowMeta = new RowMeta(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore ); // Create convert meta-data objects that will contain Date & Number formatters // For String to <type> conversions, we allocate a conversion meta data row as well... // data.convertRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING ); } // Grab a row Object[] r = getXMLRow(); if ( data.errorInRowButContinue ) { return true; // continue without putting the row out } if ( r == null ) { setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } return putRowOut( r ); } private boolean putRowOut( Object[] r ) throws KettleException { if ( log.isRowLevel() ) { logRowlevel( BaseMessages.getString( PKG, "GetXMLData.Log.ReadRow", data.outputRowMeta.getString( r ) ) ); } incrementLinesInput(); data.rownr++; putRow( data.outputRowMeta, r ); // copy row to output rowset(s); if ( meta.getRowLimit() > 0 && data.rownr > meta.getRowLimit() ) { // limit has been reached: stop now. setOutputDone(); return false; } return true; } private Object[] getXMLRow() throws KettleException { if ( !meta.isInFields() ) { while ( ( data.nodenr >= data.nodesize || data.file == null ) ) { if ( !openNextFile() ) { data.errorInRowButContinue = false; // stop in all cases return null; } } } return getXMLRowPutRowWithErrorhandling(); } private Object[] getXMLRowPutRowWithErrorhandling() throws KettleException { // Build an empty row based on the meta-data Object[] r; data.errorInRowButContinue = false; try { if ( meta.isInFields() ) { while ( ( data.nodenr >= data.nodesize || data.readrow == null ) ) { if ( !ReadNextString() ) { return null; } if ( data.readrow == null ) { return null; } } } r = processPutRow( data.an.get( data.nodenr ) ); } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( PKG, "GetXMLData.Error.UnableReadFile" ), e ); } return r; } private Object[] processPutRow( Node node ) throws KettleException { // Create new row... Object[] outputRowData = buildEmptyRow(); // Create new row or clone if ( meta.isInFields() ) { System.arraycopy( data.readrow, 0, outputRowData, 0, data.nrReadRow ); } try { data.nodenr++; // Read fields... for ( int i = 0; i < data.nrInputFields; i++ ) { // Get field GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Get the Path to look for String XPathValue = xmlDataField.getResolvedXPath(); if ( meta.isuseToken() ) { // See if user use Token inside path field // The syntax is : @_Fieldname- // PDI will search for Fieldname value and replace it // Fieldname must be defined before the current node XPathValue = substituteToken( XPathValue, outputRowData ); if ( isDetailed() ) { logDetailed( XPathValue ); } } // Get node value String nodevalue; // Handle namespaces if ( meta.isNamespaceAware() ) { XPath xpathField = node.createXPath( addNSPrefix( XPathValue, data.PathValue ) ); xpathField.setNamespaceURIs( data.NAMESPACE ); if ( xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF ) { nodevalue = xpathField.valueOf( node ); } else { // nodevalue=xpathField.selectSingleNode(node).asXML(); Node n = xpathField.selectSingleNode( node ); if ( n != null ) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } else { if ( xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF ) { nodevalue = node.valueOf( XPathValue ); } else { // nodevalue=node.selectSingleNode(XPathValue).asXML(); Node n = node.selectSingleNode( XPathValue ); if ( n != null ) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } // Do trimming switch ( xmlDataField.getTrimType() ) { case GetXMLDataField.TYPE_TRIM_LEFT: nodevalue = Const.ltrim( nodevalue ); break; case GetXMLDataField.TYPE_TRIM_RIGHT: nodevalue = Const.rtrim( nodevalue ); break; case GetXMLDataField.TYPE_TRIM_BOTH: nodevalue = Const.trim( nodevalue ); break; default: break; } // Do conversions // ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta( data.totalpreviousfields + i ); ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta( data.totalpreviousfields + i ); outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData( sourceValueMeta, nodevalue ); // Do we need to repeat this field if it is null? if ( meta.getInputFields()[i].isRepeated() ) { if ( data.previousRow != null && Utils.isEmpty( nodevalue ) ) { outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields + i]; } } } // End of loop over fields... int rowIndex = data.totalpreviousfields + data.nrInputFields; // See if we need to add the filename to the row... if ( meta.includeFilename() && !Utils.isEmpty( meta.getFilenameField() ) ) { outputRowData[rowIndex++] = data.filename; } // See if we need to add the row number to the row... if ( meta.includeRowNumber() && !Utils.isEmpty( meta.getRowNumberField() ) ) { outputRowData[rowIndex++] = data.rownr; } // Possibly add short filename... if ( meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0 ) { outputRowData[rowIndex++] = data.shortFilename; } // Add Extension if ( meta.getExtensionField() != null && meta.getExtensionField().length() > 0 ) { outputRowData[rowIndex++] = data.extension; } // add path if ( meta.getPathField() != null && meta.getPathField().length() > 0 ) { outputRowData[rowIndex++] = data.path; } // Add Size if ( meta.getSizeField() != null && meta.getSizeField().length() > 0 ) { outputRowData[rowIndex++] = data.size; } // add Hidden if ( meta.isHiddenField() != null && meta.isHiddenField().length() > 0 ) { outputRowData[rowIndex++] = Boolean.valueOf( data.path ); } // Add modification date if ( meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0 ) { outputRowData[rowIndex++] = data.lastModificationDateTime; } // Add Uri if ( meta.getUriField() != null && meta.getUriField().length() > 0 ) { outputRowData[rowIndex++] = data.uriName; } // Add RootUri if ( meta.getRootUriField() != null && meta.getRootUriField().length() > 0 ) { outputRowData[rowIndex] = data.rootUriName; } RowMetaInterface irow = getInputRowMeta(); if ( irow == null ) { data.previousRow = outputRowData; } else { // clone to previously allocated array to make sure next step doesn't // change it in between... System.arraycopy( outputRowData, 0, this.prevRow, 0, outputRowData.length ); // Pick up everything else that needs a real deep clone data.previousRow = irow.cloneRow( outputRowData, this.prevRow ); } } catch ( Exception e ) { if ( getStepMeta().isDoingErrorHandling() ) { // Simply add this row to the error row putError( data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001" ); data.errorInRowButContinue = true; return null; } else { logError( e.toString() ); throw new KettleException( e.toString() ); } } return outputRowData; } public String substituteToken( String aString, Object[] outputRowData ) { if ( aString == null ) { return null; } StringBuilder buffer = new StringBuilder(); String rest = aString; // search for closing string int i = rest.indexOf( data.tokenStart ); while ( i > -1 ) { int j = rest.indexOf( data.tokenEnd, i + data.tokenStart.length() ); // search for closing string if ( j > -1 ) { String varName = rest.substring( i + data.tokenStart.length(), j ); Object Value = varName; for ( int k = 0; k < data.nrInputFields; k++ ) { GetXMLDataField Tmp_xmlInputField = meta.getInputFields()[k]; if ( Tmp_xmlInputField.getName().equalsIgnoreCase( varName ) ) { Value = "'" + outputRowData[data.totalpreviousfields + k] + "'"; } } buffer.append( rest.substring( 0, i ) ); buffer.append( Value ); rest = rest.substring( j + data.tokenEnd.length() ); } else { // no closing tag found; end the search buffer.append( rest ); rest = ""; } // keep searching i = rest.indexOf( data.tokenEnd ); } buffer.append( rest ); return buffer.toString(); } public boolean init( StepMetaInterface smi, StepDataInterface sdi ) { meta = (GetXMLDataMeta) smi; data = (GetXMLDataData) sdi; if ( super.init( smi, sdi ) ) { data.rownr = 1L; data.nrInputFields = meta.getInputFields().length; // correct attribute path if needed // do it once for ( int i = 0; i < data.nrInputFields; i++ ) { GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Resolve variable substitution String XPathValue = environmentSubstitute( xmlDataField.getXPath() ); if ( xmlDataField.getElementType() == GetXMLDataField.ELEMENT_TYPE_ATTRIBUT ) { // We have an attribute // do we need to add leading @? // Only put @ to the last element in path, not in front at all int last = XPathValue.lastIndexOf( GetXMLDataMeta.N0DE_SEPARATOR ); if ( last > -1 ) { last++; String attribut = XPathValue.substring( last, XPathValue.length() ); if ( !attribut.startsWith( GetXMLDataMeta.AT ) ) { XPathValue = XPathValue.substring( 0, last ) + GetXMLDataMeta.AT + attribut; } } else { if ( !XPathValue.startsWith( GetXMLDataMeta.AT ) ) { XPathValue = GetXMLDataMeta.AT + XPathValue; } } } xmlDataField.setResolvedXPath( XPathValue ); } data.PathValue = environmentSubstitute( meta.getLoopXPath() ); if ( Utils.isEmpty( data.PathValue ) ) { logError( BaseMessages.getString( PKG, "GetXMLData.Error.EmptyPath" ) ); return false; } if ( !data.PathValue.substring( 0, 1 ).equals( GetXMLDataMeta.N0DE_SEPARATOR ) ) { data.PathValue = GetXMLDataMeta.N0DE_SEPARATOR + data.PathValue; } if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "GetXMLData.Log.LoopXPath", data.PathValue ) ); } data.prunePath = environmentSubstitute( meta.getPrunePath() ); if ( data.prunePath != null ) { if ( Utils.isEmpty( data.prunePath.trim() ) ) { data.prunePath = null; } else { // ensure a leading slash if ( !data.prunePath.startsWith( GetXMLDataMeta.N0DE_SEPARATOR ) ) { data.prunePath = GetXMLDataMeta.N0DE_SEPARATOR + data.prunePath; } // check if other conditions apply that do not allow pruning if ( meta.isInFields() ) { data.prunePath = null; // not possible by design, could be changed later on } } } return true; } return false; } public void dispose( StepMetaInterface smi, StepDataInterface sdi ) { meta = (GetXMLDataMeta) smi; data = (GetXMLDataData) sdi; if ( data.file != null ) { try { data.file.close(); } catch ( Exception e ) { // Ignore close errors } } if ( data.an != null ) { data.an.clear(); data.an = null; } if ( data.NAMESPACE != null ) { data.NAMESPACE.clear(); data.NAMESPACE = null; } if ( data.NSPath != null ) { data.NSPath.clear(); data.NSPath = null; } if ( data.readrow != null ) { data.readrow = null; } if ( data.document != null ) { data.document = null; } if ( data.fr != null ) { BaseStep.closeQuietly( data.fr ); } if ( data.is != null ) { BaseStep.closeQuietly( data.is ); } if ( data.files != null ) { data.files = null; } super.dispose( smi, sdi ); } }
[PDI-17478] Can't use directory path variables on Get data from XML step
plugins/xml/core/src/main/java/org/pentaho/di/trans/steps/getxmldata/GetXMLData.java
[PDI-17478] Can't use directory path variables on Get data from XML step
<ide><path>lugins/xml/core/src/main/java/org/pentaho/di/trans/steps/getxmldata/GetXMLData.java <ide> FileObject file = null; <ide> try { <ide> // XML source is a file. <del> file = KettleVFS.getFileObject( Fieldvalue, getTransMeta() ); <add> file = KettleVFS.getFileObject( environmentSubstitute( Fieldvalue ), getTransMeta() ); <ide> <ide> if ( meta.isIgnoreEmptyFile() && file.getContent().getSize() == 0 ) { <ide> logBasic( BaseMessages.getString( PKG, "GetXMLData.Error.FileSizeZero", "" + file.getName() ) );
Java
apache-2.0
911be20abf3b7905f0cfd531160a3e8463009838
0
graphhopper/graphhopper,graphhopper/graphhopper,graphhopper/graphhopper,graphhopper/graphhopper
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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 com.graphhopper.routing.lm; import com.graphhopper.routing.Dijkstra; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.BeelineWeightApproximator; import com.graphhopper.routing.weighting.WeightApproximator; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; import java.util.Arrays; /** * This class is a weight approximation based on precalculated landmarks. * * @author Peter Karich */ public class LMApproximator implements WeightApproximator { private final LandmarkStorage lms; private final Weighting weighting; private int[] activeLandmarkIndices; private int[] weightsFromActiveLandmarksToT; private int[] weightsFromTToActiveLandmarks; private double epsilon = 1; private int towerNodeNextToT = -1; private double weightFromTToTowerNode; private boolean recalculateActiveLandmarks = true; private final double factor; private final boolean reverse; private final int maxBaseNodes; private final Graph graph; private final WeightApproximator fallBackApproximation; private boolean fallback = false; public static LMApproximator forLandmarks(Graph g, LandmarkStorage lms, int activeLM) { return new LMApproximator(g, lms.getWeighting(), lms.getBaseNodes(), lms, activeLM, lms.getFactor(), false); } public LMApproximator(Graph graph, Weighting weighting, int maxBaseNodes, LandmarkStorage lms, int activeCount, double factor, boolean reverse) { this.reverse = reverse; this.lms = lms; this.factor = factor; if (activeCount > lms.getLandmarkCount()) throw new IllegalArgumentException("Active landmarks " + activeCount + " should be lower or equals to landmark count " + lms.getLandmarkCount()); activeLandmarkIndices = new int[activeCount]; Arrays.fill(activeLandmarkIndices, -1); weightsFromActiveLandmarksToT = new int[activeCount]; weightsFromTToActiveLandmarks = new int[activeCount]; this.graph = graph; this.weighting = weighting; this.fallBackApproximation = new BeelineWeightApproximator(graph.getNodeAccess(), weighting); this.maxBaseNodes = maxBaseNodes; } /** * Increase approximation with higher epsilon */ public LMApproximator setEpsilon(double epsilon) { this.epsilon = epsilon; return this; } @Override public double approximate(final int v) { if (!recalculateActiveLandmarks && fallback || lms.isEmpty()) return fallBackApproximation.approximate(v); if (v >= maxBaseNodes) { // handle virtual node return 0; } if (v == towerNodeNextToT) return 0; // select better active landmarks, LATER: use 'success' statistics about last active landmark // we have to update the priority queues and the maps if done in the middle of the search http://cstheory.stackexchange.com/q/36355/13229 if (recalculateActiveLandmarks) { recalculateActiveLandmarks = false; if (lms.chooseActiveLandmarks(v, towerNodeNextToT, activeLandmarkIndices, reverse)) { for (int i = 0; i < activeLandmarkIndices.length; i++) { weightsFromActiveLandmarksToT[i] = lms.getFromWeight(activeLandmarkIndices[i], towerNodeNextToT); weightsFromTToActiveLandmarks[i] = lms.getToWeight(activeLandmarkIndices[i], towerNodeNextToT); } } else { // note: fallback==true means forever true! fallback = true; return fallBackApproximation.approximate(v); } } return Math.max(0.0, (getRemainingWeightUnderestimationUpToTowerNode(v) - weightFromTToTowerNode) * epsilon); } private double getRemainingWeightUnderestimationUpToTowerNode(int v) { int maxWeightInt = 0; for (int i = 0; i < activeLandmarkIndices.length; i++) { int resultInt = approximateForLandmark(i, v); maxWeightInt = Math.max(maxWeightInt, resultInt); } // Round down, we need to be an underestimator. return (maxWeightInt - 1) * factor; } private int approximateForLandmark(int i, int v) { // ---> means shortest path, d means length of shortest path // but remember that d(v,t) != d(t,v) // // Suppose we are at v, want to go to t, and are looking at a landmark LM, // preferably behind t. // // ---> t --> // v ---------> LM // // We know distances from everywhere to LM. From the triangle inequality for shortest-path distances we get: // I) d(v,t) + d(t,LM) >= d(v,LM), so d(v,t) >= d(v,LM) - d(t,LM) // // Now suppose LM is behind us: // // ---> v --> // LM ---------> t // // We also know distances from LM to everywhere, so we get: // II) d(LM,v) + d(v,t) >= d(LM,t), so d(v,t) >= d(LM,t) - d(LM,v) // // Both equations hold in the general case, so we just pick the tighter approximation. // (The other one will probably be negative.) // // Note that when routing backwards we want to approximate d(t,v), not d(v,t). // When we flip all the arrows in the two figures, we get // III) d(t,v) + d(LM,t) >= d(LM,v), so d(t,v) >= d(LM,v) - d(LM,t) // IV) d(v,LM) + d(t,v) >= d(t,LM), so d(t,v) >= d(t,LM) - d(v,LM) // // ...and we can get the right-hand sides of III) and IV) by multiplying those of II) and I) by -1. int rhs1Int = lms.getToWeight(activeLandmarkIndices[i], v) - weightsFromTToActiveLandmarks[i]; int rhs2Int = weightsFromActiveLandmarksToT[i] - lms.getFromWeight(activeLandmarkIndices[i], v); if (reverse) { rhs1Int *= -1; rhs2Int *= -1; } return Math.max(rhs1Int, rhs2Int); } @Override public void setTo(int t) { this.fallBackApproximation.setTo(t); findClosestRealNode(t); } private void findClosestRealNode(int t) { Dijkstra dijkstra = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED) { @Override protected boolean finished() { towerNodeNextToT = currEdge.adjNode; weightFromTToTowerNode = currEdge.weight; return currEdge.adjNode < maxBaseNodes; } // We only expect a very short search @Override protected void initCollections(int size) { super.initCollections(2); } }; dijkstra.calcPath(t, -1); } @Override public WeightApproximator reverse() { return new LMApproximator(graph, weighting, maxBaseNodes, lms, activeLandmarkIndices.length, factor, !reverse); } @Override public double getSlack() { return lms.getFactor(); } /** * This method forces a lazy recalculation of the active landmark set e.g. necessary after the 'to' node changed. */ public void triggerActiveLandmarkRecalculation() { recalculateActiveLandmarks = true; } @Override public String toString() { return "landmarks"; } }
core/src/main/java/com/graphhopper/routing/lm/LMApproximator.java
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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 com.graphhopper.routing.lm; import com.graphhopper.routing.Dijkstra; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.BeelineWeightApproximator; import com.graphhopper.routing.weighting.WeightApproximator; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; import java.util.Arrays; /** * This class is a weight approximation based on precalculated landmarks. * * @author Peter Karich */ public class LMApproximator implements WeightApproximator { private final LandmarkStorage lms; private final Weighting weighting; private int[] activeLandmarkIndices; private int[] weightsFromActiveLandmarksToT; private int[] weightsFromTToActiveLandmarks; private double epsilon = 1; private int towerNodeNextToT = -1; private double weightFromTToTowerNode; private boolean recalculateActiveLandmarks = true; private final double factor; private final boolean reverse; private final int maxBaseNodes; private final Graph graph; private final WeightApproximator fallBackApproximation; private boolean fallback = false; public static LMApproximator forLandmarks(Graph g, LandmarkStorage lms, int activeLM) { return new LMApproximator(g, lms.getWeighting(), lms.getBaseNodes(), lms, activeLM, lms.getFactor(), false); } public LMApproximator(Graph graph, Weighting weighting, int maxBaseNodes, LandmarkStorage lms, int activeCount, double factor, boolean reverse) { this.reverse = reverse; this.lms = lms; this.factor = factor; if (activeCount > lms.getLandmarkCount()) throw new IllegalArgumentException("Active landmarks " + activeCount + " should be lower or equals to landmark count " + lms.getLandmarkCount()); activeLandmarkIndices = new int[activeCount]; Arrays.fill(activeLandmarkIndices, -1); weightsFromActiveLandmarksToT = new int[activeCount]; weightsFromTToActiveLandmarks = new int[activeCount]; this.graph = graph; this.weighting = weighting; this.fallBackApproximation = new BeelineWeightApproximator(graph.getNodeAccess(), weighting); this.maxBaseNodes = maxBaseNodes; } /** * Increase approximation with higher epsilon */ public LMApproximator setEpsilon(double epsilon) { this.epsilon = epsilon; return this; } @Override public double approximate(final int v) { if (!recalculateActiveLandmarks && fallback || lms.isEmpty()) return fallBackApproximation.approximate(v); if (v >= maxBaseNodes) { // handle virtual node return 0; } if (v == towerNodeNextToT) return 0; // select better active landmarks, LATER: use 'success' statistics about last active landmark // we have to update the priority queues and the maps if done in the middle of the search http://cstheory.stackexchange.com/q/36355/13229 if (recalculateActiveLandmarks) { recalculateActiveLandmarks = false; if (lms.chooseActiveLandmarks(v, towerNodeNextToT, activeLandmarkIndices, reverse)) { for (int i = 0; i < activeLandmarkIndices.length; i++) { weightsFromActiveLandmarksToT[i] = lms.getFromWeight(activeLandmarkIndices[i], towerNodeNextToT); weightsFromTToActiveLandmarks[i] = lms.getToWeight(activeLandmarkIndices[i], towerNodeNextToT); } } else { // note: fallback==true means forever true! fallback = true; return fallBackApproximation.approximate(v); } } return Math.max(0.0, (getRemainingWeightUnderestimationUpToTowerNode(v) - weightFromTToTowerNode) * epsilon); } private double getRemainingWeightUnderestimationUpToTowerNode(int v) { int maxWeightInt = 0; for (int i = 0; i < activeLandmarkIndices.length; i++) { int resultInt = approximateForLandmark(i, v); maxWeightInt = Math.max(maxWeightInt, resultInt); } // Round down, we need to be an underestimator. return (maxWeightInt - 1) * factor; } private int approximateForLandmark(int i, int v) { // ---> means shortest path, d means length of shortest path // but remember that d(v,t) != d(t,v) // // Suppose we are at v, want to go to t, and are looking at a landmark LM, // preferably behind t. // // ---> t --> // v ---------> LM // // We know distances from everywhere to LM. From the triangle inequality for shortest-path distances we get: // I) d(v,t) + d(t,LM) >= d(v,LM), so d(v,t) >= d(v,LM) - d(t,LM) // // Now suppose LM is behind us: // // ---> v --> // LM ---------> t // // We also know distances from LM to everywhere, so we get: // II) d(LM,v) + d(v,t) >= d(LM,t), so d(v,t) >= d(LM,t) - d(LM,v) // // Both equations hold in the general case, so we just pick the tighter approximation. // (The other one will probably be negative.) // // Note that when routing backwards we want to approximate d(t,v), not d(v,t). // When we flip all the arrows in the two figures, we get // III) d(t,v) + d(LM,t) >= d(LM,v), so d(t,v) >= d(LM,v) - d(LM,t) // IV) d(v,LM) + d(t,v) >= d(t,LM), so d(t,v) >= d(t,LM) - d(v,LM) // // ...and we can get the right-hand sides of III) and IV) by multiplying those of II) and I) by -1. int rhs1Int = weightsFromActiveLandmarksToT[i] - lms.getFromWeight(activeLandmarkIndices[i], v); int rhs2Int = lms.getToWeight(activeLandmarkIndices[i], v) - weightsFromTToActiveLandmarks[i]; int resultInt; if (reverse) { resultInt = Math.max(-rhs2Int, -rhs1Int); } else { resultInt = Math.max(rhs1Int, rhs2Int); } return resultInt; } @Override public void setTo(int t) { this.fallBackApproximation.setTo(t); findClosestRealNode(t); } private void findClosestRealNode(int t) { Dijkstra dijkstra = new Dijkstra(graph, weighting, TraversalMode.NODE_BASED) { @Override protected boolean finished() { towerNodeNextToT = currEdge.adjNode; weightFromTToTowerNode = currEdge.weight; return currEdge.adjNode < maxBaseNodes; } // We only expect a very short search @Override protected void initCollections(int size) { super.initCollections(2); } }; dijkstra.calcPath(t, -1); } @Override public WeightApproximator reverse() { return new LMApproximator(graph, weighting, maxBaseNodes, lms, activeLandmarkIndices.length, factor, !reverse); } @Override public double getSlack() { return lms.getFactor(); } /** * This method forces a lazy recalculation of the active landmark set e.g. necessary after the 'to' node changed. */ public void triggerActiveLandmarkRecalculation() { recalculateActiveLandmarks = true; } @Override public String toString() { return "landmarks"; } }
LMApproximator: Align variable names with equation numbers
core/src/main/java/com/graphhopper/routing/lm/LMApproximator.java
LMApproximator: Align variable names with equation numbers
<ide><path>ore/src/main/java/com/graphhopper/routing/lm/LMApproximator.java <ide> // <ide> // ...and we can get the right-hand sides of III) and IV) by multiplying those of II) and I) by -1. <ide> <del> int rhs1Int = weightsFromActiveLandmarksToT[i] - lms.getFromWeight(activeLandmarkIndices[i], v); <del> int rhs2Int = lms.getToWeight(activeLandmarkIndices[i], v) - weightsFromTToActiveLandmarks[i]; <del> <del> int resultInt; <add> int rhs1Int = lms.getToWeight(activeLandmarkIndices[i], v) - weightsFromTToActiveLandmarks[i]; <add> int rhs2Int = weightsFromActiveLandmarksToT[i] - lms.getFromWeight(activeLandmarkIndices[i], v); <add> <ide> if (reverse) { <del> resultInt = Math.max(-rhs2Int, -rhs1Int); <del> } else { <del> resultInt = Math.max(rhs1Int, rhs2Int); <del> } <del> return resultInt; <add> rhs1Int *= -1; <add> rhs2Int *= -1; <add> } <add> return Math.max(rhs1Int, rhs2Int); <ide> } <ide> <ide> @Override
Java
apache-2.0
45bf79c06df1e5aac18fe0aa7363a53dd396fac0
0
apache/xml-graphics-commons,apache/xml-graphics-commons,apache/xml-graphics-commons
/* * 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. */ /* $Id$ */ package org.apache.xmlgraphics.ps; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.Map; /** * This class defines the basic resources (procsets) used by the Apache XML Graphics project. * * @version $Id$ */ public final class PSProcSets { /** the standard procset for the XML Graphics project */ public static final PSResource STD_PROCSET; /** the EPS procset for the XML Graphics project */ public static final PSResource EPS_PROCSET = new EPSProcSet(); /** the standard command map matching the {@link #STD_PROCSET}. */ public static final PSCommandMap STD_COMMAND_MAP; static { StdProcSet stdProcSet = new StdProcSet(); STD_PROCSET = stdProcSet; STD_COMMAND_MAP = stdProcSet; } /** * The standard procset used by XML Graphics Commons. */ private static class StdProcSet extends PSProcSet implements PSCommandMap { /** A Map<String, String> of standard shorthand macros defined in the {@link StdProcSet}. */ private static final Map STANDARD_MACROS; static { Map macros = new java.util.HashMap(); macros.put("moveto", "M"); macros.put("rmoveto", "RM"); macros.put("curveto", "C"); macros.put("lineto", "L"); macros.put("show", "t"); macros.put("ashow", "A"); macros.put("closepath", "cp"); macros.put("setrgbcolor", "RC"); macros.put("setgray", "GC"); macros.put("setcmykcolor", "CC"); macros.put("newpath", "N"); macros.put("setmiterlimit", "ML"); macros.put("setlinewidth", "LC"); macros.put("setlinewidth", "LW"); macros.put("setlinejoin", "LJ"); macros.put("grestore", "GR"); macros.put("gsave", "GS"); macros.put("fill", "f"); macros.put("stroke", "S"); macros.put("concat", "CT"); STANDARD_MACROS = Collections.unmodifiableMap(macros); } public StdProcSet() { super("Apache XML Graphics Std ProcSet", 1.1f, 0); } public void writeTo(PSGenerator gen) throws IOException { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, new Object[] {TYPE_PROCSET, getName(), Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.VERSION, new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2001-2003,2010 " + "The Apache Software Foundation. " + "License terms: http://www.apache.org/licenses/LICENSE-2.0"); gen.writeDSCComment(DSCConstants.TITLE, "Basic set of procedures used by the XML Graphics project (Batik and FOP)"); gen.writeln("/bd{bind def}bind def"); gen.writeln("/ld{load def}bd"); Iterator iter = STANDARD_MACROS.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); gen.writeln("/" + entry.getValue() + "/" + entry.getKey()+" ld"); } gen.writeln("/re {4 2 roll M"); //define rectangle gen.writeln("1 index 0 rlineto"); gen.writeln("0 exch rlineto"); gen.writeln("neg 0 rlineto"); gen.writeln("cp } bd"); gen.writeln("/_ctm matrix def"); //Holds the current matrix gen.writeln("/_tm matrix def"); //BT: save currentmatrix, set _tm to identitymatrix and move to 0/0 gen.writeln("/BT { _ctm currentmatrix pop matrix _tm copy pop 0 0 moveto } bd"); //ET: restore last currentmatrix gen.writeln("/ET { _ctm setmatrix } bd"); gen.writeln("/iTm { _ctm setmatrix _tm concat } bd"); gen.writeln("/Tm { _tm astore pop iTm 0 0 moveto } bd"); gen.writeln("/ux 0.0 def"); gen.writeln("/uy 0.0 def"); // <font> <size> F gen.writeln("/F {"); gen.writeln(" /Tp exch def"); // gen.writeln(" currentdict exch get"); gen.writeln(" /Tf exch def"); gen.writeln(" Tf findfont Tp scalefont setfont"); gen.writeln(" /cf Tf def /cs Tp def /cw ( ) stringwidth pop def"); gen.writeln("} bd"); gen.writeln("/ULS {currentpoint /uy exch def /ux exch def} bd"); gen.writeln("/ULE {"); gen.writeln(" /Tcx currentpoint pop def"); gen.writeln(" gsave"); gen.writeln(" newpath"); gen.writeln(" cf findfont cs scalefont dup"); gen.writeln(" /FontMatrix get 0 get /Ts exch def /FontInfo get dup"); gen.writeln(" /UnderlinePosition get Ts mul /To exch def"); gen.writeln(" /UnderlineThickness get Ts mul /Tt exch def"); gen.writeln(" ux uy To add moveto Tcx uy To add lineto"); gen.writeln(" Tt setlinewidth stroke"); gen.writeln(" grestore"); gen.writeln("} bd"); gen.writeln("/OLE {"); gen.writeln(" /Tcx currentpoint pop def"); gen.writeln(" gsave"); gen.writeln(" newpath"); gen.writeln(" cf findfont cs scalefont dup"); gen.writeln(" /FontMatrix get 0 get /Ts exch def /FontInfo get dup"); gen.writeln(" /UnderlinePosition get Ts mul /To exch def"); gen.writeln(" /UnderlineThickness get Ts mul /Tt exch def"); gen.writeln(" ux uy To add cs add moveto Tcx uy To add cs add lineto"); gen.writeln(" Tt setlinewidth stroke"); gen.writeln(" grestore"); gen.writeln("} bd"); gen.writeln("/SOE {"); gen.writeln(" /Tcx currentpoint pop def"); gen.writeln(" gsave"); gen.writeln(" newpath"); gen.writeln(" cf findfont cs scalefont dup"); gen.writeln(" /FontMatrix get 0 get /Ts exch def /FontInfo get dup"); gen.writeln(" /UnderlinePosition get Ts mul /To exch def"); gen.writeln(" /UnderlineThickness get Ts mul /Tt exch def"); gen.writeln(" ux uy To add cs 10 mul 26 idiv add moveto " + "Tcx uy To add cs 10 mul 26 idiv add lineto"); gen.writeln(" Tt setlinewidth stroke"); gen.writeln(" grestore"); gen.writeln("} bd"); gen.writeln("/QT {"); gen.writeln("/Y22 exch store"); gen.writeln("/X22 exch store"); gen.writeln("/Y21 exch store"); gen.writeln("/X21 exch store"); gen.writeln("currentpoint"); gen.writeln("/Y21 load 2 mul add 3 div exch"); gen.writeln("/X21 load 2 mul add 3 div exch"); gen.writeln("/X21 load 2 mul /X22 load add 3 div"); gen.writeln("/Y21 load 2 mul /Y22 load add 3 div"); gen.writeln("/X22 load /Y22 load curveto"); gen.writeln("} bd"); gen.writeln("/SSPD {"); gen.writeln("dup length /d exch dict def"); gen.writeln("{"); gen.writeln("/v exch def"); gen.writeln("/k exch def"); gen.writeln("currentpagedevice k known {"); gen.writeln("/cpdv currentpagedevice k get def"); gen.writeln("v cpdv ne {"); gen.writeln("/upd false def"); gen.writeln("/nullv v type /nulltype eq def"); gen.writeln("/nullcpdv cpdv type /nulltype eq def"); gen.writeln("nullv nullcpdv or"); gen.writeln("{"); gen.writeln("/upd true def"); gen.writeln("} {"); gen.writeln("/sametype v type cpdv type eq def"); gen.writeln("sametype {"); gen.writeln("v type /arraytype eq {"); gen.writeln("/vlen v length def"); gen.writeln("/cpdvlen cpdv length def"); gen.writeln("vlen cpdvlen eq {"); gen.writeln("0 1 vlen 1 sub {"); gen.writeln("/i exch def"); gen.writeln("/obj v i get def"); gen.writeln("/cpdobj cpdv i get def"); gen.writeln("obj cpdobj ne {"); gen.writeln("/upd true def"); gen.writeln("exit"); gen.writeln("} if"); gen.writeln("} for"); gen.writeln("} {"); gen.writeln("/upd true def"); gen.writeln("} ifelse"); gen.writeln("} {"); gen.writeln("v type /dicttype eq {"); gen.writeln("v {"); gen.writeln("/dv exch def"); gen.writeln("/dk exch def"); gen.writeln("/cpddv cpdv dk get def"); gen.writeln("dv cpddv ne {"); gen.writeln("/upd true def"); gen.writeln("exit"); gen.writeln("} if"); gen.writeln("} forall"); gen.writeln("} {"); gen.writeln("/upd true def"); gen.writeln("} ifelse"); gen.writeln("} ifelse"); gen.writeln("} if"); gen.writeln("} ifelse"); gen.writeln("upd true eq {"); gen.writeln("d k v put"); gen.writeln("} if"); gen.writeln("} if"); gen.writeln("} if"); gen.writeln("} forall"); gen.writeln("d length 0 gt {"); gen.writeln("d setpagedevice"); gen.writeln("} if"); gen.writeln("} bd"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(this); } /** {@inheritDoc} */ public String mapCommand(String command) { String mapped = (String)STANDARD_MACROS.get(command); return (mapped != null ? mapped : command); } } private static class EPSProcSet extends PSProcSet { public EPSProcSet() { super("Apache XML Graphics EPS ProcSet", 1.0f, 0); } public void writeTo(PSGenerator gen) throws IOException { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, new Object[] {TYPE_PROCSET, getName(), Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.VERSION, new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2002-2003 " + "The Apache Software Foundation. " + "License terms: http://www.apache.org/licenses/LICENSE-2.0"); gen.writeDSCComment(DSCConstants.TITLE, "EPS procedures used by the Apache XML Graphics project (Batik and FOP)"); gen.writeln("/BeginEPSF { %def"); gen.writeln("/b4_Inc_state save def % Save state for cleanup"); gen.writeln("/dict_count countdictstack def % Count objects on dict stack"); gen.writeln("/op_count count 1 sub def % Count objects on operand stack"); gen.writeln("userdict begin % Push userdict on dict stack"); gen.writeln("/showpage { } def % Redefine showpage, { } = null proc"); gen.writeln("0 setgray 0 setlinecap % Prepare graphics state"); gen.writeln("1 setlinewidth 0 setlinejoin"); gen.writeln("10 setmiterlimit [ ] 0 setdash newpath"); gen.writeln("/languagelevel where % If level not equal to 1 then"); gen.writeln("{pop languagelevel % set strokeadjust and"); gen.writeln("1 ne % overprint to their defaults."); gen.writeln("{false setstrokeadjust false setoverprint"); gen.writeln("} if"); gen.writeln("} if"); gen.writeln("} bd"); gen.writeln("/EndEPSF { %def"); gen.writeln("count op_count sub {pop} repeat % Clean up stacks"); gen.writeln("countdictstack dict_count sub {end} repeat"); gen.writeln("b4_Inc_state restore"); gen.writeln("} bd"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(this); } } /** * Generates a resource defining standard procset with operations used by the XML Graphics * project. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem */ public static void writeStdProcSet(PSGenerator gen) throws IOException { ((StdProcSet)STD_PROCSET).writeTo(gen); } /** * Generates a resource defining standard procset with operations used by the XML Graphics * project. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem * @deprecated Use writeStdProcSet() instead. */ public static void writeFOPStdProcSet(PSGenerator gen) throws IOException { writeStdProcSet(gen); } /** * Generates a resource defining a procset for including EPS graphics. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem */ public static void writeEPSProcSet(PSGenerator gen) throws IOException { ((EPSProcSet)EPS_PROCSET).writeTo(gen); } /** * Generates a resource defining a procset for including EPS graphics. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem * @deprecated Use writeEPSProcSet() instead. */ public static void writeFOPEPSProcSet(PSGenerator gen) throws IOException { writeEPSProcSet(gen); } }
src/java/org/apache/xmlgraphics/ps/PSProcSets.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. */ /* $Id$ */ package org.apache.xmlgraphics.ps; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.Map; /** * This class defines the basic resources (procsets) used by the Apache XML Graphics project. * * @version $Id$ */ public final class PSProcSets { /** the standard procset for the XML Graphics project */ public static final PSResource STD_PROCSET; /** the EPS procset for the XML Graphics project */ public static final PSResource EPS_PROCSET = new EPSProcSet(); /** the standard command map matching the {@link #STD_PROCSET}. */ public static final PSCommandMap STD_COMMAND_MAP; static { StdProcSet stdProcSet = new StdProcSet(); STD_PROCSET = stdProcSet; STD_COMMAND_MAP = stdProcSet; } /** * The standard procset used by XML Graphics Commons. */ private static class StdProcSet extends PSProcSet implements PSCommandMap { /** A Map<String, String> of standard shorthand macros defined in the {@link StdProcSet}. */ private static final Map STANDARD_MACROS; static { Map macros = new java.util.HashMap(); macros.put("moveto", "M"); macros.put("rmoveto", "RM"); macros.put("curveto", "C"); macros.put("lineto", "L"); macros.put("show", "t"); macros.put("ashow", "A"); macros.put("closepath", "cp"); macros.put("setrgbcolor", "RC"); macros.put("setgray", "GC"); macros.put("setcmykcolor", "CC"); macros.put("newpath", "N"); macros.put("setmiterlimit", "ML"); macros.put("setlinewidth", "LC"); macros.put("setlinewidth", "LW"); macros.put("setlinejoin", "LJ"); macros.put("grestore", "GR"); macros.put("gsave", "GS"); macros.put("fill", "f"); macros.put("stroke", "S"); macros.put("concat", "CT"); STANDARD_MACROS = Collections.unmodifiableMap(macros); } public StdProcSet() { super("Apache XML Graphics Std ProcSet", 1.1f, 0); } public void writeTo(PSGenerator gen) throws IOException { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, new Object[] {TYPE_PROCSET, getName(), Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.VERSION, new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2001-2003,2010 " + "The Apache Software Foundation. " + "License terms: http://www.apache.org/licenses/LICENSE-2.0"); gen.writeDSCComment(DSCConstants.TITLE, "Basic set of procedures used by the XML Graphics project (Batik and FOP)"); gen.writeln("/bd{bind def}bind def"); gen.writeln("/ld{load def}bd"); Iterator iter = STANDARD_MACROS.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); gen.writeln("/" + entry.getValue() + "/" + entry.getKey()+" ld"); } gen.writeln("/re {4 2 roll M"); //define rectangle gen.writeln("1 index 0 rlineto"); gen.writeln("0 exch rlineto"); gen.writeln("neg 0 rlineto"); gen.writeln("cp } bd"); gen.writeln("/_ctm matrix def"); //Holds the current matrix gen.writeln("/_tm matrix def"); //BT: save currentmatrix, set _tm to identitymatrix and move to 0/0 gen.writeln("/BT { _ctm currentmatrix pop matrix _tm copy pop 0 0 moveto } bd"); //ET: restore last currentmatrix gen.writeln("/ET { _ctm setmatrix } bd"); gen.writeln("/iTm { _ctm setmatrix _tm concat } bd"); gen.writeln("/Tm { _tm astore pop iTm 0 0 moveto } bd"); gen.writeln("/ux 0.0 def"); gen.writeln("/uy 0.0 def"); // <font> <size> F gen.writeln("/F {"); gen.writeln(" /Tp exch def"); // gen.writeln(" currentdict exch get"); gen.writeln(" /Tf exch def"); gen.writeln(" Tf findfont Tp scalefont setfont"); gen.writeln(" /cf Tf def /cs Tp def"); gen.writeln(" /cf Tf def /cs Tp def /cw ( ) stringwidth pop def"); gen.writeln("} bd"); gen.writeln("/ULS {currentpoint /uy exch def /ux exch def} bd"); gen.writeln("/ULE {"); gen.writeln(" /Tcx currentpoint pop def"); gen.writeln(" gsave"); gen.writeln(" newpath"); gen.writeln(" cf findfont cs scalefont dup"); gen.writeln(" /FontMatrix get 0 get /Ts exch def /FontInfo get dup"); gen.writeln(" /UnderlinePosition get Ts mul /To exch def"); gen.writeln(" /UnderlineThickness get Ts mul /Tt exch def"); gen.writeln(" ux uy To add moveto Tcx uy To add lineto"); gen.writeln(" Tt setlinewidth stroke"); gen.writeln(" grestore"); gen.writeln("} bd"); gen.writeln("/OLE {"); gen.writeln(" /Tcx currentpoint pop def"); gen.writeln(" gsave"); gen.writeln(" newpath"); gen.writeln(" cf findfont cs scalefont dup"); gen.writeln(" /FontMatrix get 0 get /Ts exch def /FontInfo get dup"); gen.writeln(" /UnderlinePosition get Ts mul /To exch def"); gen.writeln(" /UnderlineThickness get Ts mul /Tt exch def"); gen.writeln(" ux uy To add cs add moveto Tcx uy To add cs add lineto"); gen.writeln(" Tt setlinewidth stroke"); gen.writeln(" grestore"); gen.writeln("} bd"); gen.writeln("/SOE {"); gen.writeln(" /Tcx currentpoint pop def"); gen.writeln(" gsave"); gen.writeln(" newpath"); gen.writeln(" cf findfont cs scalefont dup"); gen.writeln(" /FontMatrix get 0 get /Ts exch def /FontInfo get dup"); gen.writeln(" /UnderlinePosition get Ts mul /To exch def"); gen.writeln(" /UnderlineThickness get Ts mul /Tt exch def"); gen.writeln(" ux uy To add cs 10 mul 26 idiv add moveto " + "Tcx uy To add cs 10 mul 26 idiv add lineto"); gen.writeln(" Tt setlinewidth stroke"); gen.writeln(" grestore"); gen.writeln("} bd"); gen.writeln("/QT {"); gen.writeln("/Y22 exch store"); gen.writeln("/X22 exch store"); gen.writeln("/Y21 exch store"); gen.writeln("/X21 exch store"); gen.writeln("currentpoint"); gen.writeln("/Y21 load 2 mul add 3 div exch"); gen.writeln("/X21 load 2 mul add 3 div exch"); gen.writeln("/X21 load 2 mul /X22 load add 3 div"); gen.writeln("/Y21 load 2 mul /Y22 load add 3 div"); gen.writeln("/X22 load /Y22 load curveto"); gen.writeln("} bd"); gen.writeln("/SSPD {"); gen.writeln("dup length /d exch dict def"); gen.writeln("{"); gen.writeln("/v exch def"); gen.writeln("/k exch def"); gen.writeln("currentpagedevice k known {"); gen.writeln("/cpdv currentpagedevice k get def"); gen.writeln("v cpdv ne {"); gen.writeln("/upd false def"); gen.writeln("/nullv v type /nulltype eq def"); gen.writeln("/nullcpdv cpdv type /nulltype eq def"); gen.writeln("nullv nullcpdv or"); gen.writeln("{"); gen.writeln("/upd true def"); gen.writeln("} {"); gen.writeln("/sametype v type cpdv type eq def"); gen.writeln("sametype {"); gen.writeln("v type /arraytype eq {"); gen.writeln("/vlen v length def"); gen.writeln("/cpdvlen cpdv length def"); gen.writeln("vlen cpdvlen eq {"); gen.writeln("0 1 vlen 1 sub {"); gen.writeln("/i exch def"); gen.writeln("/obj v i get def"); gen.writeln("/cpdobj cpdv i get def"); gen.writeln("obj cpdobj ne {"); gen.writeln("/upd true def"); gen.writeln("exit"); gen.writeln("} if"); gen.writeln("} for"); gen.writeln("} {"); gen.writeln("/upd true def"); gen.writeln("} ifelse"); gen.writeln("} {"); gen.writeln("v type /dicttype eq {"); gen.writeln("v {"); gen.writeln("/dv exch def"); gen.writeln("/dk exch def"); gen.writeln("/cpddv cpdv dk get def"); gen.writeln("dv cpddv ne {"); gen.writeln("/upd true def"); gen.writeln("exit"); gen.writeln("} if"); gen.writeln("} forall"); gen.writeln("} {"); gen.writeln("/upd true def"); gen.writeln("} ifelse"); gen.writeln("} ifelse"); gen.writeln("} if"); gen.writeln("} ifelse"); gen.writeln("upd true eq {"); gen.writeln("d k v put"); gen.writeln("} if"); gen.writeln("} if"); gen.writeln("} if"); gen.writeln("} forall"); gen.writeln("d length 0 gt {"); gen.writeln("d setpagedevice"); gen.writeln("} if"); gen.writeln("} bd"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(this); } /** {@inheritDoc} */ public String mapCommand(String command) { String mapped = (String)STANDARD_MACROS.get(command); return (mapped != null ? mapped : command); } } private static class EPSProcSet extends PSProcSet { public EPSProcSet() { super("Apache XML Graphics EPS ProcSet", 1.0f, 0); } public void writeTo(PSGenerator gen) throws IOException { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, new Object[] {TYPE_PROCSET, getName(), Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.VERSION, new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2002-2003 " + "The Apache Software Foundation. " + "License terms: http://www.apache.org/licenses/LICENSE-2.0"); gen.writeDSCComment(DSCConstants.TITLE, "EPS procedures used by the Apache XML Graphics project (Batik and FOP)"); gen.writeln("/BeginEPSF { %def"); gen.writeln("/b4_Inc_state save def % Save state for cleanup"); gen.writeln("/dict_count countdictstack def % Count objects on dict stack"); gen.writeln("/op_count count 1 sub def % Count objects on operand stack"); gen.writeln("userdict begin % Push userdict on dict stack"); gen.writeln("/showpage { } def % Redefine showpage, { } = null proc"); gen.writeln("0 setgray 0 setlinecap % Prepare graphics state"); gen.writeln("1 setlinewidth 0 setlinejoin"); gen.writeln("10 setmiterlimit [ ] 0 setdash newpath"); gen.writeln("/languagelevel where % If level not equal to 1 then"); gen.writeln("{pop languagelevel % set strokeadjust and"); gen.writeln("1 ne % overprint to their defaults."); gen.writeln("{false setstrokeadjust false setoverprint"); gen.writeln("} if"); gen.writeln("} if"); gen.writeln("} bd"); gen.writeln("/EndEPSF { %def"); gen.writeln("count op_count sub {pop} repeat % Clean up stacks"); gen.writeln("countdictstack dict_count sub {end} repeat"); gen.writeln("b4_Inc_state restore"); gen.writeln("} bd"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(this); } } /** * Generates a resource defining standard procset with operations used by the XML Graphics * project. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem */ public static void writeStdProcSet(PSGenerator gen) throws IOException { ((StdProcSet)STD_PROCSET).writeTo(gen); } /** * Generates a resource defining standard procset with operations used by the XML Graphics * project. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem * @deprecated Use writeStdProcSet() instead. */ public static void writeFOPStdProcSet(PSGenerator gen) throws IOException { writeStdProcSet(gen); } /** * Generates a resource defining a procset for including EPS graphics. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem */ public static void writeEPSProcSet(PSGenerator gen) throws IOException { ((EPSProcSet)EPS_PROCSET).writeTo(gen); } /** * Generates a resource defining a procset for including EPS graphics. * @param gen PSGenerator to use for output * @throws IOException In case of an I/O problem * @deprecated Use writeEPSProcSet() instead. */ public static void writeFOPEPSProcSet(PSGenerator gen) throws IOException { writeEPSProcSet(gen); } }
Reverted change accidentally introduced in rev. 953786 git-svn-id: c1447309447e562cc43d70ade9fe6c70ff9b4cec@953788 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/xmlgraphics/ps/PSProcSets.java
Reverted change accidentally introduced in rev. 953786
<ide><path>rc/java/org/apache/xmlgraphics/ps/PSProcSets.java <ide> // gen.writeln(" currentdict exch get"); <ide> gen.writeln(" /Tf exch def"); <ide> gen.writeln(" Tf findfont Tp scalefont setfont"); <del> gen.writeln(" /cf Tf def /cs Tp def"); <ide> gen.writeln(" /cf Tf def /cs Tp def /cw ( ) stringwidth pop def"); <ide> gen.writeln("} bd"); <ide>
Java
apache-2.0
374664b556b418c87c96d5001429caf3a3e7698c
0
smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto,smartnews/presto
/* * 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 io.trino.operator; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.units.DataSize; import io.trino.execution.TaskId; import io.trino.spi.TrinoException; import javax.annotation.concurrent.GuardedBy; import java.util.ArrayDeque; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.throwIfUnchecked; import static com.google.common.util.concurrent.Futures.nonCancellationPropagating; import static io.trino.spi.StandardErrorCode.REMOTE_TASK_FAILED; import static java.lang.Math.max; import static java.util.Objects.requireNonNull; public class StreamingExchangeClientBuffer implements ExchangeClientBuffer { private static final Logger log = Logger.get(StreamingExchangeClientBuffer.class); private final Executor executor; private final long bufferCapacityInBytes; @GuardedBy("this") private final Queue<Slice> bufferedPages = new ArrayDeque<>(); @GuardedBy("this") private volatile long bufferRetainedSizeInBytes; @GuardedBy("this") private volatile long maxBufferRetainedSizeInBytes; @GuardedBy("this") private volatile SettableFuture<Void> blocked = SettableFuture.create(); @GuardedBy("this") private final Set<TaskId> activeTasks = new HashSet<>(); @GuardedBy("this") private boolean noMoreTasks; @GuardedBy("this") private Throwable failure; @GuardedBy("this") private boolean closed; public StreamingExchangeClientBuffer(Executor executor, DataSize bufferCapacity) { this.executor = requireNonNull(executor, "executor is null"); this.bufferCapacityInBytes = requireNonNull(bufferCapacity, "bufferCapacity is null").toBytes(); } @Override public ListenableFuture<Void> isBlocked() { return nonCancellationPropagating(blocked); } @Override public synchronized Slice pollPage() { throwIfFailed(); if (closed) { return null; } Slice page = bufferedPages.poll(); if (page != null) { bufferRetainedSizeInBytes -= page.getRetainedSize(); checkState(bufferRetainedSizeInBytes >= 0, "unexpected bufferRetainedSizeInBytes: %s", bufferRetainedSizeInBytes); } // if buffer is empty block future calls if (bufferedPages.isEmpty() && !isFinished() && blocked.isDone()) { blocked = SettableFuture.create(); } return page; } @Override public synchronized void addTask(TaskId taskId) { if (closed) { return; } checkState(!noMoreTasks, "no more tasks are expected"); activeTasks.add(taskId); } @Override public void addPages(TaskId taskId, List<Slice> pages) { long pagesRetainedSizeInBytes = 0; for (Slice page : pages) { pagesRetainedSizeInBytes += page.getRetainedSize(); } synchronized (this) { if (closed) { return; } checkState(activeTasks.contains(taskId), "taskId is not active: %s", taskId); bufferedPages.addAll(pages); bufferRetainedSizeInBytes += pagesRetainedSizeInBytes; maxBufferRetainedSizeInBytes = max(maxBufferRetainedSizeInBytes, bufferRetainedSizeInBytes); unblockIfNecessary(blocked); } } @Override public synchronized void taskFinished(TaskId taskId) { if (closed) { return; } checkState(activeTasks.contains(taskId), "taskId not registered: %s", taskId); activeTasks.remove(taskId); if (noMoreTasks && activeTasks.isEmpty() && !blocked.isDone()) { unblockIfNecessary(blocked); } } @Override public synchronized void taskFailed(TaskId taskId, Throwable t) { if (closed) { return; } checkState(activeTasks.contains(taskId), "taskId not registered: %s", taskId); if (t instanceof TrinoException && REMOTE_TASK_FAILED.toErrorCode().equals(((TrinoException) t).getErrorCode())) { // This error indicates that a downstream task was trying to fetch results from an upstream task that is marked as failed // Instead of failing a downstream task let the coordinator handle and report the failure of an upstream task to ensure correct error reporting log.debug("Task failure discovered while fetching task results: %s", taskId); return; } failure = t; activeTasks.remove(taskId); unblockIfNecessary(blocked); } @Override public synchronized void noMoreTasks() { noMoreTasks = true; if (activeTasks.isEmpty() && !blocked.isDone()) { unblockIfNecessary(blocked); } } @Override public synchronized boolean isFinished() { return failure == null && noMoreTasks && activeTasks.isEmpty() && bufferedPages.isEmpty(); } @Override public synchronized boolean isFailed() { return failure != null; } @Override public long getRemainingCapacityInBytes() { return max(bufferCapacityInBytes - bufferRetainedSizeInBytes, 0); } @Override public long getRetainedSizeInBytes() { return bufferRetainedSizeInBytes; } @Override public long getMaxRetainedSizeInBytes() { return maxBufferRetainedSizeInBytes; } @Override public synchronized int getBufferedPageCount() { return bufferedPages.size(); } @Override public synchronized void close() { if (closed) { return; } bufferedPages.clear(); bufferRetainedSizeInBytes = 0; activeTasks.clear(); noMoreTasks = true; closed = true; unblockIfNecessary(blocked); } private void unblockIfNecessary(SettableFuture<Void> blocked) { if (!blocked.isDone()) { executor.execute(() -> blocked.set(null)); } } private synchronized void throwIfFailed() { if (failure != null) { throwIfUnchecked(failure); throw new RuntimeException(failure); } } }
core/trino-main/src/main/java/io/trino/operator/StreamingExchangeClientBuffer.java
/* * 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 io.trino.operator; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.airlift.slice.Slice; import io.airlift.units.DataSize; import io.trino.execution.TaskId; import io.trino.spi.TrinoException; import javax.annotation.concurrent.GuardedBy; import java.util.ArrayDeque; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.throwIfUnchecked; import static com.google.common.util.concurrent.Futures.nonCancellationPropagating; import static io.trino.spi.StandardErrorCode.REMOTE_TASK_FAILED; import static java.lang.Math.max; import static java.util.Objects.requireNonNull; public class StreamingExchangeClientBuffer implements ExchangeClientBuffer { private final Executor executor; private final long bufferCapacityInBytes; @GuardedBy("this") private final Queue<Slice> bufferedPages = new ArrayDeque<>(); @GuardedBy("this") private volatile long bufferRetainedSizeInBytes; @GuardedBy("this") private volatile long maxBufferRetainedSizeInBytes; @GuardedBy("this") private volatile SettableFuture<Void> blocked = SettableFuture.create(); @GuardedBy("this") private final Set<TaskId> activeTasks = new HashSet<>(); @GuardedBy("this") private boolean noMoreTasks; @GuardedBy("this") private Throwable failure; @GuardedBy("this") private boolean closed; public StreamingExchangeClientBuffer(Executor executor, DataSize bufferCapacity) { this.executor = requireNonNull(executor, "executor is null"); this.bufferCapacityInBytes = requireNonNull(bufferCapacity, "bufferCapacity is null").toBytes(); } @Override public ListenableFuture<Void> isBlocked() { return nonCancellationPropagating(blocked); } @Override public synchronized Slice pollPage() { throwIfFailed(); if (closed) { return null; } Slice page = bufferedPages.poll(); if (page != null) { bufferRetainedSizeInBytes -= page.getRetainedSize(); checkState(bufferRetainedSizeInBytes >= 0, "unexpected bufferRetainedSizeInBytes: %s", bufferRetainedSizeInBytes); } // if buffer is empty block future calls if (bufferedPages.isEmpty() && !isFinished() && blocked.isDone()) { blocked = SettableFuture.create(); } return page; } @Override public synchronized void addTask(TaskId taskId) { if (closed) { return; } checkState(!noMoreTasks, "no more tasks are expected"); activeTasks.add(taskId); } @Override public void addPages(TaskId taskId, List<Slice> pages) { long pagesRetainedSizeInBytes = 0; for (Slice page : pages) { pagesRetainedSizeInBytes += page.getRetainedSize(); } synchronized (this) { if (closed) { return; } checkState(activeTasks.contains(taskId), "taskId is not active: %s", taskId); bufferedPages.addAll(pages); bufferRetainedSizeInBytes += pagesRetainedSizeInBytes; maxBufferRetainedSizeInBytes = max(maxBufferRetainedSizeInBytes, bufferRetainedSizeInBytes); unblockIfNecessary(blocked); } } @Override public synchronized void taskFinished(TaskId taskId) { if (closed) { return; } checkState(activeTasks.contains(taskId), "taskId not registered: %s", taskId); activeTasks.remove(taskId); if (noMoreTasks && activeTasks.isEmpty() && !blocked.isDone()) { unblockIfNecessary(blocked); } } @Override public synchronized void taskFailed(TaskId taskId, Throwable t) { if (closed) { return; } checkState(activeTasks.contains(taskId), "taskId not registered: %s", taskId); if (t instanceof TrinoException && REMOTE_TASK_FAILED.toErrorCode().equals(((TrinoException) t).getErrorCode())) { // let coordinator handle this return; } failure = t; activeTasks.remove(taskId); unblockIfNecessary(blocked); } @Override public synchronized void noMoreTasks() { noMoreTasks = true; if (activeTasks.isEmpty() && !blocked.isDone()) { unblockIfNecessary(blocked); } } @Override public synchronized boolean isFinished() { return failure == null && noMoreTasks && activeTasks.isEmpty() && bufferedPages.isEmpty(); } @Override public synchronized boolean isFailed() { return failure != null; } @Override public long getRemainingCapacityInBytes() { return max(bufferCapacityInBytes - bufferRetainedSizeInBytes, 0); } @Override public long getRetainedSizeInBytes() { return bufferRetainedSizeInBytes; } @Override public long getMaxRetainedSizeInBytes() { return maxBufferRetainedSizeInBytes; } @Override public synchronized int getBufferedPageCount() { return bufferedPages.size(); } @Override public synchronized void close() { if (closed) { return; } bufferedPages.clear(); bufferRetainedSizeInBytes = 0; activeTasks.clear(); noMoreTasks = true; closed = true; unblockIfNecessary(blocked); } private void unblockIfNecessary(SettableFuture<Void> blocked) { if (!blocked.isDone()) { executor.execute(() -> blocked.set(null)); } } private synchronized void throwIfFailed() { if (failure != null) { throwIfUnchecked(failure); throw new RuntimeException(failure); } } }
And descriptive comment and log REMOTE_TASK_FAILED errors
core/trino-main/src/main/java/io/trino/operator/StreamingExchangeClientBuffer.java
And descriptive comment and log REMOTE_TASK_FAILED errors
<ide><path>ore/trino-main/src/main/java/io/trino/operator/StreamingExchangeClientBuffer.java <ide> <ide> import com.google.common.util.concurrent.ListenableFuture; <ide> import com.google.common.util.concurrent.SettableFuture; <add>import io.airlift.log.Logger; <ide> import io.airlift.slice.Slice; <ide> import io.airlift.units.DataSize; <ide> import io.trino.execution.TaskId; <ide> public class StreamingExchangeClientBuffer <ide> implements ExchangeClientBuffer <ide> { <add> private static final Logger log = Logger.get(StreamingExchangeClientBuffer.class); <add> <ide> private final Executor executor; <ide> private final long bufferCapacityInBytes; <ide> <ide> checkState(activeTasks.contains(taskId), "taskId not registered: %s", taskId); <ide> <ide> if (t instanceof TrinoException && REMOTE_TASK_FAILED.toErrorCode().equals(((TrinoException) t).getErrorCode())) { <del> // let coordinator handle this <add> // This error indicates that a downstream task was trying to fetch results from an upstream task that is marked as failed <add> // Instead of failing a downstream task let the coordinator handle and report the failure of an upstream task to ensure correct error reporting <add> log.debug("Task failure discovered while fetching task results: %s", taskId); <ide> return; <ide> } <ide>
Java
apache-2.0
8b3a9f11e8e96c7b28b545afa48bf4f966eda7a0
0
apereo/cas,apereo/cas,fogbeam/cas_mirror,pdrados/cas,pdrados/cas,pdrados/cas,rkorn86/cas,pdrados/cas,fogbeam/cas_mirror,pdrados/cas,rkorn86/cas,apereo/cas,rkorn86/cas,Jasig/cas,apereo/cas,fogbeam/cas_mirror,apereo/cas,Jasig/cas,fogbeam/cas_mirror,rkorn86/cas,apereo/cas,Jasig/cas,fogbeam/cas_mirror,Jasig/cas,apereo/cas,fogbeam/cas_mirror,pdrados/cas
package org.apereo.cas.services; import lombok.val; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; /** * This is {@link ServicesManagerTests}. * * @author Misagh Moayyed * @since 6.3.0 */ @Tag("RegisteredService") public class ServicesManagerTests { @Test public void verifyFindById() { val component = mock(ServicesManager.class); val service = mock(RegisteredService.class); when(component.findServiceBy(anyLong())).thenReturn(service); when(component.findServiceBy(anyLong(), any())).thenCallRealMethod(); assertNotNull(component.findServiceBy(1, RegisteredService.class)); } @Test public void verifyFindByName() { val component = mock(ServicesManager.class); when(component.findServiceByName(anyString())).thenReturn(null); when(component.findServiceByName(anyString(), any())).thenCallRealMethod(); assertNull(component.findServiceByName("test", BaseMockRegisteredService.class)); val service = mock(RegisteredService.class); when(component.findServiceByName(anyString())).thenReturn(service); assertNotNull(component.findServiceByName("test", RegisteredService.class)); } private abstract static class BaseMockRegisteredService implements RegisteredService { private static final long serialVersionUID = 5470970585502265482L; } }
api/cas-server-core-api-services/src/test/java/org/apereo/cas/services/ServicesManagerTests.java
package org.apereo.cas.services; import lombok.val; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.*; /** * This is {@link ServicesManagerTests}. * * @author Misagh Moayyed * @since 6.3.0 */ @Tag("RegisteredService") public class ServicesManagerTests { @Test public void verifyFindById() { val component = mock(ServicesManager.class); val service = mock(RegisteredService.class); when(component.findServiceBy(anyLong())).thenReturn(service); when(component.findServiceBy(anyLong(), any())).thenCallRealMethod(); assertNotNull(component.findServiceBy(1, RegisteredService.class)); } @Test public void verifyFindByName() { val component = mock(ServicesManager.class); when(component.findServiceByName(anyString())).thenReturn(null); when(component.findServiceByName(anyString(), any())).thenCallRealMethod(); assertNull(component.findServiceByName("test", BaseMockRegisteredService.class)); val service = mock(RegisteredService.class); when(component.findServiceByName(anyString())).thenReturn(service); assertNotNull(component.findServiceByName("test", RegisteredService.class)); } private abstract static class BaseMockRegisteredService implements RegisteredService { private static final long serialVersionUID = 5470970585502265482L; } }
fix styling issues
api/cas-server-core-api-services/src/test/java/org/apereo/cas/services/ServicesManagerTests.java
fix styling issues
<ide><path>pi/cas-server-core-api-services/src/test/java/org/apereo/cas/services/ServicesManagerTests.java <ide> <ide> import static org.junit.jupiter.api.Assertions.*; <ide> import static org.mockito.ArgumentMatchers.*; <del>import static org.mockito.Mockito.anyLong; <ide> import static org.mockito.Mockito.*; <ide> <ide> /**
Java
agpl-3.0
ae9caa9528bce66e77b1b7a4973815ea12bbf30e
0
axelor/axelor-business-suite,axelor/axelor-business-suite,ama-axelor/axelor-business-suite,axelor/axelor-business-suite,ama-axelor/axelor-business-suite,ama-axelor/axelor-business-suite
/* * Axelor Business Solutions * * Copyright (C) 2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package com.axelor.apps.prestashop.service.library; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.w3c.dom.Document; import org.xml.sax.SAXException; import wslite.json.JSONArray; import wslite.json.JSONException; import wslite.json.JSONObject; public class PSWebServiceClient { /** @var string Shop URL */ protected String url; /** @var string Authentification key */ protected String key; private final CloseableHttpClient httpclient; private CloseableHttpResponse response; private HashMap<String, Object> responseReturns; /** * PrestaShopWebservice constructor. <code> * * try * { * PSWebServiceClient ws = new PSWebServiceClient('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false); * // Now we have a webservice object to play with * } * catch (PrestaShopWebserviceException ex) * { * // Handle exception * } * * </code> * * @param url * Root URL for the shop * @param key * Authentification key * @param debug * Debug mode Activated (true) or deactivated (false) */ public PSWebServiceClient(String url, String key) { this.url = url; this.key = key; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(key, "")); this.httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } /** * Take the status code and throw an exception if the server didn't return 200 * or 201 code * * @param status_code * Status code of an HTTP return * @throws pswebservice.PrestaShopWebserviceException */ protected void checkStatusCode(int statusCode) throws PrestaShopWebserviceException { if(statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) return; throw new PrestaShopWebserviceException(String.format("An underlying call to the Prestashop API failed with status code %d (%s)", statusCode, HttpStatus.getStatusText(statusCode))); } protected String getResponseContent() { try { return readInputStreamAsString((InputStream) this.responseReturns.get("response")); } catch (IOException ex) { return ""; } } /** * Handles request to PrestaShop Webservice. Can throw exception. * * @param url * Resource name * @param request * @return array status_code, response * @throws pswebservice.PrestaShopWebserviceException */ protected HashMap<String, Object> executeRequest(HttpUriRequest request) throws PrestaShopWebserviceException { HashMap<String, Object> returns = new HashMap<>(); try { response = httpclient.execute(request); Header[] headers = response.getAllHeaders(); HttpEntity entity = response.getEntity(); returns.put("status_code", response.getStatusLine().getStatusCode()); returns.put("response", entity.getContent()); returns.put("header", headers); this.responseReturns = returns; } catch (IOException ex) { throw new PrestaShopWebserviceException("Bad HTTP response : " + ex.toString()); } return returns; } /** * Load XML from string. Can throw exception * * @param responseBody * @return parsedXml * @throws javax.xml.parsers.ParserConfigurationException * @throws org.xml.sax.SAXException * @throws java.io.IOException */ protected Document parseXML(InputStream responseBody) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // System.out.println(responseBody); return docBuilder.parse(responseBody); } /** * Add (POST) a resource * <p> * Unique parameter must take : <br> * <br> * 'resource' => Resource name<br> * 'postXml' => Full XML string to add resource<br> * <br> * * @param opt * @return xml response * @throws pswebservice.PrestaShopWebserviceException * @throws TransformerException */ @SuppressWarnings("deprecation") public Document add(Map<String, Object> opt) throws PrestaShopWebserviceException, TransformerException { if ((opt.containsKey("resource") && opt.containsKey("postXml")) || (opt.containsKey("url") && opt.containsKey("postXml"))) { String completeUrl; completeUrl = (opt.containsKey("resource") ? this.url + "/api/" + (String) opt.get("resource") : (String) opt.get("url")); String xml = (String) opt.get("postXml"); if (opt.containsKey("id_shop")) completeUrl += "&id_shop=" + (String) opt.get("id_shop"); if (opt.containsKey("id_group_shop")) completeUrl += "&id_group_shop=" + (String) opt.get("id_group_shop"); StringEntity entity = new StringEntity(xml, ContentType.create("text/xml", Consts.UTF_8)); // entity.setChunked(true); HttpPost httppost = new HttpPost(completeUrl); httppost.setEntity(entity); HashMap<String, Object> resoult = this.executeRequest(httppost); this.checkStatusCode((Integer) resoult.get("status_code")); try { String obj = IOUtils.toString((InputStream) resoult.get("response")); InputStream is = new ByteArrayInputStream(obj.trim().getBytes()); Document doc = this.parseXML(is); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { ex.printStackTrace(); throw new PrestaShopWebserviceException("Response XML Parse exception"); } } else { throw new PrestaShopWebserviceException("Bad parameters given"); } } /** * Retrieve (GET) a resource * <p> * Unique parameter must take : <br> * <br> * 'url' => Full URL for a GET request of Webservice (ex: * http://mystore.com/api/customers/1/)<br> * OR<br> * 'resource' => Resource name,<br> * 'id' => ID of a resource you want to get<br> * <br> * </p> * <code> * * try * { * PSWebServiceClient ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false); * HashMap<String,Object> opt = new HashMap(); * opt.put("resouce","orders"); * opt.put("id",1); * Document xml = ws->get(opt); * // Here in xml, a XMLElement object you can parse * catch (PrestaShopWebserviceException ex) * { * Handle exception * } * * </code> * * @param opt * Map representing resource to get. * @return Document response * @throws pswebservice.PrestaShopWebserviceException */ @SuppressWarnings("rawtypes") public Document get(Map<String, Object> opt) throws PrestaShopWebserviceException { String completeUrl; if (opt.containsKey("url")) { completeUrl = (String) opt.get("url"); } else if (opt.containsKey("resource")) { completeUrl = this.url + "/api/" + opt.get("resource"); if (opt.containsKey("id")) completeUrl += "/" + opt.get("id"); String[] params = new String[] { "filter", "display", "sort", "limit", "id_shop", "id_group_shop" }; for (String p : params) if (opt.containsKey(p)) try { Object param = opt.get(p); if (param instanceof HashMap) { Map xparams = (HashMap) param; Iterator it = xparams.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); completeUrl += "?" + p + "[" + pair.getKey() + "]=" + URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&"; it.remove(); // avoids a ConcurrentModificationException } } else { completeUrl += "?" + p + "=" + URLEncoder.encode((String) opt.get(p), "UTF-8") + "&"; } } catch (UnsupportedEncodingException ex) { throw new PrestaShopWebserviceException("URI encodin excepton: " + ex.toString()); } } else { throw new PrestaShopWebserviceException("Bad parameters given"); } HttpGet httpget = new HttpGet(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httpget); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity try { Document doc = this.parseXML((InputStream) resoult.get("response")); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { throw new PrestaShopWebserviceException("Response XML Parse exception: " + ex.toString()); } } @SuppressWarnings({ "rawtypes", "deprecation" }) public JSONObject getJson(Map<String, Object> opt) throws PrestaShopWebserviceException, JSONException { String completeUrl; boolean flag = false; if (opt.containsKey("url")) { completeUrl = (String) opt.get("url"); } else if (opt.containsKey("resource")) { completeUrl = this.url + "/api/" + opt.get("resource"); if (opt.containsKey("id")) completeUrl += "/" + opt.get("id"); String[] params = new String[] { "filter", "display", "sort", "limit", "id_shop", "id_group_shop" }; for (String p : params) if (opt.containsKey(p)) try { flag = true; Object param = opt.get(p); if (param instanceof HashMap) { Map xparams = (HashMap) param; Iterator it = xparams.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); completeUrl += "?" + p + "[" + pair.getKey() + "]=" + URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&"; it.remove(); // avoids a ConcurrentModificationException } } else { completeUrl += "?" + p + "=" + URLEncoder.encode((String) opt.get(p), "UTF-8") + "&"; } } catch (UnsupportedEncodingException ex) { throw new PrestaShopWebserviceException("URI encodin excepton: " + ex.toString()); } } else { throw new PrestaShopWebserviceException("Bad parameters given"); } if (flag) { completeUrl += "output_format=JSON"; } else { completeUrl += "?output_format=JSON"; } HttpGet httpget = new HttpGet(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httpget); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity try { String jsonStr = IOUtils.toString((InputStream) resoult.get("response")); JSONObject json = null; if (!jsonStr.equals("[]")) { json = new JSONObject(jsonStr); } response.close(); return json; } catch (IOException ex) { throw new PrestaShopWebserviceException("Response JSON Parse exception: " + ex.toString()); } } /** * Head method (HEAD) a resource * * @param opt * Map representing resource for head request. * @return XMLElement status_code, response */ public Map<String, String> head(Map<String, Object> opt) throws PrestaShopWebserviceException { String completeUrl; if (opt.containsKey("url")) { completeUrl = (String) opt.get("url"); } else if (opt.containsKey("resource")) { completeUrl = this.url + "/api/" + opt.get("resource"); if (opt.containsKey("id")) completeUrl += "/" + opt.get("id"); String[] params = new String[] { "filter", "display", "sort", "limit" }; for (String p : params) if (opt.containsKey("p")) try { completeUrl += "?" + p + "=" + URLEncoder.encode((String) opt.get(p), "UTF-8") + "&"; } catch (UnsupportedEncodingException ex) { throw new PrestaShopWebserviceException("URI encodin excepton: " + ex.toString()); } } else throw new PrestaShopWebserviceException("Bad parameters given"); HttpHead httphead = new HttpHead(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httphead); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity HashMap<String, String> headers = new HashMap<String, String>(); for (Header h : (Header[]) resoult.get("header")) { headers.put(h.getName(), h.getValue()); } return headers; } /** * Edit (PUT) a resource * <p> * Unique parameter must take : <br> * <br> * 'resource' => Resource name ,<br> * 'id' => ID of a resource you want to edit,<br> * 'putXml' => Modified XML string of a resource<br> * <br> * * @param opt * representing resource to edit. * @return * @throws TransformerException */ public Document edit(Map<String, Object> opt) throws PrestaShopWebserviceException, TransformerException { String xml = ""; String completeUrl; if (opt.containsKey("url")) completeUrl = (String) opt.get("url"); else if (((opt.containsKey("resource") && opt.containsKey("id")) || opt.containsKey("url")) && opt.containsKey("postXml")) { completeUrl = (opt.containsKey("url")) ? (String) opt.get("url") : this.url + "/api/" + opt.get("resource") + "/" + opt.get("id"); xml = (String) opt.get("postXml"); if (opt.containsKey("id_shop")) completeUrl += "&id_shop=" + opt.get("id_shop"); if (opt.containsKey("id_group_shop")) completeUrl += "&id_group_shop=" + opt.get("id_group_shop"); } else throw new PrestaShopWebserviceException("Bad parameters given"); StringEntity entity = new StringEntity(xml, ContentType.create("text/xml", Consts.UTF_8)); // entity.setChunked(true); HttpPut httpput = new HttpPut(completeUrl); httpput.setEntity(entity); HashMap<String, Object> resoult = this.executeRequest(httpput); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity try { Document doc = this.parseXML((InputStream) resoult.get("response")); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { throw new PrestaShopWebserviceException("Response XML Parse exception: " + ex.toString()); } } /** * Delete (DELETE) a resource. Unique parameter must take : <br> * <br> * 'resource' => Resource name<br> * 'id' => ID or array which contains IDs of a resource(s) you want to * delete<br> * <br> * * @param opt * representing resource to delete. * @return * @throws pswebservice.PrestaShopWebserviceException */ public boolean delete(Map<String, Object> opt) throws PrestaShopWebserviceException { String completeUrl = ""; if (opt.containsKey("url")) completeUrl = (String) opt.get("url"); else if (opt.containsKey("resource") && opt.containsKey("id")) // if (opt.get("id")) // completeUrl = this.url+"/api/"+opt.get("resource")+"/?id=[".implode(',', // $options['id'])+"]"; // else completeUrl = this.url + "/api/" + opt.get("resource") + "/" + opt.get("id"); if (opt.containsKey("id_shop")) completeUrl += "&id_shop=" + opt.get("id_shop"); if (opt.containsKey("id_group_shop")) completeUrl += "&id_group_shop=" + opt.get("id_group_shop"); HttpDelete httpdelete = new HttpDelete(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httpdelete); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity return true; } /** * * @param imgURL * @param productId * @return xml response * @throws pswebservice.PrestaShopWebserviceException * @throws java.net.MalformedURLException */ public Document addImg(String imgURL, Integer productId) throws PrestaShopWebserviceException, MalformedURLException, IOException { URL imgUrl = new URL(imgURL); InputStream is = imgUrl.openStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); String completeUrl = this.url + "/api/images/products/" + String.valueOf(productId); HttpPost httppost = new HttpPost(completeUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("image", new ByteArrayBody(buffer.toByteArray(), "upload.jpg")); HttpEntity entity = builder.build(); httppost.setEntity(entity); HashMap<String, Object> resoult = this.executeRequest(httppost); this.checkStatusCode((Integer) resoult.get("status_code")); try { Document doc = this.parseXML((InputStream) resoult.get("response")); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { throw new PrestaShopWebserviceException("Response XML Parse exception"); } } private String readInputStreamAsString(InputStream in) throws IOException { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while (result != -1) { byte b = (byte) result; buf.write(b); result = bis.read(); } String returns = buf.toString(); return returns; } public String DocumentToString(Document doc) throws TransformerException { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.METHOD, "xml"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc.getDocumentElement()); trans.transform(source, result); String xmlString = sw.toString(); return xmlString; } public List<Integer> fetchApiIds(String resources) throws PrestaShopWebserviceException, JSONException { new PSWebServiceClient(this.url, this.key); HashMap<String, Object> opt = new HashMap<String, Object>(); opt.put("resource", resources); JSONObject schema = this.getJson(opt); List<Integer> ids = new ArrayList<Integer>(); JSONArray jsonMainArr = schema.getJSONArray(resources); for (int i = 0; i < jsonMainArr.length(); i++) { JSONObject childJSONObject = jsonMainArr.getJSONObject(i); ids.add(childJSONObject.getInt("id")); } return ids; } }
axelor-prestashop/src/main/java/com/axelor/apps/prestashop/service/library/PSWebServiceClient.java
/* * Axelor Business Solutions * * Copyright (C) 2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package com.axelor.apps.prestashop.service.library; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.IOUtils; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.w3c.dom.Document; import org.xml.sax.SAXException; import wslite.json.JSONArray; import wslite.json.JSONException; import wslite.json.JSONObject; public class PSWebServiceClient { /** @var string Shop URL */ protected String url; /** @var string Authentification key */ protected String key; private final CloseableHttpClient httpclient; private CloseableHttpResponse response; private HashMap<String, Object> responseReturns; /** * PrestaShopWebservice constructor. <code> * * try * { * PSWebServiceClient ws = new PSWebServiceClient('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false); * // Now we have a webservice object to play with * } * catch (PrestaShopWebserviceException ex) * { * // Handle exception * } * * </code> * * @param url * Root URL for the shop * @param key * Authentification key * @param debug * Debug mode Activated (true) or deactivated (false) */ public PSWebServiceClient(String url, String key) { this.url = url; this.key = key; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(key, "")); this.httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } /** * Take the status code and throw an exception if the server didn't return 200 * or 201 code * * @param status_code * Status code of an HTTP return * @throws pswebservice.PrestaShopWebserviceException */ protected void checkStatusCode(int status_code) throws PrestaShopWebserviceException { String error_label = "This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s."; switch (status_code) { case 200: case 201: break; case 204: throw new PrestaShopWebserviceException(String.format(error_label, status_code, "No content"), this); case 400: throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Bad Request"), this); case 401: throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Unauthorized"), this); case 404: throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Not Found"), this); case 405: throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Method Not Allowed"), this); case 500: throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Internal Server Error"), this); default: throw new PrestaShopWebserviceException( "This call to PrestaShop Web Services returned an unexpected HTTP status of:" + status_code); } } protected String getResponseContent() { try { return readInputStreamAsString((InputStream) this.responseReturns.get("response")); } catch (IOException ex) { return ""; } } /** * Handles request to PrestaShop Webservice. Can throw exception. * * @param url * Resource name * @param request * @return array status_code, response * @throws pswebservice.PrestaShopWebserviceException */ protected HashMap<String, Object> executeRequest(HttpUriRequest request) throws PrestaShopWebserviceException { HashMap<String, Object> returns = new HashMap<>(); try { response = httpclient.execute(request); Header[] headers = response.getAllHeaders(); HttpEntity entity = response.getEntity(); returns.put("status_code", response.getStatusLine().getStatusCode()); returns.put("response", entity.getContent()); returns.put("header", headers); this.responseReturns = returns; } catch (IOException ex) { throw new PrestaShopWebserviceException("Bad HTTP response : " + ex.toString()); } return returns; } /** * Load XML from string. Can throw exception * * @param responseBody * @return parsedXml * @throws javax.xml.parsers.ParserConfigurationException * @throws org.xml.sax.SAXException * @throws java.io.IOException */ protected Document parseXML(InputStream responseBody) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // System.out.println(responseBody); return docBuilder.parse(responseBody); } /** * Add (POST) a resource * <p> * Unique parameter must take : <br> * <br> * 'resource' => Resource name<br> * 'postXml' => Full XML string to add resource<br> * <br> * * @param opt * @return xml response * @throws pswebservice.PrestaShopWebserviceException * @throws TransformerException */ @SuppressWarnings("deprecation") public Document add(Map<String, Object> opt) throws PrestaShopWebserviceException, TransformerException { if ((opt.containsKey("resource") && opt.containsKey("postXml")) || (opt.containsKey("url") && opt.containsKey("postXml"))) { String completeUrl; completeUrl = (opt.containsKey("resource") ? this.url + "/api/" + (String) opt.get("resource") : (String) opt.get("url")); String xml = (String) opt.get("postXml"); if (opt.containsKey("id_shop")) completeUrl += "&id_shop=" + (String) opt.get("id_shop"); if (opt.containsKey("id_group_shop")) completeUrl += "&id_group_shop=" + (String) opt.get("id_group_shop"); StringEntity entity = new StringEntity(xml, ContentType.create("text/xml", Consts.UTF_8)); // entity.setChunked(true); HttpPost httppost = new HttpPost(completeUrl); httppost.setEntity(entity); HashMap<String, Object> resoult = this.executeRequest(httppost); this.checkStatusCode((Integer) resoult.get("status_code")); try { String obj = IOUtils.toString((InputStream) resoult.get("response")); InputStream is = new ByteArrayInputStream(obj.trim().getBytes()); Document doc = this.parseXML(is); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { ex.printStackTrace(); throw new PrestaShopWebserviceException("Response XML Parse exception"); } } else { throw new PrestaShopWebserviceException("Bad parameters given"); } } /** * Retrieve (GET) a resource * <p> * Unique parameter must take : <br> * <br> * 'url' => Full URL for a GET request of Webservice (ex: * http://mystore.com/api/customers/1/)<br> * OR<br> * 'resource' => Resource name,<br> * 'id' => ID of a resource you want to get<br> * <br> * </p> * <code> * * try * { * PSWebServiceClient ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false); * HashMap<String,Object> opt = new HashMap(); * opt.put("resouce","orders"); * opt.put("id",1); * Document xml = ws->get(opt); * // Here in xml, a XMLElement object you can parse * catch (PrestaShopWebserviceException ex) * { * Handle exception * } * * </code> * * @param opt * Map representing resource to get. * @return Document response * @throws pswebservice.PrestaShopWebserviceException */ @SuppressWarnings("rawtypes") public Document get(Map<String, Object> opt) throws PrestaShopWebserviceException { String completeUrl; if (opt.containsKey("url")) { completeUrl = (String) opt.get("url"); } else if (opt.containsKey("resource")) { completeUrl = this.url + "/api/" + opt.get("resource"); if (opt.containsKey("id")) completeUrl += "/" + opt.get("id"); String[] params = new String[] { "filter", "display", "sort", "limit", "id_shop", "id_group_shop" }; for (String p : params) if (opt.containsKey(p)) try { Object param = opt.get(p); if (param instanceof HashMap) { Map xparams = (HashMap) param; Iterator it = xparams.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); completeUrl += "?" + p + "[" + pair.getKey() + "]=" + URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&"; it.remove(); // avoids a ConcurrentModificationException } } else { completeUrl += "?" + p + "=" + URLEncoder.encode((String) opt.get(p), "UTF-8") + "&"; } } catch (UnsupportedEncodingException ex) { throw new PrestaShopWebserviceException("URI encodin excepton: " + ex.toString()); } } else { throw new PrestaShopWebserviceException("Bad parameters given"); } HttpGet httpget = new HttpGet(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httpget); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity try { Document doc = this.parseXML((InputStream) resoult.get("response")); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { throw new PrestaShopWebserviceException("Response XML Parse exception: " + ex.toString()); } } @SuppressWarnings({ "rawtypes", "deprecation" }) public JSONObject getJson(Map<String, Object> opt) throws PrestaShopWebserviceException, JSONException { String completeUrl; boolean flag = false; if (opt.containsKey("url")) { completeUrl = (String) opt.get("url"); } else if (opt.containsKey("resource")) { completeUrl = this.url + "/api/" + opt.get("resource"); if (opt.containsKey("id")) completeUrl += "/" + opt.get("id"); String[] params = new String[] { "filter", "display", "sort", "limit", "id_shop", "id_group_shop" }; for (String p : params) if (opt.containsKey(p)) try { flag = true; Object param = opt.get(p); if (param instanceof HashMap) { Map xparams = (HashMap) param; Iterator it = xparams.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); completeUrl += "?" + p + "[" + pair.getKey() + "]=" + URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&"; it.remove(); // avoids a ConcurrentModificationException } } else { completeUrl += "?" + p + "=" + URLEncoder.encode((String) opt.get(p), "UTF-8") + "&"; } } catch (UnsupportedEncodingException ex) { throw new PrestaShopWebserviceException("URI encodin excepton: " + ex.toString()); } } else { throw new PrestaShopWebserviceException("Bad parameters given"); } if (flag) { completeUrl += "output_format=JSON"; } else { completeUrl += "?output_format=JSON"; } HttpGet httpget = new HttpGet(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httpget); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity try { String jsonStr = IOUtils.toString((InputStream) resoult.get("response")); JSONObject json = null; if (!jsonStr.equals("[]")) { json = new JSONObject(jsonStr); } response.close(); return json; } catch (IOException ex) { throw new PrestaShopWebserviceException("Response JSON Parse exception: " + ex.toString()); } } /** * Head method (HEAD) a resource * * @param opt * Map representing resource for head request. * @return XMLElement status_code, response */ public Map<String, String> head(Map<String, Object> opt) throws PrestaShopWebserviceException { String completeUrl; if (opt.containsKey("url")) { completeUrl = (String) opt.get("url"); } else if (opt.containsKey("resource")) { completeUrl = this.url + "/api/" + opt.get("resource"); if (opt.containsKey("id")) completeUrl += "/" + opt.get("id"); String[] params = new String[] { "filter", "display", "sort", "limit" }; for (String p : params) if (opt.containsKey("p")) try { completeUrl += "?" + p + "=" + URLEncoder.encode((String) opt.get(p), "UTF-8") + "&"; } catch (UnsupportedEncodingException ex) { throw new PrestaShopWebserviceException("URI encodin excepton: " + ex.toString()); } } else throw new PrestaShopWebserviceException("Bad parameters given"); HttpHead httphead = new HttpHead(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httphead); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity HashMap<String, String> headers = new HashMap<String, String>(); for (Header h : (Header[]) resoult.get("header")) { headers.put(h.getName(), h.getValue()); } return headers; } /** * Edit (PUT) a resource * <p> * Unique parameter must take : <br> * <br> * 'resource' => Resource name ,<br> * 'id' => ID of a resource you want to edit,<br> * 'putXml' => Modified XML string of a resource<br> * <br> * * @param opt * representing resource to edit. * @return * @throws TransformerException */ public Document edit(Map<String, Object> opt) throws PrestaShopWebserviceException, TransformerException { String xml = ""; String completeUrl; if (opt.containsKey("url")) completeUrl = (String) opt.get("url"); else if (((opt.containsKey("resource") && opt.containsKey("id")) || opt.containsKey("url")) && opt.containsKey("postXml")) { completeUrl = (opt.containsKey("url")) ? (String) opt.get("url") : this.url + "/api/" + opt.get("resource") + "/" + opt.get("id"); xml = (String) opt.get("postXml"); if (opt.containsKey("id_shop")) completeUrl += "&id_shop=" + opt.get("id_shop"); if (opt.containsKey("id_group_shop")) completeUrl += "&id_group_shop=" + opt.get("id_group_shop"); } else throw new PrestaShopWebserviceException("Bad parameters given"); StringEntity entity = new StringEntity(xml, ContentType.create("text/xml", Consts.UTF_8)); // entity.setChunked(true); HttpPut httpput = new HttpPut(completeUrl); httpput.setEntity(entity); HashMap<String, Object> resoult = this.executeRequest(httpput); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity try { Document doc = this.parseXML((InputStream) resoult.get("response")); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { throw new PrestaShopWebserviceException("Response XML Parse exception: " + ex.toString()); } } /** * Delete (DELETE) a resource. Unique parameter must take : <br> * <br> * 'resource' => Resource name<br> * 'id' => ID or array which contains IDs of a resource(s) you want to * delete<br> * <br> * * @param opt * representing resource to delete. * @return * @throws pswebservice.PrestaShopWebserviceException */ public boolean delete(Map<String, Object> opt) throws PrestaShopWebserviceException { String completeUrl = ""; if (opt.containsKey("url")) completeUrl = (String) opt.get("url"); else if (opt.containsKey("resource") && opt.containsKey("id")) // if (opt.get("id")) // completeUrl = this.url+"/api/"+opt.get("resource")+"/?id=[".implode(',', // $options['id'])+"]"; // else completeUrl = this.url + "/api/" + opt.get("resource") + "/" + opt.get("id"); if (opt.containsKey("id_shop")) completeUrl += "&id_shop=" + opt.get("id_shop"); if (opt.containsKey("id_group_shop")) completeUrl += "&id_group_shop=" + opt.get("id_group_shop"); HttpDelete httpdelete = new HttpDelete(completeUrl); HashMap<String, Object> resoult = this.executeRequest(httpdelete); this.checkStatusCode((int) resoult.get("status_code"));// check the response validity return true; } /** * * @param imgURL * @param productId * @return xml response * @throws pswebservice.PrestaShopWebserviceException * @throws java.net.MalformedURLException */ public Document addImg(String imgURL, Integer productId) throws PrestaShopWebserviceException, MalformedURLException, IOException { URL imgUrl = new URL(imgURL); InputStream is = imgUrl.openStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); String completeUrl = this.url + "/api/images/products/" + String.valueOf(productId); HttpPost httppost = new HttpPost(completeUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("image", new ByteArrayBody(buffer.toByteArray(), "upload.jpg")); HttpEntity entity = builder.build(); httppost.setEntity(entity); HashMap<String, Object> resoult = this.executeRequest(httppost); this.checkStatusCode((Integer) resoult.get("status_code")); try { Document doc = this.parseXML((InputStream) resoult.get("response")); response.close(); return doc; } catch (ParserConfigurationException | SAXException | IOException ex) { throw new PrestaShopWebserviceException("Response XML Parse exception"); } } private String readInputStreamAsString(InputStream in) throws IOException { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while (result != -1) { byte b = (byte) result; buf.write(b); result = bis.read(); } String returns = buf.toString(); return returns; } public String DocumentToString(Document doc) throws TransformerException { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.METHOD, "xml"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc.getDocumentElement()); trans.transform(source, result); String xmlString = sw.toString(); return xmlString; } public List<Integer> fetchApiIds(String resources) throws PrestaShopWebserviceException, JSONException { new PSWebServiceClient(this.url, this.key); HashMap<String, Object> opt = new HashMap<String, Object>(); opt.put("resource", resources); JSONObject schema = this.getJson(opt); List<Integer> ids = new ArrayList<Integer>(); JSONArray jsonMainArr = schema.getJSONArray(resources); for (int i = 0; i < jsonMainArr.length(); i++) { JSONObject childJSONObject = jsonMainArr.getJSONObject(i); ids.add(childJSONObject.getInt("id")); } return ids; } }
prestashop: enhance status code decoding
axelor-prestashop/src/main/java/com/axelor/apps/prestashop/service/library/PSWebServiceClient.java
prestashop: enhance status code decoding
<ide><path>xelor-prestashop/src/main/java/com/axelor/apps/prestashop/service/library/PSWebServiceClient.java <ide> import javax.xml.transform.dom.DOMSource; <ide> import javax.xml.transform.stream.StreamResult; <ide> <add>import org.apache.commons.httpclient.HttpStatus; <ide> import org.apache.commons.io.IOUtils; <ide> import org.apache.http.Consts; <ide> import org.apache.http.Header; <ide> * Status code of an HTTP return <ide> * @throws pswebservice.PrestaShopWebserviceException <ide> */ <del> protected void checkStatusCode(int status_code) throws PrestaShopWebserviceException { <del> <del> String error_label = "This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s."; <del> switch (status_code) { <del> case 200: <del> case 201: <del> break; <del> case 204: <del> throw new PrestaShopWebserviceException(String.format(error_label, status_code, "No content"), this); <del> case 400: <del> throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Bad Request"), this); <del> case 401: <del> throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Unauthorized"), this); <del> case 404: <del> throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Not Found"), this); <del> case 405: <del> throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Method Not Allowed"), <del> this); <del> case 500: <del> throw new PrestaShopWebserviceException(String.format(error_label, status_code, "Internal Server Error"), <del> this); <del> default: <del> throw new PrestaShopWebserviceException( <del> "This call to PrestaShop Web Services returned an unexpected HTTP status of:" + status_code); <del> } <add> protected void checkStatusCode(int statusCode) throws PrestaShopWebserviceException { <add> if(statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) return; <add> throw new PrestaShopWebserviceException(String.format("An underlying call to the Prestashop API failed with status code %d (%s)", statusCode, HttpStatus.getStatusText(statusCode))); <ide> } <ide> <ide> protected String getResponseContent() {
JavaScript
mit
faeabbfdbaf95e060949235f6b333efcc7b90be5
0
aeschylus/subunit,sghall/subunit,aeschylus/subunit,sghall/subunit
import { extend_selection } from "../core/extend_selection"; import { extend_enter } from "../core/extend_enter"; export function data(value, key) { var i = -1, n = this.length, group, node; if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; if (key) { var nodeByKeyValue = new Subunit_Map(), dataByKeyValue = new Subunit_Map(), keyValues = [], keyValue; for (i = -1; ++i < n;) { keyValue = key.call(node = group[i], node.__data__, i); if (nodeByKeyValue.has(keyValue)) { exitNodes[i] = node; // duplicate selection key } else { nodeByKeyValue.set(keyValue, node); } keyValues.push(keyValue); } for (i = -1; ++i < m;) { keyValue = key.call(groupData, nodeData = groupData[i], i); if (node = nodeByKeyValue.get(keyValue)) { updateNodes[i] = node; node.__data__ = nodeData; } else if (!dataByKeyValue.has(keyValue)) { // no duplicate data key enterNodes[i] = _selection_dataNode(nodeData); } dataByKeyValue.set(keyValue, nodeData); nodeByKeyValue.remove(keyValue); } for (i = -1; ++i < n;) { if (nodeByKeyValue.has(keyValues[i])) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0;) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; } else { enterNodes[i] = _selection_dataNode(nodeData); } } for (; i < m; ++i) { enterNodes[i] = _selection_dataNode(groupData[i]); } for (; i < n; ++i) { exitNodes[i] = group[i]; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var enter = extend_enter([]), update = extend_selection([]), exit = extend_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; } function subunit_class(ctor, properties) { try { for (var key in properties) { Object.defineProperty(ctor.prototype, key, { value: properties[key], enumerable: false }); } } catch (e) { ctor.prototype = properties; } } var subunit_map_prefix = "\0", subunit_map_prefixCode = subunit_map_prefix.charCodeAt(0); function subunit_map_has(key) { return subunit_map_prefix + key in this; } function subunit_map_remove(key) { key = subunit_map_prefix + key; return key in this && delete this[key]; } function subunit_map_keys() { var keys = []; this.forEach(function (key) { keys.push(key); }); return keys; } function subunit_map_size() { var size = 0; for (var key in this) { if (key.charCodeAt(0) === subunit_map_prefixCode) { ++size; } } return size; } function subunit_map_empty() { for (var key in this) { if (key.charCodeAt(0) === subunit_map_prefixCode) { return false; } } return true; } function Subunit_Map() {} subunit_class(Subunit_Map, { has: subunit_map_has, get: function(key) { return this[subunit_map_prefix + key]; }, set: function(key, value) { return this[subunit_map_prefix + key] = value; }, remove: subunit_map_remove, keys: subunit_map_keys, values: function() { var values = []; this.forEach(function (key, value) { values.push(value); }); return values; }, entries: function() { var entries = []; this.forEach(function (key, value) { entries.push({key: key, value: value}); }); return entries; }, size: subunit_map_size, empty: subunit_map_empty, forEach: function(f) { for (var key in this) { if (key.charCodeAt(0) === subunit_map_prefixCode) { f.call(this, key.substring(1), this[key]); } } } }); function _selection_dataNode(data) { var store = {}; store.__data__ = data; store.__class__ = []; return store; }
src/methods/data.js
import { extend_selection } from "../core/extend_selection"; import { extend_enter } from "../core/extend_enter"; export function data(value, key) { var i = -1, n = this.length, group, node; if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; if (key) { var nodeByKeyValue = new Che_Map(), dataByKeyValue = new Che_Map(), keyValues = [], keyValue; for (i = -1; ++i < n;) { keyValue = key.call(node = group[i], node.__data__, i); if (nodeByKeyValue.has(keyValue)) { exitNodes[i] = node; // duplicate selection key } else { nodeByKeyValue.set(keyValue, node); } keyValues.push(keyValue); } for (i = -1; ++i < m;) { keyValue = key.call(groupData, nodeData = groupData[i], i); if (node = nodeByKeyValue.get(keyValue)) { updateNodes[i] = node; node.__data__ = nodeData; } else if (!dataByKeyValue.has(keyValue)) { // no duplicate data key enterNodes[i] = _selection_dataNode(nodeData); } dataByKeyValue.set(keyValue, nodeData); nodeByKeyValue.remove(keyValue); } for (i = -1; ++i < n;) { if (nodeByKeyValue.has(keyValues[i])) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0;) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; } else { enterNodes[i] = _selection_dataNode(nodeData); } } for (; i < m; ++i) { enterNodes[i] = _selection_dataNode(groupData[i]); } for (; i < n; ++i) { exitNodes[i] = group[i]; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var enter = extend_enter([]), update = extend_selection([]), exit = extend_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; } function subunit_class(ctor, properties) { try { for (var key in properties) { Object.defineProperty(ctor.prototype, key, { value: properties[key], enumerable: false }); } } catch (e) { ctor.prototype = properties; } } var subunit_map_prefix = "\0", subunit_map_prefixCode = subunit_map_prefix.charCodeAt(0); function subunit_map_has(key) { return subunit_map_prefix + key in this; } function subunit_map_remove(key) { key = subunit_map_prefix + key; return key in this && delete this[key]; } function subunit_map_keys() { var keys = []; this.forEach(function (key) { keys.push(key); }); return keys; } function subunit_map_size() { var size = 0; for (var key in this) { if (key.charCodeAt(0) === subunit_map_prefixCode) { ++size; } } return size; } function subunit_map_empty() { for (var key in this) { if (key.charCodeAt(0) === subunit_map_prefixCode) { return false; } } return true; } function Che_Map() {} subunit_class(Che_Map, { has: subunit_map_has, get: function(key) { return this[subunit_map_prefix + key]; }, set: function(key, value) { return this[subunit_map_prefix + key] = value; }, remove: subunit_map_remove, keys: subunit_map_keys, values: function() { var values = []; this.forEach(function (key, value) { values.push(value); }); return values; }, entries: function() { var entries = []; this.forEach(function (key, value) { entries.push({key: key, value: value}); }); return entries; }, size: subunit_map_size, empty: subunit_map_empty, forEach: function(f) { for (var key in this) { if (key.charCodeAt(0) === subunit_map_prefixCode) { f.call(this, key.substring(1), this[key]); } } } }); function _selection_dataNode(data) { var store = {}; store.__data__ = data; store.__class__ = []; return store; }
rename map function
src/methods/data.js
rename map function
<ide><path>rc/methods/data.js <ide> nodeData; <ide> <ide> if (key) { <del> var nodeByKeyValue = new Che_Map(), <del> dataByKeyValue = new Che_Map(), <add> var nodeByKeyValue = new Subunit_Map(), <add> dataByKeyValue = new Subunit_Map(), <ide> keyValues = [], keyValue; <ide> <ide> for (i = -1; ++i < n;) { <ide> return true; <ide> } <ide> <del>function Che_Map() {} <add>function Subunit_Map() {} <ide> <del>subunit_class(Che_Map, { <add>subunit_class(Subunit_Map, { <ide> has: subunit_map_has, <ide> get: function(key) { <ide> return this[subunit_map_prefix + key];
Java
apache-2.0
8960414fd1f1ecd222b5239c4237e15789c452ef
0
burmanm/hawkular-metrics,burmanm/hawkular-metrics,burmanm/hawkular-metrics,hawkular/hawkular-metrics,pilhuhn/rhq-metrics,mwringe/hawkular-metrics,jotak/hawkular-metrics,hawkular/hawkular-metrics,jotak/hawkular-metrics,ppalaga/hawkular-metrics,pilhuhn/rhq-metrics,pilhuhn/rhq-metrics,tsegismont/hawkular-metrics,hawkular/hawkular-metrics,spadgett/hawkular-metrics,pilhuhn/rhq-metrics,mwringe/hawkular-metrics,spadgett/hawkular-metrics,tsegismont/hawkular-metrics,tsegismont/hawkular-metrics,ppalaga/hawkular-metrics,ppalaga/hawkular-metrics,tsegismont/hawkular-metrics,mwringe/hawkular-metrics,jotak/hawkular-metrics,burmanm/hawkular-metrics,spadgett/hawkular-metrics,mwringe/hawkular-metrics,spadgett/hawkular-metrics,hawkular/hawkular-metrics,spadgett/hawkular-metrics,jotak/hawkular-metrics,ppalaga/hawkular-metrics
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.metrics.api.jaxrs.handler; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static org.hawkular.metrics.api.jaxrs.filter.TenantFilter.TENANT_HEADER_NAME; import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.emptyPayload; import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.requestToCounterDataPoints; import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.requestToCounters; import static org.hawkular.metrics.core.api.MetricType.COUNTER; import java.net.URI; import java.util.List; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import org.hawkular.metrics.api.jaxrs.ApiError; import org.hawkular.metrics.api.jaxrs.handler.observer.MetricCreatedObserver; import org.hawkular.metrics.api.jaxrs.handler.observer.ResultSetObserver; import org.hawkular.metrics.api.jaxrs.model.Counter; import org.hawkular.metrics.api.jaxrs.model.CounterDataPoint; import org.hawkular.metrics.api.jaxrs.request.MetricDefinition; import org.hawkular.metrics.api.jaxrs.util.ApiUtils; import org.hawkular.metrics.core.api.Metric; import org.hawkular.metrics.core.api.MetricId; import org.hawkular.metrics.core.api.MetricsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; /** * @author Stefan Negrea * */ @Path("/counters") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @Api(value = "", description = "Counter metrics interface. A counter is a metric whose value are monotonically " + "increasing or decreasing.") public class CounterHandler { private static Logger logger = LoggerFactory.getLogger(CounterHandler.class); private static final long EIGHT_HOURS = MILLISECONDS.convert(8, HOURS); @Inject private MetricsService metricsService; @HeaderParam(TENANT_HEADER_NAME) private String tenantId; @POST @Path("/") @ApiOperation( value = "Create counter metric definition. This operation also causes the rate to be calculated and " + "persisted periodically after raw count data is persisted.", notes = "Clients are not required to explicitly create a metric before storing data. Doing so however " + "allows clients to prevent naming collisions and to specify tags and data retention.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Metric definition created successfully"), @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), @ApiResponse(code = 409, message = "Counter metric with given id already exists", response = ApiError.class), @ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error", response = ApiError.class) }) public void createCounter ( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo) { if (metricDefinition == null) { asyncResponse.resume(emptyPayload()); return; } Metric<Double> metric = new Metric<>(tenantId, COUNTER, new MetricId(metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/counters/{id}").build(metric.getId().getName()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); } @GET @Path("/{id}") @ApiOperation(value = "Retrieve a counter definition", response = MetricDefinition.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's definition was successfully retrieved."), @ApiResponse(code = 204, message = "Query was successful, but no metrics definition is set."), @ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's definition.", response = ApiError.class) }) public void getCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id) { metricsService.findMetric(tenantId, COUNTER, new MetricId(id)) .map(MetricDefinition::new) .map(metricDef -> Response.ok(metricDef).build()) .switchIfEmpty(Observable.just(ApiUtils.noContent())) .subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t))); } @POST @Path("/data") @ApiOperation(value = "Add data points for multiple counters") @ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data points succeeded."), @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), @ApiResponse(code = 500, message = "Unexpected error happened while storing the data points", response = ApiError.class) }) public void addData(@Suspended final AsyncResponse asyncResponse, @ApiParam(value = "List of metrics", required = true) List<Counter> counters) { if (counters.isEmpty()) { asyncResponse.resume(emptyPayload()); } else { Observable<Metric<Long>> metrics = requestToCounters(tenantId, counters); Observable<Void> observable = metricsService.addCounterData((metrics)); observable.subscribe(new ResultSetObserver(asyncResponse)); } } @POST @Path("/{id}/data") @ApiOperation(value = "Add data for a single counter") @ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data succeeded."), @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), @ApiResponse(code = 500, message = "Unexpected error happened while storing the data", response = ApiError.class), }) public void addData( @Suspended final AsyncResponse asyncResponse, @PathParam("id") String id, @ApiParam(value = "List of data points containing timestamp and value", required = true) List<CounterDataPoint> data) { if (data.isEmpty()) { asyncResponse.resume(emptyPayload()); } else { Metric<Long> metric = new Metric<>(tenantId, COUNTER, new MetricId(id), requestToCounterDataPoints(data)); Observable<Void> observable = metricsService.addCounterData(Observable.just(metric)); observable.subscribe(new ResultSetObserver(asyncResponse)); } } @GET @Path("/{id}/data") @ApiOperation(value = "Retrieve counter data points.", response = List.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully fetched metric data."), @ApiResponse(code = 204, message = "No metric data was found."), @ApiResponse(code = 400, message = "start or end parameter is invalid.", response = ApiError.class), @ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.", response = ApiError.class) }) public void findCounterData( @Suspended AsyncResponse asyncResponse, @PathParam("id") String id, @ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") final Long start, @ApiParam(value = "Defaults to now") @QueryParam("end") final Long end) { long now = System.currentTimeMillis(); long startTime = start == null ? now - EIGHT_HOURS : start; long endTime = end == null ? now : end; metricsService.findCounterData(tenantId, new MetricId(id), startTime, endTime) .map(CounterDataPoint::new) .toList() .map(ApiUtils::collectionToResponse) .subscribe( asyncResponse::resume, t -> { logger.warn("Failed to fetch counter data", t); ApiUtils.serverError(t); }); } }
api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.metrics.api.jaxrs.handler; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static org.hawkular.metrics.api.jaxrs.filter.TenantFilter.TENANT_HEADER_NAME; import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.emptyPayload; import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.requestToCounterDataPoints; import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.requestToCounters; import static org.hawkular.metrics.core.api.MetricType.COUNTER; import java.net.URI; import java.util.List; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import org.hawkular.metrics.api.jaxrs.ApiError; import org.hawkular.metrics.api.jaxrs.handler.observer.MetricCreatedObserver; import org.hawkular.metrics.api.jaxrs.handler.observer.ResultSetObserver; import org.hawkular.metrics.api.jaxrs.model.Counter; import org.hawkular.metrics.api.jaxrs.model.CounterDataPoint; import org.hawkular.metrics.api.jaxrs.request.MetricDefinition; import org.hawkular.metrics.api.jaxrs.util.ApiUtils; import org.hawkular.metrics.core.api.Metric; import org.hawkular.metrics.core.api.MetricId; import org.hawkular.metrics.core.api.MetricsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; /** * @author Stefan Negrea * */ @Path("/counters") @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @Api(value = "", description = "Counter metrics interface. A counter is a metric whose value are monotonically " + "increasing or decreasing.") public class CounterHandler { private static Logger logger = LoggerFactory.getLogger(CounterHandler.class); private static final long EIGHT_HOURS = MILLISECONDS.convert(8, HOURS); @Inject private MetricsService metricsService; @HeaderParam(TENANT_HEADER_NAME) private String tenantId; @POST @Path("/") @ApiOperation( value = "Create counter metric definition. This operation also causes the rate to be calculated and " + "persisted periodically after raw count data is persisted.", notes = "Clients are not required to explicitly create a metric before storing data. Doing so however " + "allows clients to prevent naming collisions and to specify tags and data retention.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Metric definition created successfully"), @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), @ApiResponse(code = 409, message = "Counter metric with given id already exists", response = ApiError.class), @ApiResponse(code = 500, message = "Metric definition creation failed due to an unexpected error", response = ApiError.class) }) public void createCounter ( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo) { if (metricDefinition == null) { asyncResponse.resume(emptyPayload()); return; } Metric<Double> metric = new Metric<>(tenantId, COUNTER, new MetricId(metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); URI location = uriInfo.getBaseUriBuilder().path("/counters/{id}").build(metric.getId().getName()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); } @GET @Path("/{id}") @ApiOperation(value = "Retrieve a counter definition", response = MetricDefinition.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Metric's definition was successfully retrieved."), @ApiResponse(code = 204, message = "Query was successful, but no metrics definition is set."), @ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's definition.", response = ApiError.class) }) public void getCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id) { metricsService.findMetric(tenantId, COUNTER, new MetricId(id)) .map(MetricDefinition::new) .map(metricDef -> Response.ok(metricDef).build()) .switchIfEmpty(Observable.just(ApiUtils.noContent())) .subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t))); } @POST @Path("/data") @ApiOperation(value = "Add data points for multiple counters") @ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data points succeeded."), @ApiResponse(code = 500, message = "Unexpected error happened while storing the data points", response = ApiError.class) }) public void addData(@Suspended final AsyncResponse asyncResponse, @ApiParam(value = "List of metrics", required = true) List<Counter> counters) { if (counters.isEmpty()) { asyncResponse.resume(emptyPayload()); } else { Observable<Metric<Long>> metrics = requestToCounters(tenantId, counters); Observable<Void> observable = metricsService.addCounterData((metrics)); observable.subscribe(new ResultSetObserver(asyncResponse)); } } @POST @Path("/{id}/data") @ApiOperation(value = "Add data for a single counter") @ApiResponses(value = { @ApiResponse(code = 200, message = "Adding data succeeded."), @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), @ApiResponse(code = 500, message = "Unexpected error happened while storing the data", response = ApiError.class), }) public void addData( @Suspended final AsyncResponse asyncResponse, @PathParam("id") String id, @ApiParam(value = "List of data points containing timestamp and value", required = true) List<CounterDataPoint> data) { if (data.isEmpty()) { asyncResponse.resume(emptyPayload()); } else { Metric<Long> metric = new Metric<>(tenantId, COUNTER, new MetricId(id), requestToCounterDataPoints(data)); Observable<Void> observable = metricsService.addCounterData(Observable.just(metric)); observable.subscribe(new ResultSetObserver(asyncResponse)); } } @GET @Path("/{id}/data") @ApiOperation(value = "Retrieve counter data points.", response = List.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully fetched metric data."), @ApiResponse(code = 204, message = "No metric data was found."), @ApiResponse(code = 400, message = "start or end parameter is invalid.", response = ApiError.class), @ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.", response = ApiError.class) }) public void findCounterData( @Suspended AsyncResponse asyncResponse, @PathParam("id") String id, @ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") final Long start, @ApiParam(value = "Defaults to now") @QueryParam("end") final Long end) { long now = System.currentTimeMillis(); long startTime = start == null ? now - EIGHT_HOURS : start; long endTime = end == null ? now : end; metricsService.findCounterData(tenantId, new MetricId(id), startTime, endTime) .map(CounterDataPoint::new) .toList() .map(ApiUtils::collectionToResponse) .subscribe( asyncResponse::resume, t -> { logger.warn("Failed to fetch counter data", t); ApiUtils.serverError(t); }); } }
[HWKMETRICS-152] document missing payload
api/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java
[HWKMETRICS-152] document missing payload
<ide><path>pi/metrics-api-jaxrs/src/main/java/org/hawkular/metrics/api/jaxrs/handler/CounterHandler.java <ide> @ApiOperation(value = "Add data points for multiple counters") <ide> @ApiResponses(value = { <ide> @ApiResponse(code = 200, message = "Adding data points succeeded."), <add> @ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class), <ide> @ApiResponse(code = 500, message = "Unexpected error happened while storing the data points", <ide> response = ApiError.class) }) <ide> public void addData(@Suspended final AsyncResponse asyncResponse,
Java
apache-2.0
a7d4473ca5eaaeb2c2a2b3a34d7d4529830d3e39
0
griddynamics/xml-dom-kettle-etl-plugin,fsolovyev/xml-dom-kettle-etl-plugin
package org.pentaho.di.core.row.value; import static org.junit.Assert.*; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import org.junit.Test; import org.pentaho.di.DOMTestUtilities; import org.pentaho.di.core.exception.KettleValueException; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class ValueMetaDomTest { private static final String SAMPLE_XML_STRING = "<some><xml>text</xml></some>"; @Test public void testGetString() throws ParserConfigurationException, SAXException, IOException, KettleValueException, XPathExpressionException { ValueMetaDom vmd = new ValueMetaDom(); Document doc = DOMTestUtilities.createTestDocument(SAMPLE_XML_STRING); String xmlString = vmd.getString(doc); assertNull(DOMTestUtilities.validateXPath(xmlString, new String[]{"/some/xml/text()[1]='text'"})); } }
test/org/pentaho/di/core/row/value/ValueMetaDomTest.java
package org.pentaho.di.core.row.value; import static org.junit.Assert.*; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import org.junit.Test; import org.pentaho.di.DOMTestUtilities; import org.pentaho.di.core.exception.KettleValueException; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class ValueMetaDomTest { @Test public void testGetString() throws ParserConfigurationException, SAXException, IOException, KettleValueException, XPathExpressionException { ValueMetaDom vmd = new ValueMetaDom(); Document doc = DOMTestUtilities.createTestDocument("<some><xml>text</xml></some>"); String xmlString = vmd.getString(doc); assertNull(DOMTestUtilities.validateXPath(xmlString, new String[]{"/some/xml/text()[1]='text'"})); } }
Extracted constant
test/org/pentaho/di/core/row/value/ValueMetaDomTest.java
Extracted constant
<ide><path>est/org/pentaho/di/core/row/value/ValueMetaDomTest.java <ide> <ide> public class ValueMetaDomTest { <ide> <add> private static final String SAMPLE_XML_STRING = "<some><xml>text</xml></some>"; <add> <ide> @Test <ide> public void testGetString() throws ParserConfigurationException, SAXException, IOException, KettleValueException, XPathExpressionException { <ide> ValueMetaDom vmd = new ValueMetaDom(); <del> Document doc = DOMTestUtilities.createTestDocument("<some><xml>text</xml></some>"); <add> Document doc = DOMTestUtilities.createTestDocument(SAMPLE_XML_STRING); <ide> String xmlString = vmd.getString(doc); <ide> assertNull(DOMTestUtilities.validateXPath(xmlString, new String[]{"/some/xml/text()[1]='text'"})); <ide> }
Java
apache-2.0
1db0ead540e292a6028eff8792205c98c870af81
0
neykov/incubator-brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,andreaturli/legacy-brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn
package brooklyn.management.internal; import static com.google.common.base.Preconditions.checkNotNull; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import brooklyn.catalog.BrooklynCatalog; import brooklyn.config.BrooklynProperties; import brooklyn.config.StringConfigMap; import brooklyn.entity.Application; import brooklyn.entity.Effector; import brooklyn.entity.Entity; import brooklyn.entity.basic.AbstractEntity; import brooklyn.entity.drivers.EntityDriverManager; import brooklyn.entity.drivers.downloads.DownloadResolverManager; import brooklyn.entity.rebind.ChangeListener; import brooklyn.entity.rebind.RebindManager; import brooklyn.internal.storage.BrooklynStorage; import brooklyn.location.Location; import brooklyn.location.LocationRegistry; import brooklyn.management.AccessController; import brooklyn.management.EntityManager; import brooklyn.management.ExecutionContext; import brooklyn.management.ExecutionManager; import brooklyn.management.LocationManager; import brooklyn.management.SubscriptionContext; import brooklyn.management.Task; import brooklyn.mementos.BrooklynMemento; import brooklyn.mementos.BrooklynMementoPersister; import brooklyn.util.task.AbstractExecutionContext; public class NonDeploymentManagementContext implements ManagementContextInternal { public enum NonDeploymentManagementContextMode { PRE_MANAGEMENT, MANAGEMENT_REBINDING, MANAGEMENT_STARTING, MANAGEMENT_STARTED, MANAGEMENT_STOPPING, MANAGEMENT_STOPPED; public boolean isPreManaged() { return this == PRE_MANAGEMENT || this == MANAGEMENT_REBINDING; } } private final AbstractEntity entity; private NonDeploymentManagementContextMode mode; private ManagementContextInternal initialManagementContext; private final QueueingSubscriptionManager qsm; private final BasicSubscriptionContext subscriptionContext; private final NonDeploymentExecutionContext executionContext; private NonDeploymentEntityManager entityManager; private NonDeploymentLocationManager locationManager; private NonDeploymentAccessManager accessManager; private NonDeploymentUsageManager usageManager; public NonDeploymentManagementContext(AbstractEntity entity, NonDeploymentManagementContextMode mode) { this.entity = checkNotNull(entity, "entity"); this.mode = checkNotNull(mode, "mode"); qsm = new QueueingSubscriptionManager(); subscriptionContext = new BasicSubscriptionContext(qsm, entity); executionContext = new NonDeploymentExecutionContext(); entityManager = new NonDeploymentEntityManager(null); locationManager = new NonDeploymentLocationManager(null); accessManager = new NonDeploymentAccessManager(null); usageManager = new NonDeploymentUsageManager(null); } @Override public String getManagementPlaneId() { return null; } @Override public String getManagementNodeId() { return null; } public void setManagementContext(ManagementContextInternal val) { this.initialManagementContext = checkNotNull(val, "initialManagementContext"); this.entityManager = new NonDeploymentEntityManager(val); this.locationManager = new NonDeploymentLocationManager(val); this.accessManager = new NonDeploymentAccessManager(val); this.usageManager = new NonDeploymentUsageManager(val); } @Override public String toString() { return super.toString()+"["+entity+";"+mode+"]"; } public void setMode(NonDeploymentManagementContextMode mode) { this.mode = checkNotNull(mode, "mode"); } public NonDeploymentManagementContextMode getMode() { return mode; } @Override public Collection<Application> getApplications() { return Collections.emptyList(); } @Override public boolean isRunning() { // Assume that the real management context has not been terminated, so always true return true; } @Override public EntityManager getEntityManager() { return entityManager; } @Override public LocationManager getLocationManager() { return locationManager; } @Override public AccessManager getAccessManager() { return accessManager; } @Override public UsageManager getUsageManager() { return usageManager; } @Override public AccessController getAccessController() { return getAccessManager().getAccessController(); } @Override public ExecutionManager getExecutionManager() { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation: executions cannot be performed prior to management"); } @Override public QueueingSubscriptionManager getSubscriptionManager() { return qsm; } @Override public synchronized SubscriptionContext getSubscriptionContext(Entity entity) { if (!this.entity.equals(entity)) throw new IllegalStateException("Non-deployment context "+this+" can only use a single Entity: has "+this.entity+", but passed "+entity); return subscriptionContext; } @Override public ExecutionContext getExecutionContext(Entity entity) { if (!this.entity.equals(entity)) throw new IllegalStateException("Non-deployment context "+this+" can only use a single Entity: has "+this.entity+", but passed "+entity); return executionContext; } // TODO the methods below should delegate to the application? @Override public EntityDriverManager getEntityDriverManager() { checkInitialManagementContextReal(); return initialManagementContext.getEntityDriverManager(); } @Override public DownloadResolverManager getEntityDownloadsManager() { checkInitialManagementContextReal(); return initialManagementContext.getEntityDownloadsManager(); } @Override public StringConfigMap getConfig() { checkInitialManagementContextReal(); return initialManagementContext.getConfig(); } @Override public BrooklynProperties getBrooklynProperties() { checkInitialManagementContextReal(); return initialManagementContext.getBrooklynProperties(); } @Override public BrooklynStorage getStorage() { checkInitialManagementContextReal(); return initialManagementContext.getStorage(); } @Override public RebindManager getRebindManager() { // There was a race where EffectorUtils on invoking an effector calls: // mgmtSupport.getEntityChangeListener().onEffectorCompleted(eff); // but where the entity/app may be being unmanaged concurrently (e.g. calling app.stop()). // So now we allow the change-listener to be called. if (isInitialManagementContextReal()) { return initialManagementContext.getRebindManager(); } else { return new NonDeploymentRebindManager(); } } @Override public LocationRegistry getLocationRegistry() { checkInitialManagementContextReal(); return initialManagementContext.getLocationRegistry(); } @Override public BrooklynCatalog getCatalog() { checkInitialManagementContextReal(); return initialManagementContext.getCatalog(); } @Override public <T> T invokeEffectorMethodSync(final Entity entity, final Effector<T> eff, final Object args) throws ExecutionException { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation: cannot invoke effector "+eff+" on entity "+entity); } @Override public <T> Task<T> invokeEffector(final Entity entity, final Effector<T> eff, @SuppressWarnings("rawtypes") final Map parameters) { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation: cannot invoke effector "+eff+" on entity "+entity); } @Override public ClassLoader getBaseClassLoader() { checkInitialManagementContextReal(); return initialManagementContext.getBaseClassLoader(); } @Override public Iterable<URL> getBaseClassPathForScanning() { checkInitialManagementContextReal(); return initialManagementContext.getBaseClassPathForScanning(); } @Override public void addEntitySetListener(CollectionChangeListener<Entity> listener) { checkInitialManagementContextReal(); initialManagementContext.addEntitySetListener(listener); } @Override public void removeEntitySetListener(CollectionChangeListener<Entity> listener) { checkInitialManagementContextReal(); initialManagementContext.removeEntitySetListener(listener); } @Override public void terminate() { if (isInitialManagementContextReal()) { initialManagementContext.terminate(); } else { // no-op; the non-deployment management context has nothing needing terminated } } @Override public long getTotalEffectorInvocations() { if (isInitialManagementContextReal()) { return initialManagementContext.getTotalEffectorInvocations(); } else { return 0; } } @Override public void setBaseClassPathForScanning(Iterable<URL> urls) { checkInitialManagementContextReal(); initialManagementContext.setBaseClassPathForScanning(urls); } @Override public void prePreManage(Entity entity) { // no-op } @Override public void prePreManage(Location location) { // no-op } private boolean isInitialManagementContextReal() { return (initialManagementContext != null && !(initialManagementContext instanceof NonDeploymentManagementContext)); } private void checkInitialManagementContextReal() { if (!isInitialManagementContextReal()) { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation."); } } @Override public void reloadBrooklynProperties() { checkInitialManagementContextReal(); initialManagementContext.reloadBrooklynProperties(); } private class NonDeploymentExecutionContext extends AbstractExecutionContext { @Override public Set<Task<?>> getTasks() { return Collections.emptySet(); } @Override protected <T> Task<T> submitInternal(Map<?, ?> properties, Object task) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } } /** * For when the initial management context is not "real"; the changeListener is a no-op, but everything else forbidden. * * @author aled */ private class NonDeploymentRebindManager implements RebindManager { @Override public ChangeListener getChangeListener() { return ChangeListener.NOOP; } @Override public void setPersister(BrooklynMementoPersister persister) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public BrooklynMementoPersister getPersister() { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public List<Application> rebind(BrooklynMemento memento) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public List<Application> rebind(BrooklynMemento memento, ClassLoader classLoader) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public void stop() { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public void waitForPendingComplete(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } } }
core/src/main/java/brooklyn/management/internal/NonDeploymentManagementContext.java
package brooklyn.management.internal; import static com.google.common.base.Preconditions.checkNotNull; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import brooklyn.catalog.BrooklynCatalog; import brooklyn.config.BrooklynProperties; import brooklyn.config.StringConfigMap; import brooklyn.entity.Application; import brooklyn.entity.Effector; import brooklyn.entity.Entity; import brooklyn.entity.basic.AbstractEntity; import brooklyn.entity.drivers.EntityDriverManager; import brooklyn.entity.drivers.downloads.DownloadResolverManager; import brooklyn.entity.rebind.ChangeListener; import brooklyn.entity.rebind.RebindManager; import brooklyn.internal.storage.BrooklynStorage; import brooklyn.location.Location; import brooklyn.location.LocationRegistry; import brooklyn.management.AccessController; import brooklyn.management.EntityManager; import brooklyn.management.ExecutionContext; import brooklyn.management.ExecutionManager; import brooklyn.management.LocationManager; import brooklyn.management.SubscriptionContext; import brooklyn.management.Task; import brooklyn.mementos.BrooklynMemento; import brooklyn.mementos.BrooklynMementoPersister; import brooklyn.util.task.AbstractExecutionContext; public class NonDeploymentManagementContext implements ManagementContextInternal { public enum NonDeploymentManagementContextMode { PRE_MANAGEMENT, MANAGEMENT_REBINDING, MANAGEMENT_STARTING, MANAGEMENT_STARTED, MANAGEMENT_STOPPING, MANAGEMENT_STOPPED; public boolean isPreManaged() { return this == PRE_MANAGEMENT || this == MANAGEMENT_REBINDING; } } private final AbstractEntity entity; private NonDeploymentManagementContextMode mode; private ManagementContextInternal initialManagementContext; private final QueueingSubscriptionManager qsm; private final BasicSubscriptionContext subscriptionContext; private final NonDeploymentExecutionContext executionContext; private NonDeploymentEntityManager entityManager; private NonDeploymentLocationManager locationManager; private NonDeploymentAccessManager accessManager; private NonDeploymentUsageManager usageManager; public NonDeploymentManagementContext(AbstractEntity entity, NonDeploymentManagementContextMode mode) { this.entity = checkNotNull(entity, "entity"); this.mode = checkNotNull(mode, "mode"); qsm = new QueueingSubscriptionManager(); subscriptionContext = new BasicSubscriptionContext(qsm, entity); executionContext = new NonDeploymentExecutionContext(); entityManager = new NonDeploymentEntityManager(null); locationManager = new NonDeploymentLocationManager(null); accessManager = new NonDeploymentAccessManager(null); usageManager = new NonDeploymentUsageManager(null); } @Override public String getManagementPlaneId() { return null; } @Override public String getManagementNodeId() { return null; } public void setManagementContext(ManagementContextInternal val) { this.initialManagementContext = checkNotNull(val, "initialManagementContext"); this.entityManager = new NonDeploymentEntityManager(val); this.locationManager = new NonDeploymentLocationManager(val); this.accessManager = new NonDeploymentAccessManager(val); this.usageManager = new NonDeploymentUsageManager(val); } @Override public String toString() { return super.toString()+"["+entity+";"+mode+"]"; } public void setMode(NonDeploymentManagementContextMode mode) { this.mode = checkNotNull(mode, "mode"); } public NonDeploymentManagementContextMode getMode() { return mode; } @Override public Collection<Application> getApplications() { return Collections.emptyList(); } @Override public boolean isRunning() { // Assume that the real management context has not been terminated, so always true return true; } @Override public EntityManager getEntityManager() { return entityManager; } @Override public LocationManager getLocationManager() { return locationManager; } @Override public AccessManager getAccessManager() { return accessManager; } @Override public UsageManager getUsageManager() { return usageManager; } @Override public AccessController getAccessController() { return getAccessManager().getAccessController(); } @Override public ExecutionManager getExecutionManager() { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation: executions cannot be performed prior to management"); } @Override public QueueingSubscriptionManager getSubscriptionManager() { return qsm; } @Override public synchronized SubscriptionContext getSubscriptionContext(Entity entity) { if (!this.entity.equals(entity)) throw new IllegalStateException("Non-deployment context "+this+" can only use a single Entity: has "+this.entity+", but passed "+entity); return subscriptionContext; } @Override public ExecutionContext getExecutionContext(Entity entity) { if (!this.entity.equals(entity)) throw new IllegalStateException("Non-deployment context "+this+" can only use a single Entity: has "+this.entity+", but passed "+entity); return executionContext; } // TODO the methods below should delegate to the application? @Override public EntityDriverManager getEntityDriverManager() { checkInitialManagementContextReal(); return initialManagementContext.getEntityDriverManager(); } @Override public DownloadResolverManager getEntityDownloadsManager() { checkInitialManagementContextReal(); return initialManagementContext.getEntityDownloadsManager(); } @Override public StringConfigMap getConfig() { checkInitialManagementContextReal(); return initialManagementContext.getConfig(); } @Override public BrooklynProperties getBrooklynProperties() { checkInitialManagementContextReal(); return initialManagementContext.getBrooklynProperties(); } @Override public BrooklynStorage getStorage() { checkInitialManagementContextReal(); return initialManagementContext.getStorage(); } @Override public RebindManager getRebindManager() { // There was a race where EffectorUtils on invoking an effector calls: // mgmtSupport.getEntityChangeListener().onEffectorCompleted(eff); // but where the entity/app may be being unmanaged concurrently (e.g. calling app.stop()). // So now we allow the change-listener to be called. if (isInitialManagementContextReal()) { return initialManagementContext.getRebindManager(); } else { return new NonDeploymentRebindManager(); } } @Override public LocationRegistry getLocationRegistry() { checkInitialManagementContextReal(); return initialManagementContext.getLocationRegistry(); } @Override public BrooklynCatalog getCatalog() { checkInitialManagementContextReal(); return initialManagementContext.getCatalog(); } @Override public <T> T invokeEffectorMethodSync(final Entity entity, final Effector<T> eff, final Object args) throws ExecutionException { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation: cannot invoke effector "+eff+" on entity "+entity); } @Override public <T> Task<T> invokeEffector(final Entity entity, final Effector<T> eff, @SuppressWarnings("rawtypes") final Map parameters) { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation: cannot invoke effector "+eff+" on entity "+entity); } @Override public ClassLoader getBaseClassLoader() { checkInitialManagementContextReal(); return initialManagementContext.getBaseClassLoader(); } @Override public Iterable<URL> getBaseClassPathForScanning() { checkInitialManagementContextReal(); return initialManagementContext.getBaseClassPathForScanning(); } @Override public void addEntitySetListener(CollectionChangeListener<Entity> listener) { checkInitialManagementContextReal(); initialManagementContext.addEntitySetListener(listener); } @Override public void removeEntitySetListener(CollectionChangeListener<Entity> listener) { checkInitialManagementContextReal(); initialManagementContext.removeEntitySetListener(listener); } @Override public void terminate() { if (isInitialManagementContextReal()) { initialManagementContext.terminate(); } else { // no-op; the non-deployment management context has nothing needing terminated } } @Override public long getTotalEffectorInvocations() { if (isInitialManagementContextReal()) { return initialManagementContext.getTotalEffectorInvocations(); } else { return 0; } } @Override public void setBaseClassPathForScanning(Iterable<URL> urls) { checkInitialManagementContextReal(); initialManagementContext.setBaseClassPathForScanning(urls); } @Override public void prePreManage(Entity entity) { // no-op } @Override public void prePreManage(Location location) { // no-op } private boolean isInitialManagementContextReal() { return (initialManagementContext != null && !(initialManagementContext instanceof NonDeploymentManagementContext)); } private void checkInitialManagementContextReal() { if (!isInitialManagementContextReal()) { throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation."); } } @Override public void reloadBrooklynProperties() { // TODO Auto-generated method stub } private class NonDeploymentExecutionContext extends AbstractExecutionContext { @Override public Set<Task<?>> getTasks() { return Collections.emptySet(); } @Override protected <T> Task<T> submitInternal(Map<?, ?> properties, Object task) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } } /** * For when the initial management context is not "real"; the changeListener is a no-op, but everything else forbidden. * * @author aled */ private class NonDeploymentRebindManager implements RebindManager { @Override public ChangeListener getChangeListener() { return ChangeListener.NOOP; } @Override public void setPersister(BrooklynMementoPersister persister) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public BrooklynMementoPersister getPersister() { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public List<Application> rebind(BrooklynMemento memento) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public List<Application> rebind(BrooklynMemento memento, ClassLoader classLoader) { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public void stop() { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } @Override public void waitForPendingComplete(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { throw new IllegalStateException("Non-deployment context "+NonDeploymentManagementContext.this+" is not valid for this operation."); } } }
Implemented NonDeploymentManagementContext.reloadBrooklynProperties()
core/src/main/java/brooklyn/management/internal/NonDeploymentManagementContext.java
Implemented NonDeploymentManagementContext.reloadBrooklynProperties()
<ide><path>ore/src/main/java/brooklyn/management/internal/NonDeploymentManagementContext.java <ide> <ide> @Override <ide> public void reloadBrooklynProperties() { <del> // TODO Auto-generated method stub <del> <add> checkInitialManagementContextReal(); <add> initialManagementContext.reloadBrooklynProperties(); <ide> } <ide> <ide> private class NonDeploymentExecutionContext extends AbstractExecutionContext {
Java
apache-2.0
1288c324530fa03507827eacdf1fbe5ee9ce96b3
0
gkhays/NameParser
/* * (C) Copyright 2016 Garve Hays and others. * * 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. * * Contributors: * Garve Hays */ package hays.gkh; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NameParser { private static List<String> nobiliaryParticleList = Arrays .asList(new String[] { "vere", "von", "van", "de", "del", "della", "di", "da", "pietro", "vanden", "du", "st.", "st", "la", "ter", "al", "ibn", "de la" }); private static List<String> salutationList = Arrays.asList(new String[] { "mr", "master", "mister", "mrs", "miss", "ms", "dr", "rev", "fr" }); private static List<String> suffixList = Arrays.asList(new String[] { "I", "II", "III", "IV", "V", "Senior", "Junior", "Jr", "JR", "Sr", "SR", "PhD", "APR", "RPh", "PE", "MD", "MA", "DMD", "CME" }); /** * Test */ public static void main(String[] args) { String[] testNames = { "Von Fabella", "E. Pitney Bowes", "Dan Rather", "Dr. Jones", "Marcus Welby MD", "Ken Griffey Jr.", "Jack Jones M.D.", "E. Pluribus Unum", "Don R. Draper", "William S. Gates SR", "William S. Gates III", "Anthony de la Alpaca" }; NameParser parser = new NameParser(); for (String s : testNames) { parser.splitFullName(s); System.out.printf("[%4s] %10s %2s %10s [%4s]\n", parser.getHonorific(), parser.getFirstName(), parser.getInitials(), parser.getLastName(), parser.getSuffix()); } } private String firstName; private String honorific; private String initials; private String lastName; private String suffix; private String fixCase(String s) { String word = safeUpperCaseFirst(s, "-"); word = safeUpperCaseFirst(s, Pattern.quote(".")); // '\\.' return word; } public String getFirstName() { return this.firstName; } public String getHonorific() { return this.honorific; } public String getInitials() { return this.initials; } public String getLastName() { return this.lastName; } private Object getSuffix() { return this.suffix; } /** * Detect compound last names such as "Von Fange." * * Naturally there is a name for these kind of things; in this case it is * nobiliary particle. See the Wikipedia article: <a * href="https://en.wikipedia.org/wiki/Nobiliary_particle">Nobiliary * particle</a>. * * * @param s a {@link String} containing the name to test * @return <code>true</code> if a compound name; otherwise false */ private boolean isCompoundLastName(String s) { String word = s.toLowerCase(); for (String n : nobiliaryParticleList) { return (word.equals(n)); } return false; } private boolean isHonorific(String s) { String word = s.replace(".", "").toLowerCase(); for (String salutation : salutationList ) { return (word.equals(salutation)); } return false; } private boolean isInitial(String s) { return s.length() == 1 || (s.length() == 2 && s.contains(".")); } /** * Check to see if the given {@link String} is in Pascal case, e.g. * "McDonald." * * @param s * the {@link String} to examine * @return <code>true</code> if a match was found; false otherwise */ private boolean isPascalCase(String s) { // Considered (?<=[a-z])(?=[A-Z]). Pattern p = Pattern.compile("(?<=[a-z])(?=[A-Z])"); Matcher m = p.matcher(s); return m.find(); } private boolean isSuffix(String s) { String word = s.replace(".",""); for (String suffix : suffixList) { if (word.equals(suffix)) { return true; } } return false; } private String parseHonorific(String s) { if (isHonorific(s) == false) { return ""; } String word = s.replace(".", "").toLowerCase(); String honorific; switch (word) { case "mr": case "master": case "mister": honorific = "Mr."; break; case "mrs": honorific = "Mrs."; break; case "miss": case "ms": honorific = "Ms."; break; case "dr": honorific = "Dr."; break; case "rev": honorific = "Rev."; break; case "fr": honorific = "Fr."; break; default: return ""; } return honorific; } private String parseSuffix(String s) { if (isSuffix(s)) { return s; } return ""; } /** * Use this method if you don't have Java 8. * * @param array * the {@link String} array containing the elements to join * @param delimiter * the character used to join the elements * @return the joined {@link String} */ private String quickStringJoin(String[] array, String delimiter) { int count = 0; StringBuilder sb = new StringBuilder(); for (String s : array) { if (count == 0) { sb.append(s); } else { sb.append(delimiter).append(s); } } return sb.toString(); } /** * * @param word * @param delimiter * @return * * @since 1.8 */ private String safeUpperCaseFirst(String word, String delimiter) { String[] parts = word.split(delimiter); String[] words = new String[parts.length]; // TODO: Ummm... Why not a conventional for-loop? int count = 0; for (String s : parts) { words[count] = isPascalCase(s) ? s : upperCaseFirst(s.toLowerCase()); count++; } // Requires Java 8. return String.join(delimiter, Arrays.toString(words)); } /** * Splits a full name into the following parts: * <ul> * <li>Honorific, e.g. Mr., Mrs., Ms., etc.</li> * <li>Given name or first name</li> * <li>Surname or last name</li> * <li>Given name or first name</li> * <li>Suffix, e.g. II, Sr., PhD, etc.</li> * </ul> * * @param s * a {@link String} containing the full name to split */ public void splitFullName(String s) { // TODO: We can call splitFullName multiple times, which leaves some // baggage in the initial for each run. Quick hack below. this.initials = ""; String fullName = s.trim(); String[] unfilteredParts = fullName.split("\\s+"); List<String> nameParts = new ArrayList<String>(); for (String part : unfilteredParts) { if (part.contains("(") == false) { nameParts.add(part); } } int wordCount = nameParts.size(); this.honorific = parseHonorific(nameParts.get(0)); this.suffix = parseSuffix(nameParts.get(nameParts.size() - 1)); int startIndex = (this.honorific.isEmpty() ? 0 : 1); int endIndex = (this.suffix.isEmpty() ? wordCount : wordCount - 1); String word; for (int i = startIndex; i < endIndex - 1; i++) { word = nameParts.get(i); // Move on to parsing the last name if we find an indicator of a // compound last name such as von, van, etc. We use i != startIndex // to allow for rare cases where an indicator is actually the first // name, like "Von Fabella." if (isCompoundLastName(word) && i != startIndex) { break; } // Is it a middle initial or part of the first name? If we start off // with an initial we count it as the first name. if (isInitial(word)) { // Is the initial the first word? if (i == startIndex) { // If so, look ahead to see if they go by their middle name, // e.g. "R. Jason Smith" => "Jason Smith" and "R." is stored // as an initial. Whereas "R. J. Smith" => "R. Smith" and // "J." is stored as an initial. if (isInitial(nameParts.get(i+1))) { this.firstName = word.toUpperCase(); } else { this.initials = word.toUpperCase(); } } else { this.initials = word.toUpperCase(); } } else { this.firstName = fixCase(word); } } // Do we have more than a single word in our string? if (endIndex - startIndex > 1) { // Concatenate the last name. for (int j = 0; j < endIndex; j++) { this.lastName = fixCase(nameParts.get(j)); } } else { // Otherwise, single word strings are assumed to be first names. this.firstName = fixCase(nameParts.get(0)); } } /** * Uppercase the first character in a given {@link String}. * * @param s * the {@link String} upon which to operate * @return a {@link String} with the first character in uppercase */ private String upperCaseFirst(String s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }
src/hays/gkh/NameParser.java
/* * (C) Copyright 2016 Garve Hays and others. * * 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. * * Contributors: * Garve Hays */ package hays.gkh; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NameParser { private static List<String> nobiliaryParticleList = Arrays .asList(new String[] { "vere", "von", "van", "de", "del", "della", "di", "da", "pietro", "vanden", "du", "st.", "st", "la", "ter", "al", "ibn", "de la" }); private static List<String> salutationList = Arrays.asList(new String[] { "mr", "master", "mister", "mrs", "miss", "ms", "dr", "rev", "fr" }); private static List<String> suffixList = Arrays.asList(new String[] { "I", "II", "III", "IV", "V", "Senior", "Junior", "Jr", "JR", "Sr", "SR", "PhD", "APR", "RPh", "PE", "MD", "MA", "DMD", "CME" }); public static void main(String[] args) { String[] testNames = { "Von Fabella", "E. Pitney Bowes", "Dan Rather", "Dr. Jones", "Marcus Welby MD", "Ken Griffey Jr.", "Jack Jones M.D.", "E. Pluribus Unum", "Don R. Draper", "William S. Gates SR", "William S. Gates III", "Anthony de la Alpaca" }; NameParser parser = new NameParser(); for (String s : testNames) { parser.splitFullName(s); System.out.printf("[%4s] %10s %2s %10s [%4s]\n", parser.getHonorific(), parser.getFirstName(), parser.getInitials(), parser.getLastName(), parser.getSuffix()); } } private String firstName; private String honorific; private String initials; private String lastName; private String suffix; private String fixCase(String s) { String word = safeUpperCaseFirst(s, "-"); word = safeUpperCaseFirst(s, Pattern.quote(".")); // '\\.' return word; } public String getFirstName() { return this.firstName; } public String getHonorific() { return this.honorific; } public String getInitials() { return this.initials; } public String getLastName() { return this.lastName; } private Object getSuffix() { return this.suffix; } private boolean isCompoundLastName(String s) { String word = s.toLowerCase(); for (String n : nobiliaryParticleList) { return (word.equals(n)); } return false; } private boolean isHonorific(String s) { String word = s.replace(".", "").toLowerCase(); for (String salutation : salutationList ) { return (word.equals(salutation)); } return false; } private boolean isInitial(String s) { return s.length() == 1 || (s.length() == 2 && s.contains(".")); } // |[A-Z]+|s // (?<=[a-z])(?=[A-Z]) // http://stackoverflow.com/a/7599674/6146580 private boolean isPascalCase(String s) { Pattern p = Pattern.compile("(?<=[a-z])(?=[A-Z])"); Matcher m = p.matcher(s); return m.find(); } private boolean isSuffix(String s) { String word = s.replace(".",""); for (String suffix : suffixList) { if (word.equals(suffix)) { return true; } } return false; } private String parseHonorific(String s) { if (isHonorific(s) == false) { return ""; } String word = s.replace(".", "").toLowerCase(); String honorific; switch (word) { case "mr": case "master": case "mister": honorific = "Mr."; break; case "mrs": honorific = "Mrs."; break; case "miss": case "ms": honorific = "Ms."; break; case "dr": honorific = "Dr."; break; case "rev": honorific = "Rev."; break; case "fr": honorific = "Fr."; break; default: return ""; } return honorific; } private String parseSuffix(String s) { if (isSuffix(s)) { return s; } return ""; } /** * Use this method if you don't have Java 8. * * @param array * the {@link String} array containing the elements to join * @param delimiter * the character used to join the elements * @return the joined {@link String} */ private String quickStringJoin(String[] array, String delimiter) { int count = 0; StringBuilder sb = new StringBuilder(); for (String s : array) { if (count == 0) { sb.append(s); } else { sb.append(delimiter).append(s); } } return sb.toString(); } private String safeUpperCaseFirst(String word, String delimiter) { String[] parts = word.split(delimiter); String[] words = new String[parts.length]; // TODO: Ummm... Why not a conventional for-loop? int count = 0; for (String s : parts) { words[count] = isPascalCase(s) ? s : upperCaseFirst(s.toLowerCase()); count++; } // Requires Java 8. return String.join(delimiter, Arrays.toString(words)); } public void splitFullName(String s) { // TODO: We can call splitFullName multiple times, which leaves some // baggage in the initial for each run. Quick hack below. this.initials = ""; String fullName = s.trim(); String[] unfilteredParts = fullName.split("\\s+"); List<String> nameParts = new ArrayList<String>(); for (String part : unfilteredParts) { if (part.contains("(") == false) { nameParts.add(part); } } int wordCount = nameParts.size(); this.honorific = parseHonorific(nameParts.get(0)); this.suffix = parseSuffix(nameParts.get(nameParts.size() - 1)); int startIndex = (this.honorific.isEmpty() ? 0 : 1); int endIndex = (this.suffix.isEmpty() ? wordCount : wordCount - 1); String word; for (int i = startIndex; i < endIndex - 1; i++) { word = nameParts.get(i); // Move on to parsing the last name if we find an indicator of a // compound last name such as von, van, etc. We use i != startIndex // to allow for rare cases where an indicator is actually the first // name, like "Von Fabella." if (isCompoundLastName(word) && i != startIndex) { break; } // Is it a middle initial or part of the first name? If we start off // with an initial we count it as the first name. if (isInitial(word)) { // Is the initial the first word? if (i == startIndex) { // If so, look ahead to see if they go by their middle name, // e.g. "R. Jason Smith" => "Jason Smith" and "R." is stored // as an initial. Whereas "R. J. Smith" => "R. Smith" and // "J." is stored as an initial. if (isInitial(nameParts.get(i+1))) { this.firstName = word.toUpperCase(); } else { this.initials = word.toUpperCase(); } } else { this.initials = word.toUpperCase(); } } else { this.firstName = fixCase(word); } } // Do we have more than a single word in our string? if (endIndex - startIndex > 1) { // Concatenate the last name. for (int j = 0; j < endIndex; j++) { this.lastName = fixCase(nameParts.get(j)); } } else { // Otherwise, single word strings are assumed to be first names. this.firstName = fixCase(nameParts.get(0)); } } // http://stackoverflow.com/a/5725949/6146580 private String upperCaseFirst(String s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }
Add JavaDoc
src/hays/gkh/NameParser.java
Add JavaDoc
<ide><path>rc/hays/gkh/NameParser.java <ide> "II", "III", "IV", "V", "Senior", "Junior", "Jr", "JR", "Sr", "SR", <ide> "PhD", "APR", "RPh", "PE", "MD", "MA", "DMD", "CME" }); <ide> <add> /** <add> * Test <add> */ <ide> public static void main(String[] args) { <ide> String[] testNames = { "Von Fabella", "E. Pitney Bowes", "Dan Rather", <ide> "Dr. Jones", "Marcus Welby MD", "Ken Griffey Jr.", <ide> return this.suffix; <ide> } <ide> <add> /** <add> * Detect compound last names such as "Von Fange." <add> * <add> * Naturally there is a name for these kind of things; in this case it is <add> * nobiliary particle. See the Wikipedia article: <a <add> * href="https://en.wikipedia.org/wiki/Nobiliary_particle">Nobiliary <add> * particle</a>. <add> * <add> * <add> * @param s a {@link String} containing the name to test <add> * @return <code>true</code> if a compound name; otherwise false <add> */ <ide> private boolean isCompoundLastName(String s) { <ide> String word = s.toLowerCase(); <ide> for (String n : nobiliaryParticleList) { <ide> return s.length() == 1 || (s.length() == 2 && s.contains(".")); <ide> } <ide> <del> // |[A-Z]+|s <del> // (?<=[a-z])(?=[A-Z]) <del> // http://stackoverflow.com/a/7599674/6146580 <add> /** <add> * Check to see if the given {@link String} is in Pascal case, e.g. <add> * "McDonald." <add> * <add> * @param s <add> * the {@link String} to examine <add> * @return <code>true</code> if a match was found; false otherwise <add> */ <ide> private boolean isPascalCase(String s) { <add> // Considered (?<=[a-z])(?=[A-Z]). <ide> Pattern p = Pattern.compile("(?<=[a-z])(?=[A-Z])"); <ide> Matcher m = p.matcher(s); <ide> return m.find(); <ide> return sb.toString(); <ide> } <ide> <add> /** <add> * <add> * @param word <add> * @param delimiter <add> * @return <add> * <add> * @since 1.8 <add> */ <ide> private String safeUpperCaseFirst(String word, String delimiter) { <ide> String[] parts = word.split(delimiter); <ide> String[] words = new String[parts.length]; <ide> return String.join(delimiter, Arrays.toString(words)); <ide> } <ide> <add> /** <add> * Splits a full name into the following parts: <add> * <ul> <add> * <li>Honorific, e.g. Mr., Mrs., Ms., etc.</li> <add> * <li>Given name or first name</li> <add> * <li>Surname or last name</li> <add> * <li>Given name or first name</li> <add> * <li>Suffix, e.g. II, Sr., PhD, etc.</li> <add> * </ul> <add> * <add> * @param s <add> * a {@link String} containing the full name to split <add> */ <ide> public void splitFullName(String s) { <ide> // TODO: We can call splitFullName multiple times, which leaves some <ide> // baggage in the initial for each run. Quick hack below. <ide> } <ide> } <ide> <del> // http://stackoverflow.com/a/5725949/6146580 <add> /** <add> * Uppercase the first character in a given {@link String}. <add> * <add> * @param s <add> * the {@link String} upon which to operate <add> * @return a {@link String} with the first character in uppercase <add> */ <ide> private String upperCaseFirst(String s) { <ide> return s.substring(0, 1).toUpperCase() + s.substring(1); <ide> }
JavaScript
mit
01a955eb450d9e671324c8ca2058719df3797cc4
0
almeidapaulopt/frappe,manassolanki/frappe,ESS-LLP/frappe,manassolanki/frappe,chdecultot/frappe,saurabh6790/frappe,RicardoJohann/frappe,vjFaLk/frappe,vjFaLk/frappe,tmimori/frappe,vjFaLk/frappe,mhbu50/frappe,StrellaGroup/frappe,tmimori/frappe,saurabh6790/frappe,adityahase/frappe,frappe/frappe,neilLasrado/frappe,neilLasrado/frappe,frappe/frappe,neilLasrado/frappe,tundebabzy/frappe,StrellaGroup/frappe,chdecultot/frappe,tundebabzy/frappe,ESS-LLP/frappe,manassolanki/frappe,vjFaLk/frappe,paurosello/frappe,mhbu50/frappe,RicardoJohann/frappe,tmimori/frappe,saurabh6790/frappe,yashodhank/frappe,mhbu50/frappe,StrellaGroup/frappe,paurosello/frappe,yashodhank/frappe,yashodhank/frappe,saurabh6790/frappe,almeidapaulopt/frappe,tundebabzy/frappe,manassolanki/frappe,frappe/frappe,RicardoJohann/frappe,neilLasrado/frappe,tundebabzy/frappe,adityahase/frappe,RicardoJohann/frappe,adityahase/frappe,chdecultot/frappe,almeidapaulopt/frappe,ESS-LLP/frappe,yashodhank/frappe,ESS-LLP/frappe,almeidapaulopt/frappe,chdecultot/frappe,mhbu50/frappe,adityahase/frappe,tmimori/frappe,paurosello/frappe,paurosello/frappe
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.last_edited_communication = {}; frappe.standard_replies = {}; frappe.views.CommunicationComposer = Class.extend({ init: function(opts) { $.extend(this, opts); this.make(); }, make: function() { var me = this; this.dialog = new frappe.ui.Dialog({ title: (this.title || this.subject || __("New Email")), no_submit_on_enter: true, fields: this.get_fields(), primary_action_label: __("Send"), primary_action: function() { me.send_action(); } }); $(document).on("upload_complete", function(event, attachment) { if(me.dialog.display) { var wrapper = $(me.dialog.fields_dict.select_attachments.wrapper); // find already checked items var checked_items = wrapper.find('[data-file-name]:checked').map(function() { return $(this).attr("data-file-name"); }); // reset attachment list me.render_attach(); // check latest added checked_items.push(attachment.name); $.each(checked_items, function(i, filename) { wrapper.find('[data-file-name="'+ filename +'"]').prop("checked", true); }); } }) this.prepare(); this.dialog.show(); }, get_fields: function() { var fields= [ {label:__("To"), fieldtype:"Data", reqd: 0, fieldname:"recipients",length:524288}, {fieldtype: "Section Break", collapsible: 1, label: __("CC, BCC & Standard Reply")}, {label:__("CC"), fieldtype:"Data", fieldname:"cc", length:524288}, {label:__("BCC"), fieldtype:"Data", fieldname:"bcc", length:524288}, {label:__("Standard Reply"), fieldtype:"Link", options:"Standard Reply", fieldname:"standard_reply"}, {fieldtype: "Section Break"}, {label:__("Subject"), fieldtype:"Data", reqd: 1, fieldname:"subject", length:524288}, {fieldtype: "Section Break"}, {label:__("Message"), fieldtype:"Text Editor", reqd: 1, fieldname:"content"}, {fieldtype: "Section Break"}, {fieldtype: "Column Break"}, {label:__("Send As Email"), fieldtype:"Check", fieldname:"send_email"}, {label:__("Send me a copy"), fieldtype:"Check", fieldname:"send_me_a_copy", 'default': frappe.boot.user.send_me_a_copy}, {label:__("Send Read Receipt"), fieldtype:"Check", fieldname:"send_read_receipt"}, {label:__("Communication Medium"), fieldtype:"Select", options: ["Phone", "Chat", "Email", "SMS", "Visit", "Other"], fieldname:"communication_medium"}, {label:__("Sent or Received"), fieldtype:"Select", options: ["Received", "Sent"], fieldname:"sent_or_received"}, {label:__("Attach Document Print"), fieldtype:"Check", fieldname:"attach_document_print"}, {label:__("Select Print Format"), fieldtype:"Select", fieldname:"select_print_format"}, {label:__("Select Languages"), fieldtype:"Select", fieldname:"language_sel"}, {fieldtype: "Column Break"}, {label:__("Select Attachments"), fieldtype:"HTML", fieldname:"select_attachments"} ]; // add from if user has access to multiple email accounts var email_accounts = frappe.boot.email_accounts.filter(function(account, idx){ return !in_list(["All Accounts", "Sent", "Spam", "Trash"], account.email_account) && account.enable_outgoing }) if(frappe.boot.email_accounts && email_accounts.length > 1) { fields = [ {label: __("From"), fieldtype: "Select", reqd: 1, fieldname: "sender", options: email_accounts.map(function(e) { return e.email_id; }) } ].concat(fields); } return fields; }, prepare: function() { this.setup_subject_and_recipients(); this.setup_print_language() this.setup_print(); this.setup_attach(); this.setup_email(); this.setup_awesomplete(); this.setup_last_edited_communication(); this.setup_standard_reply(); this.dialog.fields_dict.recipients.set_value(this.recipients || ''); this.dialog.fields_dict.cc.set_value(this.cc || ''); this.dialog.fields_dict.bcc.set_value(this.bcc || ''); if(this.dialog.fields_dict.sender) { this.dialog.fields_dict.sender.set_value(this.sender || ''); } this.dialog.fields_dict.subject.set_value(this.subject || ''); this.setup_earlier_reply(); }, setup_subject_and_recipients: function() { this.subject = this.subject || ""; if(!this.forward && !this.recipients && this.last_email) { this.recipients = this.last_email.sender; this.cc = this.last_email.cc; this.bcc = this.last_email.bcc; } if(!this.forward && !this.recipients) { this.recipients = this.frm && this.frm.timeline.get_recipient(); } if(!this.subject && this.frm) { // get subject from last communication var last = this.frm.timeline.get_last_email(); if(last) { this.subject = last.subject; if(!this.recipients) { this.recipients = last.sender; } // prepend "Re:" if(strip(this.subject.toLowerCase().split(":")[0])!="re") { this.subject = __("Re: {0}", [this.subject]); } } if (!this.subject) { if (this.frm.subject_field && this.frm.doc[this.frm.subject_field]) { this.subject = __("Re: {0}", [this.frm.doc[this.frm.subject_field]]); } else { let title = this.frm.doc.name; if(this.frm.meta.title_field && this.frm.doc[this.frm.meta.title_field] && this.frm.doc[this.frm.meta.title_field] != this.frm.doc.name) { title = `${this.frm.doc[this.frm.meta.title_field]} (#${this.frm.doc.name})`; } this.subject = `${__(this.frm.doctype)}: ${title}`; } } } }, setup_standard_reply: function() { var me = this; this.dialog.fields_dict["standard_reply"].df.onchange = () => { var standard_reply = me.dialog.fields_dict.standard_reply.get_value(); var prepend_reply = function(reply) { if(me.reply_added===standard_reply) { return; } var content_field = me.dialog.fields_dict.content; var subject_field = me.dialog.fields_dict.subject; var content = content_field.get_value() || ""; var subject = subject_field.get_value() || ""; var parts = content.split('<!-- salutation-ends -->'); if(parts.length===2) { content = [reply.message, "<br>", parts[1]]; } else { content = [reply.message, "<br>", content]; } content_field.set_value(content.join('')); if(subject === "") { subject_field.set_value(reply.subject); } me.reply_added = standard_reply; } frappe.call({ method: 'frappe.email.doctype.standard_reply.standard_reply.get_standard_reply', args: { template_name: standard_reply, doc: me.frm.doc }, callback: function(r) { prepend_reply(r.message); } }); } }, setup_last_edited_communication: function() { var me = this; if (!this.doc){ if (cur_frm){ this.doc = cur_frm.doctype; }else{ this.doc = "Inbox"; } } if (cur_frm && cur_frm.docname) { this.key = cur_frm.docname; } else { this.key = "Inbox"; } if(this.last_email) { this.key = this.key + ":" + this.last_email.name; } if(this.subject){ this.key = this.key + ":" + this.subject; } this.dialog.onhide = function() { var last_edited_communication = me.get_last_edited_communication(); $.extend(last_edited_communication, { sender: me.dialog.get_value("sender"), recipients: me.dialog.get_value("recipients"), subject: me.dialog.get_value("subject"), content: me.dialog.get_value("content"), }); } this.dialog.on_page_show = function() { if (!me.txt) { var last_edited_communication = me.get_last_edited_communication(); if(last_edited_communication.content) { me.dialog.set_value("sender", last_edited_communication.sender || ""); me.dialog.set_value("subject", last_edited_communication.subject || ""); me.dialog.set_value("recipients", last_edited_communication.recipients || ""); me.dialog.set_value("content", last_edited_communication.content || ""); } } } }, get_last_edited_communication: function() { if (!frappe.last_edited_communication[this.doc]) { frappe.last_edited_communication[this.doc] = {}; } if(!frappe.last_edited_communication[this.doc][this.key]) { frappe.last_edited_communication[this.doc][this.key] = {}; } return frappe.last_edited_communication[this.doc][this.key]; }, setup_print_language: function() { var me = this; var doc = this.doc || cur_frm.doc; var fields = this.dialog.fields_dict; //Load default print language from doctype this.lang_code = doc.language //On selection of language retrieve language code $(fields.language_sel.input).click(function(){ me.lang_code = this.value }) // Load all languages in the select field language_sel $(fields.language_sel.input) .empty() .add_options(frappe.get_languages()) .val(doc.language) }, setup_print: function() { // print formats var fields = this.dialog.fields_dict; // toggle print format $(fields.attach_document_print.input).click(function() { $(fields.select_print_format.wrapper).toggle($(this).prop("checked")); }); // select print format $(fields.select_print_format.wrapper).toggle(false); if (cur_frm) { $(fields.select_print_format.input) .empty() .add_options(cur_frm.print_preview.print_formats) .val(cur_frm.print_preview.print_formats[0]); } else { $(fields.attach_document_print.wrapper).toggle(false); } }, setup_attach: function() { var fields = this.dialog.fields_dict; var attach = $(fields.select_attachments.wrapper); var me = this if (!me.attachments){ me.attachments = [] } var args = { args: { from_form: 1, folder:"Home/Attachments" }, callback: function(attachment, r) { me.attachments.push(attachment); }, max_width: null, max_height: null }; if(me.frm) { args = { args: (me.frm.attachments.get_args ? me.frm.attachments.get_args() : { from_form: 1,folder:"Home/Attachments" }), callback: function (attachment, r) { me.frm.attachments.attachment_uploaded(attachment, r) }, max_width: me.frm.cscript ? me.frm.cscript.attachment_max_width : null, max_height: me.frm.cscript ? me.frm.cscript.attachment_max_height : null } } $("<h6 class='text-muted add-attachment' style='margin-top: 12px; cursor:pointer;'>" +__("Select Attachments")+"</h6><div class='attach-list'></div>\ <p class='add-more-attachments'>\ <a class='text-muted small'><i class='octicon octicon-plus' style='font-size: 12px'></i> " +__("Add Attachment")+"</a></p>").appendTo(attach.empty()) attach.find(".add-more-attachments a").on('click',this,function() { me.upload = frappe.ui.get_upload_dialog(args); }) me.render_attach() }, render_attach:function(){ var fields = this.dialog.fields_dict; var attach = $(fields.select_attachments.wrapper).find(".attach-list").empty(); var files = []; if (this.attachments && this.attachments.length) { files = files.concat(this.attachments); } if (cur_frm) { files = files.concat(cur_frm.get_files()); } if(files.length) { $.each(files, function(i, f) { if (!f.file_name) return; f.file_url = frappe.urllib.get_full_url(f.file_url); $(repl('<p class="checkbox">' + '<label><span><input type="checkbox" data-file-name="%(name)s"></input></span>' + '<span class="small">%(file_name)s</span>' + ' <a href="%(file_url)s" target="_blank" class="text-muted small">' + '<i class="fa fa-share" style="vertical-align: middle; margin-left: 3px;"></i>' + '</label></p>', f)) .appendTo(attach) }); } }, setup_email: function() { // email var me = this; var fields = this.dialog.fields_dict; if(this.attach_document_print) { $(fields.attach_document_print.input).click(); $(fields.select_print_format.wrapper).toggle(true); } $(fields.send_email.input).prop("checked", true); $(fields.send_me_a_copy.input).on('click', () => { // update send me a copy (make it sticky) let val = fields.send_me_a_copy.get_value(); frappe.db.set_value('User', frappe.session.user, 'send_me_a_copy', val); frappe.boot.user.send_me_a_copy = val; }); // toggle print format $(fields.send_email.input).click(function() { $(fields.communication_medium.wrapper).toggle(!!!$(this).prop("checked")); $(fields.sent_or_received.wrapper).toggle(!!!$(this).prop("checked")); $(fields.send_read_receipt.wrapper).toggle($(this).prop("checked")); me.dialog.get_primary_btn().html($(this).prop("checked") ? "Send" : "Add Communication"); }); // select print format $(fields.communication_medium.wrapper).toggle(false); $(fields.sent_or_received.wrapper).toggle(false); }, send_action: function() { var me = this; var btn = me.dialog.get_primary_btn(); var form_values = this.get_values(); if(!form_values) return; var selected_attachments = $.map($(me.dialog.wrapper) .find("[data-file-name]:checked"), function (element) { return $(element).attr("data-file-name"); }); if(form_values.attach_document_print) { if (cur_frm.print_preview.is_old_style(form_values.select_print_format || "")) { cur_frm.print_preview.with_old_style({ format: form_values.select_print_format, callback: function(print_html) { me.send_email(btn, form_values, selected_attachments, print_html); } }); } else { me.send_email(btn, form_values, selected_attachments, null, form_values.select_print_format || ""); } } else { me.send_email(btn, form_values, selected_attachments); } }, get_values: function() { var form_values = this.dialog.get_values(); // cc for ( var i=0, l=this.dialog.fields.length; i < l; i++ ) { var df = this.dialog.fields[i]; if ( df.is_cc_checkbox ) { // concat in cc if ( form_values[df.fieldname] ) { form_values.cc = ( form_values.cc ? (form_values.cc + ", ") : "" ) + df.fieldname; form_values.bcc = ( form_values.bcc ? (form_values.bcc + ", ") : "" ) + df.fieldname; } delete form_values[df.fieldname]; } } return form_values; }, send_email: function(btn, form_values, selected_attachments, print_html, print_format) { var me = this; me.dialog.hide(); if((form_values.send_email || form_values.communication_medium === "Email") && !form_values.recipients) { frappe.msgprint(__("Enter Email Recipient(s)")); return; } if(!form_values.attach_document_print) { print_html = null; print_format = null; } if(form_values.send_email) { if(cur_frm && !frappe.model.can_email(me.doc.doctype, cur_frm)) { frappe.msgprint(__("You are not allowed to send emails related to this document")); return; } form_values.communication_medium = "Email"; form_values.sent_or_received = "Sent"; } return frappe.call({ method:"frappe.core.doctype.communication.email.make", args: { recipients: form_values.recipients, cc: form_values.cc, bcc: form_values.bcc, subject: form_values.subject, content: form_values.content, doctype: me.doc.doctype, name: me.doc.name, send_email: form_values.send_email, print_html: print_html, send_me_a_copy: form_values.send_me_a_copy, print_format: print_format, communication_medium: form_values.communication_medium, sent_or_received: form_values.sent_or_received, sender: form_values.sender, sender_full_name: form_values.sender?frappe.user.full_name():undefined, attachments: selected_attachments, _lang : me.lang_code, read_receipt:form_values.send_read_receipt }, btn: btn, callback: function(r) { if(!r.exc) { frappe.utils.play_sound("email"); if(form_values.send_email && r.message["emails_not_sent_to"]) { frappe.msgprint(__("Email not sent to {0} (unsubscribed / disabled)", [ frappe.utils.escape_html(r.message["emails_not_sent_to"]) ]) ); } if ((frappe.last_edited_communication[me.doc] || {})[me.key]) { delete frappe.last_edited_communication[me.doc][me.key]; } if (cur_frm) { // clear input cur_frm.timeline.input && cur_frm.timeline.input.val(""); cur_frm.reload_doc(); } // try the success callback if it exists if (me.success) { try { me.success(r); } catch (e) { console.log(e); } } } else { frappe.msgprint(__("There were errors while sending email. Please try again.")); // try the error callback if it exists if (me.error) { try { me.error(r); } catch (e) { console.log(e); } } } } }); }, setup_earlier_reply: function() { var fields = this.dialog.fields_dict, signature = frappe.boot.user.email_signature || "", last_email = this.last_email; if(!last_email) { last_email = this.frm && this.frm.timeline.get_last_email(true); } if(!frappe.utils.is_html(signature)) { signature = signature.replace(/\n/g, "<br>"); } if(this.txt) { this.message = this.txt + (this.message ? ("<br><br>" + this.message) : ""); } if(this.real_name) { this.message = '<p>'+__('Dear') +' ' + this.real_name + ",</p><!-- salutation-ends --><br>" + (this.message || ""); } var reply = (this.message || "") + (signature ? ("<br>" + signature) : ""); var content = ''; if(last_email) { var last_email_content = last_email.original_comment || last_email.content; last_email_content = last_email_content .replace(/&lt;meta[\s\S]*meta&gt;/g, '') // remove <meta> tags .replace(/&lt;style[\s\S]*&lt;\/style&gt;/g, ''); // // remove <style> tags content = '<div><br></div>' + reply + "<br><!-- original-reply --><br>" + '<blockquote>' + '<p>' + __("On {0}, {1} wrote:", [frappe.datetime.global_date_format(last_email.communication_date) , last_email.sender]) + '</p>' + last_email_content + '<blockquote>'; } else { content = "<div><br></div>" + reply; } fields.content.set_value(content); }, setup_awesomplete: function() { var me = this; [ this.dialog.fields_dict.recipients.input, this.dialog.fields_dict.cc.input, this.dialog.fields_dict.bcc.input ].map(function(input) { me.setup_awesomplete_for_input(input); }); }, setup_awesomplete_for_input: function(input) { function split(val) { return val.split( /,\s*/ ); } function extractLast(term) { return split(term).pop(); } var awesomplete = new Awesomplete(input, { minChars: 0, maxItems: 99, autoFirst: true, list: [], item: function(item, input) { return $('<li>').text(item.value).get(0); }, filter: function(text, input) { return true }, replace: function(text) { var before = this.input.value.match(/^.+,\s*|/)[0]; this.input.value = before + text + ", "; } }); var delay_timer; var $input = $(input); $input.on("input", function(e) { clearTimeout(delay_timer); delay_timer = setTimeout(function() { var term = e.target.value; frappe.call({ method:'frappe.email.get_contact_list', args: { 'txt': extractLast(term) || '%' }, quiet: true, callback: function(r) { awesomplete.list = r.message || []; } }); },250); }); } });
frappe/public/js/frappe/views/communication.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.last_edited_communication = {}; frappe.standard_replies = {}; frappe.views.CommunicationComposer = Class.extend({ init: function(opts) { $.extend(this, opts); this.make(); }, make: function() { var me = this; this.dialog = new frappe.ui.Dialog({ title: (this.title || this.subject || __("New Email")), no_submit_on_enter: true, fields: this.get_fields(), primary_action_label: __("Send"), primary_action: function() { me.send_action(); } }); $(document).on("upload_complete", function(event, attachment) { if(me.dialog.display) { var wrapper = $(me.dialog.fields_dict.select_attachments.wrapper); // find already checked items var checked_items = wrapper.find('[data-file-name]:checked').map(function() { return $(this).attr("data-file-name"); }); // reset attachment list me.render_attach(); // check latest added checked_items.push(attachment.name); $.each(checked_items, function(i, filename) { wrapper.find('[data-file-name="'+ filename +'"]').prop("checked", true); }); } }) this.prepare(); this.dialog.show(); }, get_fields: function() { var fields= [ {label:__("To"), fieldtype:"Data", reqd: 0, fieldname:"recipients",length:524288}, {fieldtype: "Section Break", collapsible: 1, label: __("CC, BCC & Standard Reply")}, {label:__("CC"), fieldtype:"Data", fieldname:"cc", length:524288}, {label:__("BCC"), fieldtype:"Data", fieldname:"bcc", length:524288}, {label:__("Standard Reply"), fieldtype:"Link", options:"Standard Reply", fieldname:"standard_reply"}, {fieldtype: "Section Break"}, {label:__("Subject"), fieldtype:"Data", reqd: 1, fieldname:"subject", length:524288}, {fieldtype: "Section Break"}, {label:__("Message"), fieldtype:"Text Editor", reqd: 1, fieldname:"content"}, {fieldtype: "Section Break"}, {fieldtype: "Column Break"}, {label:__("Send As Email"), fieldtype:"Check", fieldname:"send_email"}, {label:__("Send me a copy"), fieldtype:"Check", fieldname:"send_me_a_copy", 'default': frappe.boot.user.send_me_a_copy}, {label:__("Send Read Receipt"), fieldtype:"Check", fieldname:"send_read_receipt"}, {label:__("Communication Medium"), fieldtype:"Select", options: ["Phone", "Chat", "Email", "SMS", "Visit", "Other"], fieldname:"communication_medium"}, {label:__("Sent or Received"), fieldtype:"Select", options: ["Received", "Sent"], fieldname:"sent_or_received"}, {label:__("Attach Document Print"), fieldtype:"Check", fieldname:"attach_document_print"}, {label:__("Select Print Format"), fieldtype:"Select", fieldname:"select_print_format"}, {label:__("Select Languages"), fieldtype:"Select", fieldname:"language_sel"}, {fieldtype: "Column Break"}, {label:__("Select Attachments"), fieldtype:"HTML", fieldname:"select_attachments"} ]; // add from if user has access to multiple email accounts var email_accounts = frappe.boot.email_accounts.filter(function(account, idx){ return !in_list(["All Accounts", "Sent", "Spam", "Trash"], account.email_account) && account.enable_outgoing }) if(frappe.boot.email_accounts && email_accounts.length > 1) { fields = [ {label: __("From"), fieldtype: "Select", reqd: 1, fieldname: "sender", options: email_accounts.map(function(e) { return e.email_id; }) } ].concat(fields); } return fields; }, prepare: function() { this.setup_subject_and_recipients(); this.setup_print_language() this.setup_print(); this.setup_attach(); this.setup_email(); this.setup_awesomplete(); this.setup_last_edited_communication(); this.setup_standard_reply(); this.dialog.fields_dict.recipients.set_value(this.recipients || ''); this.dialog.fields_dict.cc.set_value(this.cc || ''); this.dialog.fields_dict.bcc.set_value(this.bcc || ''); if(this.dialog.fields_dict.sender) { this.dialog.fields_dict.sender.set_value(this.sender || ''); } this.dialog.fields_dict.subject.set_value(this.subject || ''); this.setup_earlier_reply(); }, setup_subject_and_recipients: function() { this.subject = this.subject || ""; if(!this.forward && !this.recipients && this.last_email) { this.recipients = this.last_email.sender; this.cc = this.last_email.cc; this.bcc = this.last_email.bcc; } if(!this.forward && !this.recipients) { this.recipients = this.frm && this.frm.timeline.get_recipient(); } if(!this.subject && this.frm) { // get subject from last communication var last = this.frm.timeline.get_last_email(); if(last) { this.subject = last.subject; if(!this.recipients) { this.recipients = last.sender; } // prepend "Re:" if(strip(this.subject.toLowerCase().split(":")[0])!="re") { this.subject = __("Re: {0}", [this.subject]); } } if (!this.subject) { if (this.frm.subject_field && this.frm.doc[this.frm.subject_field]) { this.subject = __("Re: {0}", [this.frm.doc[this.frm.subject_field]]); } else { let title = this.frm.doc.name; if(this.frm.meta.title_field && this.frm.doc[this.frm.meta.title_field] && this.frm.doc[this.frm.meta.title_field] != this.frm.doc.name) { title = `${this.frm.doc[this.frm.meta.title_field]} (#${this.frm.doc.name})`; } this.subject = `${__(this.frm.doctype)}: ${title}`; } } } }, setup_standard_reply: function() { var me = this; this.dialog.fields_dict["standard_reply"].df.onchange = () => { var standard_reply = me.dialog.fields_dict.standard_reply.get_value(); var prepend_reply = function(reply) { if(me.reply_added===standard_reply) { return; } var content_field = me.dialog.fields_dict.content; var subject_field = me.dialog.fields_dict.subject; var content = content_field.get_value() || ""; var subject = subject_field.get_value() || ""; var parts = content.split('<!-- salutation-ends -->'); if(parts.length===2) { content = [reply.message, "<br>", parts[1]]; } else { content = [reply.message, "<br>", content]; } content_field.set_value(content.join('')); if(subject === "") { subject_field.set_value(reply.subject); } me.reply_added = standard_reply; } frappe.call({ method: 'frappe.email.doctype.standard_reply.standard_reply.get_standard_reply', args: { template_name: standard_reply, doc: me.frm.doc }, callback: function(r) { prepend_reply(r.message); } }); } }, setup_last_edited_communication: function() { var me = this; if (!this.doc){ if (cur_frm){ this.doc = cur_frm.doctype; }else{ this.doc = "Inbox"; } } if (cur_frm && cur_frm.docname) { this.key = cur_frm.docname; } else { this.key = "Inbox"; } if(this.last_email) { this.key = this.key + ":" + this.last_email.name; } if(this.subject){ this.key = this.key + ":" + this.subject; } this.dialog.onhide = function() { var last_edited_communication = me.get_last_edited_communication(); $.extend(last_edited_communication, { sender: me.dialog.get_value("sender"), recipients: me.dialog.get_value("recipients"), subject: me.dialog.get_value("subject"), content: me.dialog.get_value("content"), }); } this.dialog.on_page_show = function() { if (!me.txt) { var last_edited_communication = me.get_last_edited_communication(); if(last_edited_communication.content) { me.dialog.set_value("sender", last_edited_communication.sender || ""); me.dialog.set_value("subject", last_edited_communication.subject || ""); me.dialog.set_value("recipients", last_edited_communication.recipients || ""); me.dialog.set_value("content", last_edited_communication.content || ""); } } } }, get_last_edited_communication: function() { if (!frappe.last_edited_communication[this.doc]) { frappe.last_edited_communication[this.doc] = {}; } if(!frappe.last_edited_communication[this.doc][this.key]) { frappe.last_edited_communication[this.doc][this.key] = {}; } return frappe.last_edited_communication[this.doc][this.key]; }, setup_print_language: function() { var me = this; var doc = this.doc || cur_frm.doc; var fields = this.dialog.fields_dict; //Load default print language from doctype this.lang_code = doc.language //On selection of language retrieve language code $(fields.language_sel.input).click(function(){ me.lang_code = this.value }) // Load all languages in the select field language_sel $(fields.language_sel.input) .empty() .add_options(frappe.get_languages()) .val(doc.language) }, setup_print: function() { // print formats var fields = this.dialog.fields_dict; // toggle print format $(fields.attach_document_print.input).click(function() { $(fields.select_print_format.wrapper).toggle($(this).prop("checked")); }); // select print format $(fields.select_print_format.wrapper).toggle(false); if (cur_frm) { $(fields.select_print_format.input) .empty() .add_options(cur_frm.print_preview.print_formats) .val(cur_frm.print_preview.print_formats[0]); } else { $(fields.attach_document_print.wrapper).toggle(false); } }, setup_attach: function() { var fields = this.dialog.fields_dict; var attach = $(fields.select_attachments.wrapper); var me = this if (!me.attachments){ me.attachments = [] } var args = { args: { from_form: 1, folder:"Home/Attachments" }, callback: function(attachment, r) { me.attachments.push(attachment); }, max_width: null, max_height: null }; if(me.frm) { args = { args: (me.frm.attachments.get_args ? me.frm.attachments.get_args() : { from_form: 1,folder:"Home/Attachments" }), callback: function (attachment, r) { me.frm.attachments.attachment_uploaded(attachment, r) }, max_width: me.frm.cscript ? me.frm.cscript.attachment_max_width : null, max_height: me.frm.cscript ? me.frm.cscript.attachment_max_height : null } } $("<h6 class='text-muted add-attachment' style='margin-top: 12px; cursor:pointer;'>" +__("Select Attachments")+"</h6><div class='attach-list'></div>\ <p class='add-more-attachments'>\ <a class='text-muted small'><i class='octicon octicon-plus' style='font-size: 12px'></i> " +__("Add Attachment")+"</a></p>").appendTo(attach.empty()) attach.find(".add-more-attachments a").on('click',this,function() { me.upload = frappe.ui.get_upload_dialog(args); }) me.render_attach() }, render_attach:function(){ var fields = this.dialog.fields_dict; var attach = $(fields.select_attachments.wrapper).find(".attach-list").empty(); if (cur_frm){ var files = cur_frm.get_files(); }else { var files = this.attachments } if(files.length) { $.each(files, function(i, f) { if (!f.file_name) return; f.file_url = frappe.urllib.get_full_url(f.file_url); $(repl('<p class="checkbox">' + '<label><span><input type="checkbox" data-file-name="%(name)s"></input></span>' + '<span class="small">%(file_name)s</span>' + ' <a href="%(file_url)s" target="_blank" class="text-muted small">' + '<i class="fa fa-share" style="vertical-align: middle; margin-left: 3px;"></i>' + '</label></p>', f)) .appendTo(attach) }); } }, setup_email: function() { // email var me = this; var fields = this.dialog.fields_dict; if(this.attach_document_print) { $(fields.attach_document_print.input).click(); $(fields.select_print_format.wrapper).toggle(true); } $(fields.send_email.input).prop("checked", true); $(fields.send_me_a_copy.input).on('click', () => { // update send me a copy (make it sticky) let val = fields.send_me_a_copy.get_value(); frappe.db.set_value('User', frappe.session.user, 'send_me_a_copy', val); frappe.boot.user.send_me_a_copy = val; }); // toggle print format $(fields.send_email.input).click(function() { $(fields.communication_medium.wrapper).toggle(!!!$(this).prop("checked")); $(fields.sent_or_received.wrapper).toggle(!!!$(this).prop("checked")); $(fields.send_read_receipt.wrapper).toggle($(this).prop("checked")); me.dialog.get_primary_btn().html($(this).prop("checked") ? "Send" : "Add Communication"); }); // select print format $(fields.communication_medium.wrapper).toggle(false); $(fields.sent_or_received.wrapper).toggle(false); }, send_action: function() { var me = this; var btn = me.dialog.get_primary_btn(); var form_values = this.get_values(); if(!form_values) return; var selected_attachments = $.map($(me.dialog.wrapper) .find("[data-file-name]:checked"), function (element) { return $(element).attr("data-file-name"); }); if(form_values.attach_document_print) { if (cur_frm.print_preview.is_old_style(form_values.select_print_format || "")) { cur_frm.print_preview.with_old_style({ format: form_values.select_print_format, callback: function(print_html) { me.send_email(btn, form_values, selected_attachments, print_html); } }); } else { me.send_email(btn, form_values, selected_attachments, null, form_values.select_print_format || ""); } } else { me.send_email(btn, form_values, selected_attachments); } }, get_values: function() { var form_values = this.dialog.get_values(); // cc for ( var i=0, l=this.dialog.fields.length; i < l; i++ ) { var df = this.dialog.fields[i]; if ( df.is_cc_checkbox ) { // concat in cc if ( form_values[df.fieldname] ) { form_values.cc = ( form_values.cc ? (form_values.cc + ", ") : "" ) + df.fieldname; form_values.bcc = ( form_values.bcc ? (form_values.bcc + ", ") : "" ) + df.fieldname; } delete form_values[df.fieldname]; } } return form_values; }, send_email: function(btn, form_values, selected_attachments, print_html, print_format) { var me = this; me.dialog.hide(); if((form_values.send_email || form_values.communication_medium === "Email") && !form_values.recipients) { frappe.msgprint(__("Enter Email Recipient(s)")); return; } if(!form_values.attach_document_print) { print_html = null; print_format = null; } if(form_values.send_email) { if(cur_frm && !frappe.model.can_email(me.doc.doctype, cur_frm)) { frappe.msgprint(__("You are not allowed to send emails related to this document")); return; } form_values.communication_medium = "Email"; form_values.sent_or_received = "Sent"; } return frappe.call({ method:"frappe.core.doctype.communication.email.make", args: { recipients: form_values.recipients, cc: form_values.cc, bcc: form_values.bcc, subject: form_values.subject, content: form_values.content, doctype: me.doc.doctype, name: me.doc.name, send_email: form_values.send_email, print_html: print_html, send_me_a_copy: form_values.send_me_a_copy, print_format: print_format, communication_medium: form_values.communication_medium, sent_or_received: form_values.sent_or_received, sender: form_values.sender, sender_full_name: form_values.sender?frappe.user.full_name():undefined, attachments: selected_attachments, _lang : me.lang_code, read_receipt:form_values.send_read_receipt }, btn: btn, callback: function(r) { if(!r.exc) { frappe.utils.play_sound("email"); if(form_values.send_email && r.message["emails_not_sent_to"]) { frappe.msgprint(__("Email not sent to {0} (unsubscribed / disabled)", [ frappe.utils.escape_html(r.message["emails_not_sent_to"]) ]) ); } if ((frappe.last_edited_communication[me.doc] || {})[me.key]) { delete frappe.last_edited_communication[me.doc][me.key]; } if (cur_frm) { // clear input cur_frm.timeline.input && cur_frm.timeline.input.val(""); cur_frm.reload_doc(); } // try the success callback if it exists if (me.success) { try { me.success(r); } catch (e) { console.log(e); } } } else { frappe.msgprint(__("There were errors while sending email. Please try again.")); // try the error callback if it exists if (me.error) { try { me.error(r); } catch (e) { console.log(e); } } } } }); }, setup_earlier_reply: function() { var fields = this.dialog.fields_dict, signature = frappe.boot.user.email_signature || "", last_email = this.last_email; if(!last_email) { last_email = this.frm && this.frm.timeline.get_last_email(true); } if(!frappe.utils.is_html(signature)) { signature = signature.replace(/\n/g, "<br>"); } if(this.txt) { this.message = this.txt + (this.message ? ("<br><br>" + this.message) : ""); } if(this.real_name) { this.message = '<p>'+__('Dear') +' ' + this.real_name + ",</p><!-- salutation-ends --><br>" + (this.message || ""); } var reply = (this.message || "") + (signature ? ("<br>" + signature) : ""); var content = ''; if(last_email) { var last_email_content = last_email.original_comment || last_email.content; last_email_content = last_email_content .replace(/&lt;meta[\s\S]*meta&gt;/g, '') // remove <meta> tags .replace(/&lt;style[\s\S]*&lt;\/style&gt;/g, ''); // // remove <style> tags content = '<div><br></div>' + reply + "<br><!-- original-reply --><br>" + '<blockquote>' + '<p>' + __("On {0}, {1} wrote:", [frappe.datetime.global_date_format(last_email.communication_date) , last_email.sender]) + '</p>' + last_email_content + '<blockquote>'; } else { content = "<div><br></div>" + reply; } fields.content.set_value(content); }, setup_awesomplete: function() { var me = this; [ this.dialog.fields_dict.recipients.input, this.dialog.fields_dict.cc.input, this.dialog.fields_dict.bcc.input ].map(function(input) { me.setup_awesomplete_for_input(input); }); }, setup_awesomplete_for_input: function(input) { function split(val) { return val.split( /,\s*/ ); } function extractLast(term) { return split(term).pop(); } var awesomplete = new Awesomplete(input, { minChars: 0, maxItems: 99, autoFirst: true, list: [], item: function(item, input) { return $('<li>').text(item.value).get(0); }, filter: function(text, input) { return true }, replace: function(text) { var before = this.input.value.match(/^.+,\s*|/)[0]; this.input.value = before + text + ", "; } }); var delay_timer; var $input = $(input); $input.on("input", function(e) { clearTimeout(delay_timer); delay_timer = setTimeout(function() { var term = e.target.value; frappe.call({ method:'frappe.email.get_contact_list', args: { 'txt': extractLast(term) || '%' }, quiet: true, callback: function(r) { awesomplete.list = r.message || []; } }); },250); }); } });
Allow developers to choose attachments (#4477) * Allow developers to choose attachments This change allows developers to choose attachments, even if there is a cur_frm object. * Update communication.js * Merge this.attachments and form attachments * fix codacy
frappe/public/js/frappe/views/communication.js
Allow developers to choose attachments (#4477)
<ide><path>rappe/public/js/frappe/views/communication.js <ide> var fields = this.dialog.fields_dict; <ide> var attach = $(fields.select_attachments.wrapper).find(".attach-list").empty(); <ide> <del> if (cur_frm){ <del> var files = cur_frm.get_files(); <del> }else { <del> var files = this.attachments <del> } <add> var files = []; <add> if (this.attachments && this.attachments.length) { <add> files = files.concat(this.attachments); <add> } <add> if (cur_frm) { <add> files = files.concat(cur_frm.get_files()); <add> } <add> <ide> if(files.length) { <ide> $.each(files, function(i, f) { <ide> if (!f.file_name) return;
Java
apache-2.0
6b3c1b2aebe8998296791d2cca704f09de1ed09e
0
huyongqiang/Android-ObservableScrollView,SOFTPOWER1991/Android-ObservableScrollView,mRogach/Android-ObservableScrollView,DeathPluto/Android-ObservableScrollView,admin-zhx/Android-ObservableScrollView,IsFei/Android-ObservableScrollView,MMCBen/Android-ObservableScrollView,RyanTech/Android-ObservableScrollView,MatanZari/Android-ObservableScrollView,moon-sky/Android-ObservableScrollView,jrlinforce/Android-ObservableScrollView,yulongxiao/Android-ObservableScrollView,huyongqiang/Android-ObservableScrollView,crazywenza/Android-ObservableScrollView,fufu100/Android-ObservableScrollView,Finderchangchang/Android-ObservableScrollView,jmquintana/-git-clone-https-github.com-ksoichiro-Android-ObservableScrollView,qingsong-xu/Android-ObservableScrollView,cgpllx/Android-ObservableScrollView,309746069/Android-ObservableScrollView,RyanTech/Android-ObservableScrollView,Ryan---Yang/Android-ObservableScrollView,liuyingwen/Android-ObservableScrollView,msdgwzhy6/Android-ObservableScrollView,peng9627/Android-ObservableScrollView,zeetherocker/Android-ObservableScrollView,rajendravermardevelopers/Android-ObservableScrollView,fufu100/Android-ObservableScrollView,github0224/Android-ObservableScrollView,yulongxiao/Android-ObservableScrollView,jmquintana/-git-clone-https-github.com-ksoichiro-Android-ObservableScrollView,cgpllx/Android-ObservableScrollView,hnyer/Android-ObservableScrollView,rayzone107/Android-ObservableScrollView,yoslabs/Android-ObservableScrollView,tks-dp/Android-ObservableScrollView,ta893115871/Android-ObservableScrollView,admin-zhx/Android-ObservableScrollView,moon-sky/Android-ObservableScrollView,numa08/Android-ObservableScrollView,mRogach/Android-ObservableScrollView,github0224/Android-ObservableScrollView,DeathPluto/Android-ObservableScrollView,gnr/Android-ObservableScrollView,silent-nischal/Android-ObservableScrollView,rayzone107/Android-ObservableScrollView,huyongqiang/Android-ObservableScrollView,YouthAndra/Android-ObservableScrollView,YouthAndra/Android-ObservableScrollView,farrywen/Android-ObservableScrollView,YouthAndra/Android-ObservableScrollView,peng9627/Android-ObservableScrollView,DeathPluto/Android-ObservableScrollView,jmquintana/prueba,liuyingwen/Android-ObservableScrollView,fufu100/Android-ObservableScrollView,ksoichiro/Android-ObservableScrollView,ylfonline/Android-ObservableScrollView,jrlinforce/Android-ObservableScrollView,qingsong-xu/Android-ObservableScrollView,31H0B1eV/Android-ObservableScrollView,ppk5457/Android-ObservableScrollView,Finderchangchang/Android-ObservableScrollView,huyongqiang/Android-ObservableScrollView,ghbhaha/Android-ObservableScrollView,arunlodhi/Android-ObservableScrollView,Finderchangchang/Android-ObservableScrollView,RyanTech/Android-ObservableScrollView,zzuli4519/Android-ObservableScrollView,460611929/Android-ObservableScrollView,admin-zhx/Android-ObservableScrollView,toiroakr/Android-ObservableScrollView,github0224/Android-ObservableScrollView,jiyuren/Android-ObservableScrollView,kyanro/Android-ObservableScrollView,ylfonline/Android-ObservableScrollView,SOFTPOWER1991/Android-ObservableScrollView,msdgwzhy6/Android-ObservableScrollView,10045125/Android-ObservableScrollView,liwangdong/Android-ObservableScrollView,jmquintana/-git-clone-https-github.com-ksoichiro-Android-ObservableScrollView,401610239/Android-ObservableScrollView,31H0B1eV/Android-ObservableScrollView,xiaomaguoguo/Android-ObservableScrollView,jrlinforce/Android-ObservableScrollView,ta893115871/Android-ObservableScrollView,Balavenkatesh/codegeek,jmquintana/prueba,farrywen/Android-ObservableScrollView,kyanro/Android-ObservableScrollView,xiebaiyuan/Android-ObservableScrollView,kyanro/Android-ObservableScrollView,luoxiaoshenghustedu/Android-ObservableScrollView,harichen/Android-ObservableScrollView,huy510cnt/ObservableScrollView,bboyfeiyu/Android-ObservableScrollView,ghbhaha/Android-ObservableScrollView,liwangdong/Android-ObservableScrollView,pedram7sd/Android-ObservableScrollView,pedram7sd/Android-ObservableScrollView,460611929/Android-ObservableScrollView,jmquintana/prueba,Balavenkatesh/codegeek,peng9627/Android-ObservableScrollView,hejunbinlan/Android-ObservableScrollView,ppk5457/Android-ObservableScrollView,rajendravermardevelopers/Android-ObservableScrollView,joyoyao/Android-ObservableScrollView,liwangdong/Android-ObservableScrollView,huhu/Android-ObservableScrollView,jaohoang/Android-ObservableScrollView,tks-dp/Android-ObservableScrollView,liuyingwen/Android-ObservableScrollView,yulongxiao/Android-ObservableScrollView,YouthAndra/Android-ObservableScrollView,jaohoang/Android-ObservableScrollView,extinguish/Android-ObservableScrollView,toiroakr/Android-ObservableScrollView,crazywenza/Android-ObservableScrollView,a642500/Android-ObservableScrollView,tks-dp/Android-ObservableScrollView,hnyer/Android-ObservableScrollView,moon-sky/Android-ObservableScrollView,YongHuiLuo/Android-ObservableScrollView,DeathPluto/Android-ObservableScrollView,snice/Android-ObservableScrollView,harichen/Android-ObservableScrollView,xiebaiyuan/Android-ObservableScrollView,xiebaiyuan/Android-ObservableScrollView,RyanTech/Android-ObservableScrollView,309746069/Android-ObservableScrollView,yoslabs/Android-ObservableScrollView,YongHuiLuo/Android-ObservableScrollView,309746069/Android-ObservableScrollView,hejunbinlan/Android-ObservableScrollView,yswheye/Android-ObservableScrollView,18611480882/Android-ObservableScrollView,jiyuren/Android-ObservableScrollView,farrywen/Android-ObservableScrollView,bensonss/Android-ObservableScrollView,ppk5457/Android-ObservableScrollView,Ryan---Yang/Android-ObservableScrollView,prashantmaurice/Android-ObservableScrollView,mRogach/Android-ObservableScrollView,github0224/Android-ObservableScrollView,ghbhaha/Android-ObservableScrollView,snice/Android-ObservableScrollView,rajendravermardevelopers/Android-ObservableScrollView,IsFei/Android-ObservableScrollView,jmquintana/prueba,ksoichiro/Android-ObservableScrollView,xiaomaguoguo/Android-ObservableScrollView,prashantmaurice/Android-ObservableScrollView,401610239/Android-ObservableScrollView,extinguish/Android-ObservableScrollView,yswheye/Android-ObservableScrollView,YongHuiLuo/Android-ObservableScrollView,yoslabs/Android-ObservableScrollView,fufu100/Android-ObservableScrollView,jaohoang/Android-ObservableScrollView,silent-nischal/Android-ObservableScrollView,rayzone107/Android-ObservableScrollView,ta893115871/Android-ObservableScrollView,hckhanh/Android-ObservableScrollView,hnyer/Android-ObservableScrollView,ksoichiro/Android-ObservableScrollView,harichen/Android-ObservableScrollView,yoslabs/Android-ObservableScrollView,IsFei/Android-ObservableScrollView,liwangdong/Android-ObservableScrollView,zeetherocker/Android-ObservableScrollView,SOFTPOWER1991/Android-ObservableScrollView,MatanZari/Android-ObservableScrollView,31H0B1eV/Android-ObservableScrollView,huhu/Android-ObservableScrollView,460611929/Android-ObservableScrollView,Ryan---Yang/Android-ObservableScrollView,huhu/Android-ObservableScrollView,a642500/Android-ObservableScrollView,xiaomaguoguo/Android-ObservableScrollView,hejunbinlan/Android-ObservableScrollView,tks-dp/Android-ObservableScrollView,pedram7sd/Android-ObservableScrollView,jrlinforce/Android-ObservableScrollView,Ryan---Yang/Android-ObservableScrollView,peng9627/Android-ObservableScrollView,AlekseyMak/ObservableScrollView,zeetherocker/Android-ObservableScrollView,numa08/Android-ObservableScrollView,MatanZari/Android-ObservableScrollView,arunlodhi/Android-ObservableScrollView,snice/Android-ObservableScrollView,ksoichiro/Android-ObservableScrollView,AlekseyMak/ObservableScrollView,ylfonline/Android-ObservableScrollView,hckhanh/Android-ObservableScrollView,xiaomaguoguo/Android-ObservableScrollView,admin-zhx/Android-ObservableScrollView,rayzone107/Android-ObservableScrollView,31H0B1eV/Android-ObservableScrollView,MMCBen/Android-ObservableScrollView,xiebaiyuan/Android-ObservableScrollView,harichen/Android-ObservableScrollView,MMCBen/Android-ObservableScrollView,luoxiaoshenghustedu/Android-ObservableScrollView,pedram7sd/Android-ObservableScrollView,a642500/Android-ObservableScrollView,qingsong-xu/Android-ObservableScrollView,silent-nischal/Android-ObservableScrollView,yswheye/Android-ObservableScrollView,401610239/Android-ObservableScrollView,551780457/Android-ObservableScrollView,extinguish/Android-ObservableScrollView,MMCBen/Android-ObservableScrollView,ppk5457/Android-ObservableScrollView,luoxiaoshenghustedu/Android-ObservableScrollView,ylfonline/Android-ObservableScrollView,401610239/Android-ObservableScrollView,yulongxiao/Android-ObservableScrollView,yswheye/Android-ObservableScrollView,mRogach/Android-ObservableScrollView,luoxiaoshenghustedu/Android-ObservableScrollView,farrywen/Android-ObservableScrollView,extinguish/Android-ObservableScrollView,SOFTPOWER1991/Android-ObservableScrollView,moon-sky/Android-ObservableScrollView,YongHuiLuo/Android-ObservableScrollView,MatanZari/Android-ObservableScrollView,460611929/Android-ObservableScrollView,309746069/Android-ObservableScrollView,551780457/Android-ObservableScrollView,numa08/Android-ObservableScrollView,jiyuren/Android-ObservableScrollView,crazywenza/Android-ObservableScrollView,msdgwzhy6/Android-ObservableScrollView,voiceofnet2012/Android-ObservableScrollView,rajendravermardevelopers/Android-ObservableScrollView,Finderchangchang/Android-ObservableScrollView,IsFei/Android-ObservableScrollView,ta893115871/Android-ObservableScrollView,hckhanh/Android-ObservableScrollView,snice/Android-ObservableScrollView,Balavenkatesh/codegeek,huhu/Android-ObservableScrollView,cgpllx/Android-ObservableScrollView,jmquintana/-git-clone-https-github.com-ksoichiro-Android-ObservableScrollView,prashantmaurice/Android-ObservableScrollView,0359xiaodong/Android-ObservableScrollView,huy510cnt/ObservableScrollView,hnyer/Android-ObservableScrollView,hejunbinlan/Android-ObservableScrollView,msdgwzhy6/Android-ObservableScrollView,kyanro/Android-ObservableScrollView,cgpllx/Android-ObservableScrollView,arunlodhi/Android-ObservableScrollView,silent-nischal/Android-ObservableScrollView,zeetherocker/Android-ObservableScrollView,ghbhaha/Android-ObservableScrollView,qingsong-xu/Android-ObservableScrollView,a642500/Android-ObservableScrollView,toiroakr/Android-ObservableScrollView,jaohoang/Android-ObservableScrollView,crazywenza/Android-ObservableScrollView,liuyingwen/Android-ObservableScrollView,jiyuren/Android-ObservableScrollView,arunlodhi/Android-ObservableScrollView,prashantmaurice/Android-ObservableScrollView,Balavenkatesh/codegeek,toiroakr/Android-ObservableScrollView,numa08/Android-ObservableScrollView,hckhanh/Android-ObservableScrollView
/* * Copyright 2014 Soichiro Kashima * * 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.github.ksoichiro.android.observablescrollview; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.SparseIntArray; import android.view.MotionEvent; import android.view.View; import com.github.ksoichiro.android.observablescrollview.internal.LogUtils; public class ObservableRecyclerView extends RecyclerView { private static final String TAG = ObservableRecyclerView.class.getSimpleName(); private ObservableScrollViewCallbacks mCallbacks; private int mPrevFirstVisiblePosition; private int mPrevFirstVisibleChildHeight = -1; private int mPrevScrolledChildrenHeight; private SparseIntArray mChildrenHeights; private int mPrevScrollY; private int mScrollY; private ScrollState mScrollState; private boolean mFirstScroll; private boolean mDragging; public ObservableRecyclerView(Context context) { super(context); init(); } public ObservableRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ObservableRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; mPrevFirstVisiblePosition = ss.prevFirstVisiblePosition; mPrevFirstVisibleChildHeight = ss.prevFirstVisibleChildHeight; mPrevScrolledChildrenHeight = ss.prevScrolledChildrenHeight; mPrevScrollY = ss.prevScrollY; mScrollY = ss.scrollY; mChildrenHeights = ss.childrenHeights; super.onRestoreInstanceState(ss.getSuperState()); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.prevFirstVisiblePosition = mPrevFirstVisiblePosition; ss.prevFirstVisibleChildHeight = mPrevFirstVisibleChildHeight; ss.prevScrolledChildrenHeight = mPrevScrolledChildrenHeight; ss.prevScrollY = mPrevScrollY; ss.scrollY = mScrollY; ss.childrenHeights = mChildrenHeights; return ss; } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mCallbacks != null) { if (getChildCount() > 0) { int firstVisiblePosition = getChildPosition(getChildAt(0)); int lastVisiblePosition = getChildPosition(getChildAt(getChildCount() - 1)); for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++) { if (mChildrenHeights.indexOfKey(i) < 0 || getChildAt(j).getHeight() != mChildrenHeights.get(i)) { mChildrenHeights.put(i, getChildAt(j).getHeight()); } } View firstVisibleChild = getChildAt(0); if (firstVisibleChild != null) { if (mPrevFirstVisiblePosition < firstVisiblePosition) { // scroll down int skippedChildrenHeight = 0; if (firstVisiblePosition - mPrevFirstVisiblePosition != 1) { LogUtils.v(TAG, "Skipped some children while scrolling down: " + (firstVisiblePosition - mPrevFirstVisiblePosition)); for (int i = firstVisiblePosition - 1; i > mPrevFirstVisiblePosition; i--) { if (0 < mChildrenHeights.indexOfKey(i)) { skippedChildrenHeight += mChildrenHeights.get(i); LogUtils.v(TAG, "Calculate skipped child height at " + i + ": " + mChildrenHeights.get(i)); } else { LogUtils.v(TAG, "Could not calculate skipped child height at " + i); } } } mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight + skippedChildrenHeight; mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight(); } else if (firstVisiblePosition < mPrevFirstVisiblePosition) { // scroll up int skippedChildrenHeight = 0; if (mPrevFirstVisiblePosition - firstVisiblePosition != 1) { LogUtils.v(TAG, "Skipped some children while scrolling up: " + (mPrevFirstVisiblePosition - firstVisiblePosition)); for (int i = mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--) { if (0 < mChildrenHeights.indexOfKey(i)) { skippedChildrenHeight += mChildrenHeights.get(i); LogUtils.v(TAG, "Calculate skipped child height at " + i + ": " + mChildrenHeights.get(i)); } else { LogUtils.v(TAG, "Could not calculate skipped child height at " + i); } } } mPrevScrolledChildrenHeight -= firstVisibleChild.getHeight() + skippedChildrenHeight; mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight(); } else if (firstVisiblePosition == 0) { mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight(); } if (mPrevFirstVisibleChildHeight < 0) { mPrevFirstVisibleChildHeight = 0; } mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.getTop(); mPrevFirstVisiblePosition = firstVisiblePosition; LogUtils.v(TAG, "first: " + firstVisiblePosition + " scrollY: " + mScrollY + " first height: " + firstVisibleChild.getHeight() + " first top: " + firstVisibleChild.getTop()); mCallbacks.onScrollChanged(mScrollY, mFirstScroll, mDragging); if (mFirstScroll) { mFirstScroll = false; } if (mPrevScrollY < mScrollY) { //down mScrollState = ScrollState.UP; } else if (mScrollY < mPrevScrollY) { //up mScrollState = ScrollState.DOWN; } else { mScrollState = ScrollState.STOP; } mPrevScrollY = mScrollY; } else { LogUtils.v(TAG, "first: " + firstVisiblePosition); } } } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mCallbacks != null) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: mFirstScroll = mDragging = true; mCallbacks.onDownMotionEvent(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mDragging = false; mCallbacks.onUpOrCancelMotionEvent(mScrollState); break; } } return super.onTouchEvent(ev); } public void setScrollViewCallbacks(ObservableScrollViewCallbacks listener) { mCallbacks = listener; } public int getCurrentScrollY() { return mScrollY; } private void init() { mChildrenHeights = new SparseIntArray(); } static class SavedState extends BaseSavedState { int prevFirstVisiblePosition; int prevFirstVisibleChildHeight = -1; int prevScrolledChildrenHeight; int prevScrollY; int scrollY; SparseIntArray childrenHeights; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); prevFirstVisiblePosition = in.readInt(); prevFirstVisibleChildHeight = in.readInt(); prevScrolledChildrenHeight = in.readInt(); prevScrollY = in.readInt(); scrollY = in.readInt(); childrenHeights = new SparseIntArray(); final int numOfChildren = in.readInt(); if (0 < numOfChildren) { for (int i = 0; i < numOfChildren; i++) { final int key = in.readInt(); final int value = in.readInt(); childrenHeights.put(key, value); } } } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(prevFirstVisiblePosition); out.writeInt(prevFirstVisibleChildHeight); out.writeInt(prevScrolledChildrenHeight); out.writeInt(prevScrollY); out.writeInt(scrollY); final int numOfChildren = childrenHeights == null ? 0 : childrenHeights.size(); out.writeInt(numOfChildren); if (0 < numOfChildren) { for (int i = 0; i < numOfChildren; i++) { out.writeInt(childrenHeights.keyAt(i)); out.writeInt(childrenHeights.valueAt(i)); } } } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
observablescrollview/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableRecyclerView.java
/* * Copyright 2014 Soichiro Kashima * * 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.github.ksoichiro.android.observablescrollview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.SparseIntArray; import android.view.MotionEvent; import android.view.View; import com.github.ksoichiro.android.observablescrollview.internal.LogUtils; public class ObservableRecyclerView extends RecyclerView { private static final String TAG = ObservableRecyclerView.class.getSimpleName(); private ObservableScrollViewCallbacks mCallbacks; private int mPrevFirstVisiblePosition; private int mPrevFirstVisibleChildHeight = -1; private int mPrevScrolledChildrenHeight; private SparseIntArray mChildrenHeights; private int mPrevScrollY; private int mScrollY; private ScrollState mScrollState; private boolean mFirstScroll; private boolean mDragging; public ObservableRecyclerView(Context context) { super(context); init(); } public ObservableRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ObservableRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mCallbacks != null) { if (getChildCount() > 0) { int firstVisiblePosition = getChildPosition(getChildAt(0)); int lastVisiblePosition = getChildPosition(getChildAt(getChildCount() - 1)); for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++) { if (mChildrenHeights.indexOfKey(i) < 0 || getChildAt(j).getHeight() != mChildrenHeights.get(i)) { mChildrenHeights.put(i, getChildAt(j).getHeight()); } } View firstVisibleChild = getChildAt(0); if (firstVisibleChild != null) { if (mPrevFirstVisiblePosition < firstVisiblePosition) { // scroll down int skippedChildrenHeight = 0; if (firstVisiblePosition - mPrevFirstVisiblePosition != 1) { LogUtils.v(TAG, "Skipped some children while scrolling down: " + (firstVisiblePosition - mPrevFirstVisiblePosition)); for (int i = firstVisiblePosition - 1; i > mPrevFirstVisiblePosition; i--) { if (0 < mChildrenHeights.indexOfKey(i)) { skippedChildrenHeight += mChildrenHeights.get(i); LogUtils.v(TAG, "Calculate skipped child height at " + i + ": " + mChildrenHeights.get(i)); } else { LogUtils.v(TAG, "Could not calculate skipped child height at " + i); } } } mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight + skippedChildrenHeight; mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight(); } else if (firstVisiblePosition < mPrevFirstVisiblePosition) { // scroll up int skippedChildrenHeight = 0; if (mPrevFirstVisiblePosition - firstVisiblePosition != 1) { LogUtils.v(TAG, "Skipped some children while scrolling up: " + (mPrevFirstVisiblePosition - firstVisiblePosition)); for (int i = mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--) { if (0 < mChildrenHeights.indexOfKey(i)) { skippedChildrenHeight += mChildrenHeights.get(i); LogUtils.v(TAG, "Calculate skipped child height at " + i + ": " + mChildrenHeights.get(i)); } else { LogUtils.v(TAG, "Could not calculate skipped child height at " + i); } } } mPrevScrolledChildrenHeight -= firstVisibleChild.getHeight() + skippedChildrenHeight; mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight(); } else if (firstVisiblePosition == 0) { mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight(); } if (mPrevFirstVisibleChildHeight < 0) { mPrevFirstVisibleChildHeight = 0; } mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.getTop(); mPrevFirstVisiblePosition = firstVisiblePosition; LogUtils.v(TAG, "first: " + firstVisiblePosition + " scrollY: " + mScrollY + " first height: " + firstVisibleChild.getHeight() + " first top: " + firstVisibleChild.getTop()); mCallbacks.onScrollChanged(mScrollY, mFirstScroll, mDragging); if (mFirstScroll) { mFirstScroll = false; } if (mPrevScrollY < mScrollY) { //down mScrollState = ScrollState.UP; } else if (mScrollY < mPrevScrollY) { //up mScrollState = ScrollState.DOWN; } else { mScrollState = ScrollState.STOP; } mPrevScrollY = mScrollY; } else { LogUtils.v(TAG, "first: " + firstVisiblePosition); } } } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mCallbacks != null) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: mFirstScroll = mDragging = true; mCallbacks.onDownMotionEvent(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mDragging = false; mCallbacks.onUpOrCancelMotionEvent(mScrollState); break; } } return super.onTouchEvent(ev); } public void setScrollViewCallbacks(ObservableScrollViewCallbacks listener) { mCallbacks = listener; } public int getCurrentScrollY() { return mScrollY; } private void init() { mChildrenHeights = new SparseIntArray(); } }
Fix that the scroll position of ObservableRecyclerView is not restored after rotating the screen.
observablescrollview/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableRecyclerView.java
Fix that the scroll position of ObservableRecyclerView is not restored after rotating the screen.
<ide><path>bservablescrollview/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableRecyclerView.java <ide> package com.github.ksoichiro.android.observablescrollview; <ide> <ide> import android.content.Context; <add>import android.os.Parcel; <add>import android.os.Parcelable; <ide> import android.support.v7.widget.RecyclerView; <ide> import android.util.AttributeSet; <ide> import android.util.SparseIntArray; <ide> public ObservableRecyclerView(Context context, AttributeSet attrs, int defStyle) { <ide> super(context, attrs, defStyle); <ide> init(); <add> } <add> <add> @Override <add> public void onRestoreInstanceState(Parcelable state) { <add> SavedState ss = (SavedState) state; <add> mPrevFirstVisiblePosition = ss.prevFirstVisiblePosition; <add> mPrevFirstVisibleChildHeight = ss.prevFirstVisibleChildHeight; <add> mPrevScrolledChildrenHeight = ss.prevScrolledChildrenHeight; <add> mPrevScrollY = ss.prevScrollY; <add> mScrollY = ss.scrollY; <add> mChildrenHeights = ss.childrenHeights; <add> super.onRestoreInstanceState(ss.getSuperState()); <add> } <add> <add> @Override <add> public Parcelable onSaveInstanceState() { <add> Parcelable superState = super.onSaveInstanceState(); <add> SavedState ss = new SavedState(superState); <add> ss.prevFirstVisiblePosition = mPrevFirstVisiblePosition; <add> ss.prevFirstVisibleChildHeight = mPrevFirstVisibleChildHeight; <add> ss.prevScrolledChildrenHeight = mPrevScrolledChildrenHeight; <add> ss.prevScrollY = mPrevScrollY; <add> ss.scrollY = mScrollY; <add> ss.childrenHeights = mChildrenHeights; <add> return ss; <ide> } <ide> <ide> @Override <ide> private void init() { <ide> mChildrenHeights = new SparseIntArray(); <ide> } <add> <add> static class SavedState extends BaseSavedState { <add> int prevFirstVisiblePosition; <add> int prevFirstVisibleChildHeight = -1; <add> int prevScrolledChildrenHeight; <add> int prevScrollY; <add> int scrollY; <add> SparseIntArray childrenHeights; <add> <add> SavedState(Parcelable superState) { <add> super(superState); <add> } <add> <add> private SavedState(Parcel in) { <add> super(in); <add> prevFirstVisiblePosition = in.readInt(); <add> prevFirstVisibleChildHeight = in.readInt(); <add> prevScrolledChildrenHeight = in.readInt(); <add> prevScrollY = in.readInt(); <add> scrollY = in.readInt(); <add> childrenHeights = new SparseIntArray(); <add> final int numOfChildren = in.readInt(); <add> if (0 < numOfChildren) { <add> for (int i = 0; i < numOfChildren; i++) { <add> final int key = in.readInt(); <add> final int value = in.readInt(); <add> childrenHeights.put(key, value); <add> } <add> } <add> } <add> <add> @Override <add> public void writeToParcel(Parcel out, int flags) { <add> super.writeToParcel(out, flags); <add> out.writeInt(prevFirstVisiblePosition); <add> out.writeInt(prevFirstVisibleChildHeight); <add> out.writeInt(prevScrolledChildrenHeight); <add> out.writeInt(prevScrollY); <add> out.writeInt(scrollY); <add> final int numOfChildren = childrenHeights == null ? 0 : childrenHeights.size(); <add> out.writeInt(numOfChildren); <add> if (0 < numOfChildren) { <add> for (int i = 0; i < numOfChildren; i++) { <add> out.writeInt(childrenHeights.keyAt(i)); <add> out.writeInt(childrenHeights.valueAt(i)); <add> } <add> } <add> } <add> <add> public static final Parcelable.Creator<SavedState> CREATOR <add> = new Parcelable.Creator<SavedState>() { <add> @Override <add> public SavedState createFromParcel(Parcel in) { <add> return new SavedState(in); <add> } <add> <add> @Override <add> public SavedState[] newArray(int size) { <add> return new SavedState[size]; <add> } <add> }; <add> } <ide> }
JavaScript
apache-2.0
b1f26b9121ebbaa6788736e6ae014976c8c6b426
0
ringo/ringojs,ringo/ringojs,ringo/ringojs,ringo/ringojs
/** * @fileOverview This module provides response helper functions for composing * JSGI response objects. For more flexibility the `JsgiResponse` is chainable. */ const fs = require("fs"); var {parseRange, canonicalRanges} = require("ringo/utils/http"); var {mimeType} = require("ringo/mime"); var {Stream} = require("io"); var {AsyncResponse} = require("./connector"); const HYPHEN = new ByteString("-", "ASCII"); const CRLF = new ByteString("\r\n", "ASCII"); const EMPTY_LINE = new ByteString("\r\n\r\n", "ASCII"); /** * A wrapper around a JSGI response object. `JsgiResponse` is chainable. * @param {Object} base a base object for the new JSGI response with the * initial <code>status</code>, <code>headers</code> and * <code>body</code> properties. * @constructor * @example // Using the constructor * var {JsgiResponse} = require('ringo/jsgi/response'); * return (new JsgiResponse()).text('Hello World!').setCharset('ISO-8859-1'); * * // Using a static helper * var response = require('ringo/jsgi/response'); * return response.json({'foo': 'bar'}).error(); */ var JsgiResponse = exports.JsgiResponse = function(base) { // Internal use only /** @ignore */ Object.defineProperty(this, "_charset", { value: "utf-8", writable: true, }); this.status = 200; this.headers = { "content-type": "text/plain; charset=" + this._charset }; this.body = [""]; if (base !== undefined) { this.status = base.status || this.status; this.headers = base.headers || this.headers; this.body = base.body || this.body; } }; /** * Set the JSGI response status. This does not commit the * request and continues the JsgiReponse chain. * @param {Number} code the status code to use * @returns {JsgiResponse} JSGI response with the new status code */ Object.defineProperty(JsgiResponse.prototype, "setStatus", { value: function(code) { this.status = code; return this; } }); /** * Set the JSGI response content-type to 'text/plain' with the string as response body. * @param {String...} text... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/plain' */ Object.defineProperty(JsgiResponse.prototype, "text", { value: function() { this.headers["content-type"] = "text/plain; charset=" + this._charset; this.body = Array.prototype.slice.call(arguments).map(String); return this; } }); /** * Set the JSGI response content-type to 'text/html' with the string as response body. * @param {String...} html... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/html' */ Object.defineProperty(JsgiResponse.prototype, "html", { value: function() { this.headers["content-type"] = "text/html; charset=" + this._charset; this.body = Array.prototype.slice.call(arguments).map(String); return this; } }); /** * Create a JSGI response with content-type 'application/json' with the JSON * representation of the given object as response body. * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/json' */ Object.defineProperty(JsgiResponse.prototype, "json", { value: function(object) { this.headers["content-type"] = "application/json; charset=" + this._charset; this.body = [JSON.stringify(object)]; return this; } }); /** * Create a JSGI response with content-type 'application/javascript' with the JSONP * representation of the given object as response body wrapped by the callback name. * @param {String} callback the callback function name for a JSONP request * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/javascript' */ Object.defineProperty(JsgiResponse.prototype, "jsonp", { value: function(callback, object) { this.headers["content-type"] = "application/javascript; charset=" + this._charset; this.body = [callback, "(", JSON.stringify(object), ");"]; return this; } }); /** * Create a JSGI response with content-type 'application/xml' with the given * XML as response body. * @param {XML|String} xml an XML document * @returns {JsgiResponse} JSGI response with content-type 'application/xml' */ Object.defineProperty(JsgiResponse.prototype, "xml", { value: function(xml) { this.headers["content-type"] = "application/xml"; this.body = [(typeof xml === 'xml' ? xml.toXMLString() : String(xml))]; return this; } }); /** * Create a JSGI response with a stream as response body. * @param {Stream} stream the stream to write * @param {String} contentType optional MIME type. If not defined, * the MIME type is <code>application/octet-stream</code>. * @returns {JsgiResponse} JSGI response */ Object.defineProperty(JsgiResponse.prototype, "stream", { value: function (stream, contentType) { if (typeof stream.readable !== "function" || typeof stream.forEach !== "function") { throw Error("Wrong argument for stream response!"); } if (!stream.readable()) { throw Error("Stream is not readable!"); } this.headers["content-type"] = contentType || "application/octet-stream"; this.body = stream; return this; } }); /** * Create a JSGI response with a <code>Binary</code> object as response body. * @param {ByteString|ByteArray} binary the binary object to write * @param {String} contentType optional MIME type. If not defined, * the MIME type is <code>application/octet-stream</code>. * @returns {JsgiResponse} JSGI response */ Object.defineProperty(JsgiResponse.prototype, "binary", { value: function (binary, contentType) { if (!(binary instanceof Binary)) { throw Error("Wrong argument for binary response!"); } this.headers["content-type"] = contentType || "application/octet-stream"; this.body = { forEach: function(fn) { fn(binary); } }; return this; } }); /** * Set the character encoding used for text responses. * @param {String} charsetName the encoding to use. * @returns {JsgiResponse} JSGI response with the given charset */ Object.defineProperty(JsgiResponse.prototype, "setCharset", { value: function(charsetName) { this._charset = charsetName; var ct = this.headers["content-type"]; if (ct) { this.headers["content-type"] = ct.substring(0, ct.indexOf("; charset=")) + "; charset=" + this._charset; } return this; } }); /** * Merge the given object into the headers of the JSGI response. * @param {Object} headers new header fields to merge with the current ones. * @returns {JsgiResponse} JSGI response with the new headers */ Object.defineProperty(JsgiResponse.prototype, "addHeaders", { value: function(additionalHeaders) { for (let fieldName in additionalHeaders) { let existingValues = this.headers[fieldName]; // check if the header is already set if (existingValues === undefined) { if (additionalHeaders[fieldName] instanceof Array) { // add multiple header values as an array of strings this.headers[fieldName] = additionalHeaders[fieldName].map(function(headerValue) { return String(headerValue); }); } else { // single-valued header as arbitrary string this.headers[fieldName] = String(additionalHeaders[fieldName]); } } else if (typeof existingValues === "string") { // the header has been set already exactly once, so expand it to an array this.headers[fieldName] = [existingValues, String(additionalHeaders[fieldName])]; } else { // the header is already an array of multiple values --> push new value this.headers[fieldName].push(String(additionalHeaders[fieldName])); } } return this; } }); /** * Sets the HTTP status to 200. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "ok", { value: function() { this.status = 200; return this; } }); /** * Sets the HTTP status to 201. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "created", { value: function() { this.status = 201; return this; } }); /** * Sets the HTTP status to 400. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "bad", { value: function() { this.status = 400; return this; } }); /** * Sets the HTTP status to 401. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "unauthorized", { value: function() { this.status = 401; return this; } }); /** * Sets the HTTP status to 403. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "forbidden", { value: function() { this.status = 403; return this; } }); /** * Sets the HTTP status to 404. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "notFound", { value: function() { this.status = 404; return this; } }); /** * Sets the HTTP status to 410. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "gone", { value: function() { this.status = 410; return this; } }); /** * Sets the HTTP status to 500. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "error", { value: function() { this.status = 500; return this; } }); /** * Sets the HTTP status to 503. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "unavailable", { value: function() { this.status = 503; return this; } }); /** * Create a response with HTTP status code 303 that redirects the client * to a new location. * @param {String} location the new location * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "redirect", { value: function(location) { this.status = 303; this.headers = { "location": location }; this.body = ["See other: " + location]; return this; } }); /** * Create a response with HTTP status code 304 that indicates the * document has not been modified * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "notModified", { value: function() { this.status = 304; this.headers = {}; this.body = [""]; return this; } }); /** * Static helper to create a `JsgiResponse` with the given status code. * @name setStatus * @function * @param {Number} code the status code to use * @returns {JsgiResponse} JSGI response with the new status code */ /** * Set the JSGI response content-type to 'text/plain' with the string as response body. * @param {String...} text... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/plain' * @name text * @function */ /** * Set the JSGI response content-type to 'text/html' with the string as response body. * @param {String...} html... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/html' * @name html * @function */ /** * Create a JSGI response with content-type 'application/json' with the JSON * representation of the given object as response body. * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/json' * @name json * @function */ /** * Create a JSGI response with content-type 'application/javascript' with the JSONP * representation of the given object as response body wrapped by the callback name. * @param {String} callback the callback function name for a JSONP request * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/javascript' * @name jsonp * @function */ /** * Create a JSGI response with content-type 'application/xml' with the given * XML as response body. * @param {XML|String} xml an XML document * @returns {JsgiResponse} JSGI response with content-type 'application/xml' * @name xml * @function */ /** * Set the character encoding used for text responses. * @param {String} charsetName the encoding to use. * @returns {JsgiResponse} JSGI response with the given charset * @name setCharset * @function */ /** * Merge the given object into the headers of the JSGI response. * @param {Object} headers new header fields to merge with the current ones. * @returns {JsgiResponse} JSGI response with the new headers * @name addHeaders * @function */ /** * Sets the HTTP status to 200. * @returns {JsgiResponse} a JSGI response object to send back * @name ok * @function */ /** * Sets the HTTP status to 201. * @returns {JsgiResponse} a JSGI response object to send back * @name created * @function */ /** * Sets the HTTP status to 400. * @returns {JsgiResponse} a JSGI response object to send back * @name bad * @function */ /** * Sets the HTTP status to 401. * @returns {JsgiResponse} a JSGI response object to send back * @name unauthorized * @function */ /** * Sets the HTTP status to 403. * @returns {JsgiResponse} a JSGI response object to send back * @name forbidden * @function */ /** * Sets the HTTP status to 404. * @returns {JsgiResponse} a JSGI response object to send back * @name notFound * @function */ /** * Sets the HTTP status to 410. * @returns {JsgiResponse} a JSGI response object to send back * @name gone * @function */ /** * Sets the HTTP status to 500. * @returns {JsgiResponse} a JSGI response object to send back * @name error * @function */ /** * Sets the HTTP status to 503. * @returns {JsgiResponse} a JSGI response object to send back * @name unavailable * @function */ /** * Create a response with HTTP status code 303 that redirects the client * to a new location. * @param {String} location the new location * @returns {JsgiResponse} a JSGI response object to send back * @name redirect * @function */ /** * Create a response with HTTP status code 304 that indicates the * document has not been modified * @returns {JsgiResponse} a JSGI response object to send back * @name notModified * @function */ // Define helper functions /** @ignore */ ["setStatus", "text", "html", "json", "jsonp", "xml", "stream", "binary", "setCharset", "addHeaders", "ok", "created", "bad", "unauthorized", "forbidden", "notFound", "gone", "error", "unavailable", "redirect", "notModified"].forEach(function(functionName) { exports[functionName] = function() { return JsgiResponse.prototype[functionName].apply((new JsgiResponse()), arguments); }; }); /** * A response representing a static resource. * @param {String|Resource} resource the resource to serve * @param {String} contentType optional MIME type. If not defined, * the MIME type is detected from the file name extension. */ exports.static = function (resource, contentType) { if (typeof resource == "string") { resource = getResource(resource); } if (!(resource instanceof org.ringojs.repository.Resource)) { throw Error("Wrong argument for static response: " + typeof(resource)); } var input; return { status: 200, headers: { "Content-Type": contentType || mimeType(resource.name) }, body: { digest: function() { return resource.lastModified().toString(36) + resource.length.toString(36); }, forEach: function(fn) { input = new Stream(resource.getInputStream()); try { input.forEach(fn); } finally { input.close(); } } } }; }; /** * An async response representing a resource as a single or multiple part response. * Multiple or overlapping byte ranges are coalesced into a canonical response range. * * @param {Object} request a JSGI request object * @param {String|Resource|Stream} representation path of a file as string, a resource, or a readable <a href="../../../io/">io.Stream</a> * @param {Number} size optional size of the resource in bytes, -1 indicates an unknown size. * @param {String} contentType optional content type to send for single range responses * @param {Number} timeout optional timeout to send back the ranges, defaults to 30 seconds, -1 indicates an infinite timeout. * @param {Number} maxRanges optional maximum number of ranges in a request, defaults to 20. Similar to Apache's <code>MaxRanges</code> directive. * @returns {AsyncResponse} async response filled with the give ranges * @see <a href="https://tools.ietf.org/html/rfc7233">RFC 7233 - Range Requests</a> * @see <a href="https://tools.ietf.org/html/rfc7233#section-6">Range Requests - Security Considerations</a> */ exports.range = function (request, representation, size, contentType, timeout, maxRanges) { // this would be an application error --> throw an exception if (!request || !request.headers || !request.headers["range"]) { throw new Error("Request is not a range request!"); } // only GET is allowed // https://tools.ietf.org/html/rfc7233#section-3.1 if (request.method !== "GET") { return new JsgiResponse().setStatus(400).text("Method not allowed."); } let stream; if (typeof representation == "string") { let localPath = fs.absolute(representation); if (!fs.exists(localPath) || !fs.isReadable(localPath)) { throw new Error("Resource does not exist or is not readable."); } if (size == null) { try { size = fs.size(localPath); } catch (e) { // ignore --> use -1 at the end } } stream = fs.openRaw(localPath, "r"); } else if (representation instanceof org.ringojs.repository.Resource) { stream = new Stream(representation.getInputStream()); if (size == null && representation.getLength != null) { size = representation.getLength(); } } else if (representation instanceof Stream) { stream = representation; } else { throw new Error("Invalid representation! Must be a path to a file, a resource, or a stream."); } if (!stream.readable()) { throw new Error("Stream must be readable!"); } const BOUNDARY = new ByteString("sjognir_doro_" + java.lang.System.identityHashCode(this).toString(36) + java.lang.System.identityHashCode(request).toString(36) + java.lang.System.identityHashCode(stream).toString(36) + (java.lang.System.currentTimeMillis() % 100000).toString(36) + (Math.random().toFixed(10).slice(2)), "ASCII"); contentType = contentType || "application/octet-stream"; maxRanges = (maxRanges != null && Number.isSafeInteger(maxRanges) && maxRanges >= 0 ? maxRanges : 20); // returns the raw ranges; might be overlapping / invalid let ranges = parseRange(request.headers["range"], size); if (ranges == null || ranges.length === 0 || ranges.length > maxRanges) { return new JsgiResponse().setStatus(416).text("Invalid Range header!"); } // make ranges canonical and check their validity // https://tools.ietf.org/html/rfc7233#section-4.3 try { ranges = canonicalRanges(ranges); } catch (e) { let invalidRangeResponse = new JsgiResponse().setStatus(416).text("Range Not Satisfiable"); if (size != null) { invalidRangeResponse.addHeaders({ "Content-Range": "bytes */" + size }); } return invalidRangeResponse; } // check if range can be fulfilled if(size != null && ranges[ranges.length - 1][1] > size) { return new JsgiResponse().setStatus(416).addHeaders({ "Content-Range": "bytes */" + size }).text("Range Not Satisfiable"); } const headers = {}; if (ranges.length > 1) { headers["Content-Type"] = "multipart/byteranges; boundary=" + BOUNDARY.decodeToString("ASCII"); } else { headers["Content-Type"] = contentType; headers["Content-Range"] = "bytes " + ranges[0].join("-") + "/" + (size >= 0 ? size : "*"); } const response = new AsyncResponse(request, (timeout || 30)); response.start(206, headers); spawn(function() { const responseBufferSize = request.env.servletResponse.getBufferSize(); let currentBytePos = 0; ranges.forEach(function(range, index, arr) { const [start, end] = range; const numBytes = end - start + 1; const rounds = Math.floor(numBytes / responseBufferSize); const restBytes = numBytes % responseBufferSize; stream.skip(start - currentBytePos); if (arr.length > 1) { if (index > 0) { response.write(CRLF); } response.write(HYPHEN); response.write(HYPHEN); response.write(BOUNDARY); response.write(CRLF); response.write("Content-Type: " + contentType); response.write(CRLF); response.write("Content-Range: bytes " + range.join("-") + "/" + (size >= 0 ? size : "*")); response.write(EMPTY_LINE); response.flush(); } for (let i = 0; i < rounds; i++) { response.write(stream.read(responseBufferSize)); response.flush(); } response.write(stream.read(restBytes)); response.flush(); currentBytePos = end + 1; }); // final boundary if (ranges.length > 1) { response.write(CRLF); response.write(HYPHEN); response.write(HYPHEN); response.write(BOUNDARY); response.write(HYPHEN); response.write(HYPHEN); } response.flush(); response.close(); }); return response; };
modules/ringo/jsgi/response.js
/** * @fileOverview This module provides response helper functions for composing * JSGI response objects. For more flexibility the `JsgiResponse` is chainable. */ const fs = require("fs"); var {parseRange, canonicalRanges} = require("ringo/utils/http"); var {mimeType} = require("ringo/mime"); var {Stream} = require("io"); var {AsyncResponse} = require("./connector"); const HYPHEN = new ByteString("-", "ASCII"); const CRLF = new ByteString("\r\n", "ASCII"); const EMPTY_LINE = new ByteString("\r\n\r\n", "ASCII"); /** * A wrapper around a JSGI response object. `JsgiResponse` is chainable. * @param {Object} base a base object for the new JSGI response with the * initial <code>status</code>, <code>headers</code> and * <code>body</code> properties. * @constructor * @example // Using the constructor * var {JsgiResponse} = require('ringo/jsgi/response'); * return (new JsgiResponse()).text('Hello World!').setCharset('ISO-8859-1'); * * // Using a static helper * var response = require('ringo/jsgi/response'); * return response.json({'foo': 'bar'}).error(); */ var JsgiResponse = exports.JsgiResponse = function(base) { // Internal use only /** @ignore */ Object.defineProperty(this, "_charset", { value: "utf-8", writable: true, }); this.status = 200; this.headers = { "content-type": "text/plain; charset=" + this._charset }; this.body = [""]; if (base !== undefined) { this.status = base.status || this.status; this.headers = base.headers || this.headers; this.body = base.body || this.body; } }; /** * Set the JSGI response status. This does not commit the * request and continues the JsgiReponse chain. * @param {Number} code the status code to use * @returns {JsgiResponse} JSGI response with the new status code */ Object.defineProperty(JsgiResponse.prototype, "setStatus", { value: function(code) { this.status = code; return this; } }); /** * Set the JSGI response content-type to 'text/plain' with the string as response body. * @param {String...} text... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/plain' */ Object.defineProperty(JsgiResponse.prototype, "text", { value: function() { this.headers["content-type"] = "text/plain; charset=" + this._charset; this.body = Array.prototype.slice.call(arguments).map(String); return this; } }); /** * Set the JSGI response content-type to 'text/html' with the string as response body. * @param {String...} html... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/html' */ Object.defineProperty(JsgiResponse.prototype, "html", { value: function() { this.headers["content-type"] = "text/html; charset=" + this._charset; this.body = Array.prototype.slice.call(arguments).map(String); return this; } }); /** * Create a JSGI response with content-type 'application/json' with the JSON * representation of the given object as response body. * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/json' */ Object.defineProperty(JsgiResponse.prototype, "json", { value: function(object) { this.headers["content-type"] = "application/json; charset=" + this._charset; this.body = [JSON.stringify(object)]; return this; } }); /** * Create a JSGI response with content-type 'application/javascript' with the JSONP * representation of the given object as response body wrapped by the callback name. * @param {String} callback the callback function name for a JSONP request * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/javascript' */ Object.defineProperty(JsgiResponse.prototype, "jsonp", { value: function(callback, object) { this.headers["content-type"] = "application/javascript; charset=" + this._charset; this.body = [callback, "(", JSON.stringify(object), ");"]; return this; } }); /** * Create a JSGI response with content-type 'application/xml' with the given * XML as response body. * @param {XML|String} xml an XML document * @returns {JsgiResponse} JSGI response with content-type 'application/xml' */ Object.defineProperty(JsgiResponse.prototype, "xml", { value: function(xml) { this.headers["content-type"] = "application/xml"; this.body = [(typeof xml === 'xml' ? xml.toXMLString() : String(xml))]; return this; } }); /** * Create a JSGI response with a stream as response body. * @param {Stream} stream the stream to write * @param {String} contentType optional MIME type. If not defined, * the MIME type is <code>application/octet-stream</code>. * @returns {JsgiResponse} JSGI response */ Object.defineProperty(JsgiResponse.prototype, "stream", { value: function (stream, contentType) { if (typeof stream.readable !== "function" || typeof stream.forEach !== "function") { throw Error("Wrong argument for stream response!"); } if (!stream.readable()) { throw Error("Stream is not readable!"); } this.headers["content-type"] = contentType || "application/octet-stream"; this.body = stream; return this; } }); /** * Create a JSGI response with a <code>Binary</code> object as response body. * @param {ByteString|ByteArray} binary the binary object to write * @param {String} contentType optional MIME type. If not defined, * the MIME type is <code>application/octet-stream</code>. * @returns {JsgiResponse} JSGI response */ Object.defineProperty(JsgiResponse.prototype, "binary", { value: function (binary, contentType) { if (!(binary instanceof Binary)) { throw Error("Wrong argument for binary response!"); } this.headers["content-type"] = contentType || "application/octet-stream"; this.body = { forEach: function(fn) { fn(binary); } }; return this; } }); /** * Set the character encoding used for text responses. * @param {String} charsetName the encoding to use. * @returns {JsgiResponse} JSGI response with the given charset */ Object.defineProperty(JsgiResponse.prototype, "setCharset", { value: function(charsetName) { this._charset = charsetName; var ct = this.headers["content-type"]; if (ct) { this.headers["content-type"] = ct.substring(0, ct.indexOf("; charset=")) + "; charset=" + this._charset; } return this; } }); /** * Merge the given object into the headers of the JSGI response. * @param {Object} headers new header fields to merge with the current ones. * @returns {JsgiResponse} JSGI response with the new headers */ Object.defineProperty(JsgiResponse.prototype, "addHeaders", { value: function(additionalHeaders) { for (let fieldName in additionalHeaders) { let existingValues = this.headers[fieldName]; // check if the header is already set if (existingValues === undefined) { if (additionalHeaders[fieldName] instanceof Array) { // add multiple header values as an array of strings this.headers[fieldName] = additionalHeaders[fieldName].map(function(headerValue) { return String(headerValue); }); } else { // single-valued header as arbitrary string this.headers[fieldName] = String(additionalHeaders[fieldName]); } } else if (typeof existingValues === "string") { // the header has been set already exactly once, so expand it to an array this.headers[fieldName] = [existingValues, String(additionalHeaders[fieldName])]; } else { // the header is already an array of multiple values --> push new value this.headers[fieldName].push(String(additionalHeaders[fieldName])); } } return this; } }); /** * Sets the HTTP status to 200. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "ok", { value: function() { this.status = 200; return this; } }); /** * Sets the HTTP status to 201. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "created", { value: function() { this.status = 201; return this; } }); /** * Sets the HTTP status to 400. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "bad", { value: function() { this.status = 400; return this; } }); /** * Sets the HTTP status to 401. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "unauthorized", { value: function() { this.status = 401; return this; } }); /** * Sets the HTTP status to 403. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "forbidden", { value: function() { this.status = 403; return this; } }); /** * Sets the HTTP status to 404. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "notFound", { value: function() { this.status = 404; return this; } }); /** * Sets the HTTP status to 410. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "gone", { value: function() { this.status = 410; return this; } }); /** * Sets the HTTP status to 500. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "error", { value: function() { this.status = 500; return this; } }); /** * Sets the HTTP status to 503. * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "unavailable", { value: function() { this.status = 503; return this; } }); /** * Create a response with HTTP status code 303 that redirects the client * to a new location. * @param {String} location the new location * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "redirect", { value: function(location) { this.status = 303; this.headers = { "location": location }; this.body = ["See other: " + location]; return this; } }); /** * Create a response with HTTP status code 304 that indicates the * document has not been modified * @returns {JsgiResponse} a JSGI response object to send back */ Object.defineProperty(JsgiResponse.prototype, "notModified", { value: function() { this.status = 304; this.headers = {}; this.body = [""]; return this; } }); /** * Static helper to create a `JsgiResponse` with the given status code. * @name setStatus * @function * @param {Number} code the status code to use * @returns {JsgiResponse} JSGI response with the new status code */ /** * Set the JSGI response content-type to 'text/plain' with the string as response body. * @param {String...} text... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/plain' * @name text * @function */ /** * Set the JSGI response content-type to 'text/html' with the string as response body. * @param {String...} html... a variable number of strings to send as response body * @returns {JsgiResponse} JSGI response with content-type 'text/html' * @name html * @function */ /** * Create a JSGI response with content-type 'application/json' with the JSON * representation of the given object as response body. * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/json' * @name json * @function */ /** * Create a JSGI response with content-type 'application/javascript' with the JSONP * representation of the given object as response body wrapped by the callback name. * @param {String} callback the callback function name for a JSONP request * @param {Object} object the object whose JSON representation to return * @returns {JsgiResponse} JSGI response with content-type 'application/javascript' * @name jsonp * @function */ /** * Create a JSGI response with content-type 'application/xml' with the given * XML as response body. * @param {XML|String} xml an XML document * @returns {JsgiResponse} JSGI response with content-type 'application/xml' * @name xml * @function */ /** * Set the character encoding used for text responses. * @param {String} charsetName the encoding to use. * @returns {JsgiResponse} JSGI response with the given charset * @name setCharset * @function */ /** * Merge the given object into the headers of the JSGI response. * @param {Object} headers new header fields to merge with the current ones. * @returns {JsgiResponse} JSGI response with the new headers * @name addHeaders * @function */ /** * Sets the HTTP status to 200. * @returns {JsgiResponse} a JSGI response object to send back * @name ok * @function */ /** * Sets the HTTP status to 201. * @returns {JsgiResponse} a JSGI response object to send back * @name created * @function */ /** * Sets the HTTP status to 400. * @returns {JsgiResponse} a JSGI response object to send back * @name bad * @function */ /** * Sets the HTTP status to 401. * @returns {JsgiResponse} a JSGI response object to send back * @name unauthorized * @function */ /** * Sets the HTTP status to 403. * @returns {JsgiResponse} a JSGI response object to send back * @name forbidden * @function */ /** * Sets the HTTP status to 404. * @returns {JsgiResponse} a JSGI response object to send back * @name notFound * @function */ /** * Sets the HTTP status to 410. * @returns {JsgiResponse} a JSGI response object to send back * @name gone * @function */ /** * Sets the HTTP status to 500. * @returns {JsgiResponse} a JSGI response object to send back * @name error * @function */ /** * Sets the HTTP status to 503. * @returns {JsgiResponse} a JSGI response object to send back * @name unavailable * @function */ /** * Create a response with HTTP status code 303 that redirects the client * to a new location. * @param {String} location the new location * @returns {JsgiResponse} a JSGI response object to send back * @name redirect * @function */ /** * Create a response with HTTP status code 304 that indicates the * document has not been modified * @returns {JsgiResponse} a JSGI response object to send back * @name notModified * @function */ // Define helper functions /** @ignore */ ["setStatus", "text", "html", "json", "jsonp", "xml", "stream", "binary", "setCharset", "addHeaders", "ok", "created", "bad", "unauthorized", "forbidden", "notFound", "gone", "error", "unavailable", "redirect", "notModified"].forEach(function(functionName) { exports[functionName] = function() { return JsgiResponse.prototype[functionName].apply((new JsgiResponse()), arguments); }; }); /** * A response representing a static resource. * @param {String|Resource} resource the resource to serve * @param {String} contentType optional MIME type. If not defined, * the MIME type is detected from the file name extension. */ exports.static = function (resource, contentType) { if (typeof resource == "string") { resource = getResource(resource); } if (!(resource instanceof org.ringojs.repository.Resource)) { throw Error("Wrong argument for static response: " + typeof(resource)); } var input; return { status: 200, headers: { "Content-Type": contentType || mimeType(resource.name) }, body: { digest: function() { return resource.lastModified().toString(36) + resource.length.toString(36); }, forEach: function(fn) { input = new Stream(resource.getInputStream()); try { input.forEach(fn); } finally { input.close(); } } } }; }; /** * An async response representing a resource as a single or multiple part response. * Multiple or overlapping byte ranges are coalesced into a canonical response range. * * @param {Object} request a JSGI request object * @param {String|Resource|Stream} representation path of a file as string, a resource, or a readable <a href="../../../io/">io.Stream</a> * @param {Number} size optional size of the resource in bytes, -1 indicates an unknown size. * @param {String} contentType optional content type to send for single range responses * @param {Number} timeout optional timeout to send back the ranges, defaults to 30 seconds, -1 indicates an infinite timeout. * @param {Number} maxRanges optional maximum number of ranges in a request, defaults to 20. Similar to Apache's <code>MaxRanges</code> directive. * @returns {AsyncResponse} async response filled with the give ranges * @see <a href="https://tools.ietf.org/html/rfc7233">RFC 7233 - Range Requests</a> * @see <a href="https://tools.ietf.org/html/rfc7233#section-6">Range Requests - Security Considerations</a> */ exports.range = function (request, representation, size, contentType, timeout, maxRanges) { // this would be an application error --> throw an exception if (!request || !request.headers || !request.headers["range"]) { throw new Error("Request is not a range request!"); } // only GET is allowed // https://tools.ietf.org/html/rfc7233#section-3.1 if (request.method !== "GET") { return new JsgiResponse().setStatus(400).text("Method not allowed."); } let stream; if (typeof representation == "string") { let localPath = fs.absolute(representation); if (!fs.exists(localPath) || !fs.isReadable(localPath)) { throw new Error("Resource does not exist or is not readable."); } if (size == null) { try { size = fs.size(localPath); } catch (e) { // ignore --> use -1 at the end } } stream = fs.openRaw(localPath, "r"); } else if (representation instanceof org.ringojs.repository.Resource) { stream = new Stream(representation.getInputStream()); if (size == null && representation.getLength != null) { size = representation.getLength(); } } else if (representation instanceof Stream) { stream = representation; } else { throw new Error("Invalid representation! Must be a path to a file, a resource, or a stream."); } if (!stream.readable()) { throw new Error("Stream must be readable!"); } const BOUNDARY = new ByteString("sjognir_doro_" + java.lang.System.identityHashCode(this).toString(36) + java.lang.System.identityHashCode(request).toString(36) + java.lang.System.identityHashCode(stream).toString(36) + (java.lang.System.currentTimeMillis() % 100000).toString(36) + (Math.random().toFixed(10).slice(2)), "ASCII"); contentType = contentType || "application/octet-stream"; maxRanges = (maxRanges != null && Number.isSafeInteger(maxRanges) && maxRanges >= 0 ? maxRanges : 20); // returns the raw ranges; might be overlapping / invalid let ranges = parseRange(request.headers["range"], size); if (ranges == null || ranges.length === 0 || ranges.length > maxRanges) { return new JsgiResponse().setStatus(416).text("Invalid Range header!"); } // make ranges canonical and check their validity // https://tools.ietf.org/html/rfc7233#section-4.3 try { ranges = canonicalRanges(ranges); } catch (e) { let invalidRangeResponse = new JsgiResponse().setStatus(416).text("Range Not Satisfiable"); if (size != null) { invalidRangeResponse.addHeaders({ "Content-Range": "bytes */" + size }); } return invalidRangeResponse; } // check if range can be fulfilled if(size != null && ranges[ranges.length - 1][1] > size) { return new JsgiResponse().setStatus(416).addHeaders({ "Content-Range": "bytes */" + size }).text("Range Not Satisfiable"); } const headers = {}; if (ranges.length > 1) { headers["Content-Type"] = "multipart/byteranges; boundary=" + BOUNDARY.decodeToString("ASCII"); } else { headers["Content-Type"] = contentType; headers["Content-Range"] = "bytes " + ranges[0].join("-") + "/" + (size >= 0 ? size : "*"); } const response = new AsyncResponse(request, (timeout || 30)); response.start(206, headers); spawn(function() { const responseBufferSize = request.env.servletResponse.getBufferSize(); let currentBytePos = 0; ranges.forEach(function(range, index, arr) { const [start, end] = range; stream.skip(start - currentBytePos); if (arr.length > 1) { if (index > 0) { response.write(CRLF); } response.write(HYPHEN); response.write(HYPHEN); response.write(BOUNDARY); response.write(CRLF); response.write("Content-Type: " + contentType); response.write(CRLF); response.write("Content-Range: bytes " + range.join("-") + "/" + (size >= 0 ? size : "*")); response.write(EMPTY_LINE); response.flush(); } let bsBuffer; do { bsBuffer = stream.read(responseBufferSize); if (bsBuffer.length > 0) { response.write(bsBuffer); response.flush(); } } while (bs.length > 0); currentBytePos = end + 1; }); // final boundary if (ranges.length > 1) { response.write(CRLF); response.write(HYPHEN); response.write(HYPHEN); response.write(BOUNDARY); response.write(HYPHEN); response.write(HYPHEN); } response.flush(); response.close(); }); return response; };
Fix: Take range limit into account for buffer read
modules/ringo/jsgi/response.js
Fix: Take range limit into account for buffer read
<ide><path>odules/ringo/jsgi/response.js <ide> let currentBytePos = 0; <ide> ranges.forEach(function(range, index, arr) { <ide> const [start, end] = range; <add> const numBytes = end - start + 1; <add> const rounds = Math.floor(numBytes / responseBufferSize); <add> const restBytes = numBytes % responseBufferSize; <add> <ide> stream.skip(start - currentBytePos); <ide> <ide> if (arr.length > 1) { <ide> response.flush(); <ide> } <ide> <del> let bsBuffer; <del> do { <del> bsBuffer = stream.read(responseBufferSize); <del> if (bsBuffer.length > 0) { <del> response.write(bsBuffer); <del> response.flush(); <del> } <del> } while (bs.length > 0); <add> for (let i = 0; i < rounds; i++) { <add> response.write(stream.read(responseBufferSize)); <add> response.flush(); <add> } <add> response.write(stream.read(restBytes)); <add> response.flush(); <ide> <ide> currentBytePos = end + 1; <ide> });
JavaScript
mit
973c2a6a18f7e7229fa73d1b80456c69a13e63e4
0
Austen-G/BlockBuilder,lovesnow/atom,transcranial/atom,nrodriguez13/atom,RuiDGoncalves/atom,stuartquin/atom,bsmr-x-script/atom,Austen-G/BlockBuilder,dsandstrom/atom,deoxilix/atom,gabrielPeart/atom,tanin47/atom,Jandersoft/atom,folpindo/atom,daxlab/atom,SlimeQ/atom,Locke23rus/atom,pkdevbox/atom,Abdillah/atom,vjeux/atom,nucked/atom,Austen-G/BlockBuilder,kandros/atom,liuderchi/atom,john-kelly/atom,pengshp/atom,Klozz/atom,alexandergmann/atom,MjAbuz/atom,SlimeQ/atom,bolinfest/atom,tisu2tisu/atom,Jonekee/atom,scippio/atom,ReddTea/atom,alexandergmann/atom,DiogoXRP/atom,champagnez/atom,dkfiresky/atom,jeremyramin/atom,cyzn/atom,synaptek/atom,tanin47/atom,constanzaurzua/atom,beni55/atom,Andrey-Pavlov/atom,transcranial/atom,alfredxing/atom,champagnez/atom,bj7/atom,ardeshirj/atom,Andrey-Pavlov/atom,synaptek/atom,bj7/atom,Rodjana/atom,Rychard/atom,n-riesco/atom,Abdillah/atom,kjav/atom,rlugojr/atom,Rychard/atom,harshdattani/atom,mdumrauf/atom,yamhon/atom,AlbertoBarrago/atom,n-riesco/atom,bencolon/atom,ardeshirj/atom,charleswhchan/atom,KENJU/atom,palita01/atom,AlexxNica/atom,AlisaKiatkongkumthon/atom,mertkahyaoglu/atom,atom/atom,darwin/atom,n-riesco/atom,john-kelly/atom,stuartquin/atom,wiggzz/atom,ralphtheninja/atom,fedorov/atom,atom/atom,Jandersoft/atom,niklabh/atom,Jandersolutions/atom,folpindo/atom,andrewleverette/atom,RobinTec/atom,FIT-CSE2410-A-Bombs/atom,hellendag/atom,palita01/atom,burodepeper/atom,Austen-G/BlockBuilder,vhutheesing/atom,woss/atom,RuiDGoncalves/atom,ralphtheninja/atom,t9md/atom,dkfiresky/atom,G-Baby/atom,liuderchi/atom,t9md/atom,lpommers/atom,anuwat121/atom,jeremyramin/atom,Neron-X5/atom,mrodalgaard/atom,rxkit/atom,john-kelly/atom,medovob/atom,gzzhanghao/atom,YunchengLiao/atom,folpindo/atom,001szymon/atom,mrodalgaard/atom,originye/atom,tmunro/atom,rlugojr/atom,MjAbuz/atom,ashneo76/atom,nucked/atom,gisenberg/atom,gisenberg/atom,G-Baby/atom,rxkit/atom,synaptek/atom,gzzhanghao/atom,bcoe/atom,dsandstrom/atom,boomwaiza/atom,efatsi/atom,Dennis1978/atom,seedtigo/atom,SlimeQ/atom,fedorov/atom,decaffeinate-examples/atom,Ingramz/atom,me-benni/atom,helber/atom,Jandersolutions/atom,xream/atom,gisenberg/atom,wiggzz/atom,tjkr/atom,Sangaroonaom/atom,woss/atom,fscherwi/atom,Dennis1978/atom,woss/atom,Andrey-Pavlov/atom,atom/atom,xream/atom,svanharmelen/atom,CraZySacX/atom,pombredanne/atom,AlbertoBarrago/atom,champagnez/atom,ivoadf/atom,yangchenghu/atom,vhutheesing/atom,daxlab/atom,decaffeinate-examples/atom,kjav/atom,sekcheong/atom,bsmr-x-script/atom,gabrielPeart/atom,helber/atom,Andrey-Pavlov/atom,bolinfest/atom,scippio/atom,YunchengLiao/atom,deoxilix/atom,scippio/atom,KENJU/atom,Abdillah/atom,transcranial/atom,PKRoma/atom,deoxilix/atom,vjeux/atom,stinsonga/atom,mdumrauf/atom,sekcheong/atom,cyzn/atom,g2p/atom,stinsonga/atom,brettle/atom,dsandstrom/atom,florianb/atom,Rodjana/atom,AdrianVovk/substance-ide,lovesnow/atom,gisenberg/atom,dkfiresky/atom,bcoe/atom,mertkahyaoglu/atom,svanharmelen/atom,n-riesco/atom,dkfiresky/atom,AdrianVovk/substance-ide,Andrey-Pavlov/atom,CraZySacX/atom,ironbox360/atom,KENJU/atom,kandros/atom,Huaraz2/atom,gabrielPeart/atom,MjAbuz/atom,jordanbtucker/atom,beni55/atom,sotayamashita/atom,boomwaiza/atom,burodepeper/atom,hellendag/atom,decaffeinate-examples/atom,tisu2tisu/atom,Locke23rus/atom,Klozz/atom,gzzhanghao/atom,jordanbtucker/atom,Jandersolutions/atom,brettle/atom,ReddTea/atom,dkfiresky/atom,jeremyramin/atom,dijs/atom,KENJU/atom,phord/atom,Arcanemagus/atom,originye/atom,nrodriguez13/atom,andrewleverette/atom,ObviouslyGreen/atom,Jandersoft/atom,AlisaKiatkongkumthon/atom,stuartquin/atom,nucked/atom,florianb/atom,ReddTea/atom,G-Baby/atom,bcoe/atom,johnrizzo1/atom,bencolon/atom,bolinfest/atom,AlexxNica/atom,bcoe/atom,yangchenghu/atom,tisu2tisu/atom,RobinTec/atom,hellendag/atom,florianb/atom,dsandstrom/atom,tmunro/atom,synaptek/atom,Rodjana/atom,mertkahyaoglu/atom,constanzaurzua/atom,YunchengLiao/atom,charleswhchan/atom,elkingtonmcb/atom,vhutheesing/atom,ashneo76/atom,liuderchi/atom,elkingtonmcb/atom,rookie125/atom,mertkahyaoglu/atom,sotayamashita/atom,sekcheong/atom,sotayamashita/atom,vjeux/atom,Jandersolutions/atom,harshdattani/atom,anuwat121/atom,Neron-X5/atom,pombredanne/atom,brettle/atom,PKRoma/atom,Klozz/atom,constanzaurzua/atom,Mokolea/atom,Jandersolutions/atom,ObviouslyGreen/atom,bsmr-x-script/atom,tmunro/atom,seedtigo/atom,Arcanemagus/atom,BogusCurry/atom,ReddTea/atom,xream/atom,NunoEdgarGub1/atom,wiggzz/atom,tanin47/atom,rookie125/atom,burodepeper/atom,sekcheong/atom,svanharmelen/atom,DiogoXRP/atom,brumm/atom,ivoadf/atom,woss/atom,RobinTec/atom,phord/atom,Abdillah/atom,Mokolea/atom,BogusCurry/atom,Huaraz2/atom,lpommers/atom,johnrizzo1/atom,lovesnow/atom,ykeisuke/atom,Neron-X5/atom,Austen-G/BlockBuilder,tjkr/atom,woss/atom,palita01/atom,andrewleverette/atom,nrodriguez13/atom,NunoEdgarGub1/atom,fedorov/atom,seedtigo/atom,mertkahyaoglu/atom,kevinrenaers/atom,fscherwi/atom,AlexxNica/atom,gontadu/atom,bcoe/atom,SlimeQ/atom,ralphtheninja/atom,Neron-X5/atom,johnrizzo1/atom,johnhaley81/atom,ykeisuke/atom,medovob/atom,Jandersoft/atom,NunoEdgarGub1/atom,DiogoXRP/atom,alfredxing/atom,alfredxing/atom,kaicataldo/atom,florianb/atom,kaicataldo/atom,johnhaley81/atom,ObviouslyGreen/atom,darwin/atom,FIT-CSE2410-A-Bombs/atom,yamhon/atom,dijs/atom,pombredanne/atom,FIT-CSE2410-A-Bombs/atom,lovesnow/atom,john-kelly/atom,brumm/atom,boomwaiza/atom,yamhon/atom,me-benni/atom,harshdattani/atom,chfritz/atom,niklabh/atom,mdumrauf/atom,pkdevbox/atom,NunoEdgarGub1/atom,stinsonga/atom,MjAbuz/atom,alexandergmann/atom,SlimeQ/atom,MjAbuz/atom,Jonekee/atom,ironbox360/atom,pkdevbox/atom,ReddTea/atom,BogusCurry/atom,vjeux/atom,dijs/atom,kandros/atom,daxlab/atom,constanzaurzua/atom,cyzn/atom,panuchart/atom,Sangaroonaom/atom,Arcanemagus/atom,Rychard/atom,kevinrenaers/atom,yangchenghu/atom,chfritz/atom,g2p/atom,fedorov/atom,panuchart/atom,AlbertoBarrago/atom,bj7/atom,ardeshirj/atom,Sangaroonaom/atom,pengshp/atom,gontadu/atom,johnhaley81/atom,ashneo76/atom,charleswhchan/atom,t9md/atom,n-riesco/atom,rxkit/atom,ivoadf/atom,mrodalgaard/atom,bencolon/atom,stinsonga/atom,Abdillah/atom,chfritz/atom,AlisaKiatkongkumthon/atom,charleswhchan/atom,kaicataldo/atom,decaffeinate-examples/atom,elkingtonmcb/atom,beni55/atom,Jandersoft/atom,kjav/atom,Neron-X5/atom,sekcheong/atom,synaptek/atom,me-benni/atom,Ingramz/atom,YunchengLiao/atom,Ingramz/atom,phord/atom,Austen-G/BlockBuilder,gontadu/atom,pombredanne/atom,ykeisuke/atom,Dennis1978/atom,ironbox360/atom,rookie125/atom,001szymon/atom,originye/atom,constanzaurzua/atom,pombredanne/atom,Huaraz2/atom,g2p/atom,RobinTec/atom,charleswhchan/atom,Locke23rus/atom,kjav/atom,niklabh/atom,rlugojr/atom,001szymon/atom,helber/atom,KENJU/atom,NunoEdgarGub1/atom,YunchengLiao/atom,vjeux/atom,Mokolea/atom,RobinTec/atom,florianb/atom,fscherwi/atom,PKRoma/atom,efatsi/atom,kevinrenaers/atom,anuwat121/atom,lpommers/atom,RuiDGoncalves/atom,CraZySacX/atom,medovob/atom,tjkr/atom,brumm/atom,dsandstrom/atom,liuderchi/atom,darwin/atom,AdrianVovk/substance-ide,pengshp/atom,panuchart/atom,jordanbtucker/atom,john-kelly/atom,kjav/atom,Jonekee/atom,gisenberg/atom,lovesnow/atom,efatsi/atom,fedorov/atom
'use strict' const path = require('path') const CSON = require('season') const fs = require('fs-plus') const COMPILERS = { '.js': require('./babel'), '.ts': require('./typescript'), '.coffee': require('./coffee-script') } for (let extension in COMPILERS) { let compiler = COMPILERS[extension] Object.defineProperty(require.extensions, extension, { enumerable: true, writable: false, value: function (module, filePath) { let code = compileFileAtPath(compiler, filePath) return module._compile(code, filePath) } }) } let cacheDirectory = null exports.setAtomHomeDirectory = function (atomHome) { let cacheDir = path.join(atomHome, 'compile-cache') if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) { cacheDir = path.join(cacheDirectory, 'root') } this.setCacheDirectory(cacheDir) } exports.setCacheDirectory = function (directory) { cacheDirectory = directory CSON.setCacheDir(path.join(cacheDirectory, 'cson')); } exports.getCacheDirectory = function () { return cacheDirectory } exports.addPathToCache = function (filePath, atomHome) { this.setAtomHomeDirectory(atomHome) extension = path.extname(filePath) if (extension === '.cson') { return CSON.readFileSync(filePath) } if (compiler = COMPILERS[extension]) { return compileFileAtPath(compiler, filePath) } } function compileFileAtPath (compiler, filePath) { let sourceCode = fs.readFileSync(filePath, 'utf8') if (compiler.shouldCompile(sourceCode, filePath)) { let cachePath = compiler.getCachePath(sourceCode, filePath) let compiledCode = readCachedJavascript(cachePath) if (compiledCode == null) { compiledCode = compiler.compile(sourceCode, filePath) writeCachedJavascript(cachePath, compiledCode) } return compiledCode } return sourceCode } function readCachedJavascript (relativeCachePath) { let cachePath = path.join(cacheDirectory, relativeCachePath) if (fs.isFileSync(cachePath)) { try { return fs.readFileSync(cachePath, 'utf8') } catch (error) {} } return null } function writeCachedJavascript (relativeCachePath, code) { let cachePath = path.join(cacheDirectory, relativeCachePath) fs.writeFileSync(cachePath, code, 'utf8') } const InlineSourceMapRegExp = /\/\/[#@]\s*sourceMappingURL=([^'"\n]+)\s*$/g require('source-map-support').install({ handleUncaughtExceptions: false, // Most of this logic is the same as the default implementation in the // source-map-support module, but we've overridden it to read the javascript // code from our cache directory. retrieveSourceMap: function (filePath) { if (!fs.isFileSync(filePath)){ return null } let sourceCode = fs.readFileSync(filePath, 'utf8') let compiler = COMPILERS[path.extname(filePath)] let fileData = readCachedJavascript(compiler.getCachePath(sourceCode, filePath)) if (fileData == null) { return null } let match, lastMatch InlineSourceMapRegExp.lastIndex = 0 while ((match = InlineSourceMapRegExp.exec(fileData))) { lastMatch = match } if (lastMatch == null){ return null } let sourceMappingURL = lastMatch[1] let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1) let sourceMapData = new Buffer(rawData, 'base64').toString() return { map: JSON.parse(sourceMapData), url: null } } })
src/compile-cache.js
'use strict' const path = require('path') const CSON = require('season') const fs = require('fs-plus') const COMPILERS = { '.js': require('./babel'), '.ts': require('./typescript'), '.coffee': require('./coffee-script') } for (let extension in COMPILERS) { let compiler = COMPILERS[extension] Object.defineProperty(require.extensions, extension, { enumerable: true, writable: false, value: function (module, filePath) { let code = compileFileAtPath(compiler, filePath) return module._compile(code, filePath) } }) } let cacheDirectory = null exports.setAtomHomeDirectory = function (atomHome) { let cacheDir = path.join(atomHome, 'compile-cache') if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) { cacheDir = path.join(cacheDirectory, 'root') } this.setCacheDirectory(cacheDir) } exports.setCacheDirectory = function (directory) { cacheDirectory = directory CSON.setCacheDir(path.join(cacheDirectory, 'cson')); } exports.getCacheDirectory = function () { return cacheDirectory } exports.addPathToCache = function (filePath, atomHome) { this.setAtomHomeDirectory(atomHome) extension = path.extname(filePath) if (extension === '.cson') { return CSON.readFileSync(filePath) } if (compiler = COMPILERS[extension]) { return compileFileAtPath(compiler, filePath) } } function compileFileAtPath (compiler, filePath) { let sourceCode = fs.readFileSync(filePath, 'utf8') if (compiler.shouldCompile(sourceCode, filePath)) { let cachePath = compiler.getCachePath(sourceCode, filePath) let compiledCode = readCachedJavascript(cachePath) if (compiledCode == null) { compiledCode = compiler.compile(sourceCode, filePath) writeCachedJavascript(cachePath, compiledCode) } return compiledCode } return sourceCode } function readCachedJavascript (relativeCachePath) { let cachePath = path.join(cacheDirectory, relativeCachePath) if (fs.isFileSync(cachePath)) { try { return fs.readFileSync(cachePath, 'utf8') } catch (error) {} } return null } function writeCachedJavascript (relativeCachePath, code) { let cachePath = path.join(cacheDirectory, relativeCachePath) fs.writeFileSync(cachePath, code, 'utf8') } const InlineSourceMapRegExp = /\/\/[#@]\s*sourceMappingURL=([^'"]+)\s*$/g require('source-map-support').install({ handleUncaughtExceptions: false, // Most of this logic is the same as the default implementation in the // source-map-support module, but we've overridden it to read the javascript // code from our cache directory. retrieveSourceMap: function (filePath) { if (!fs.isFileSync(filePath)){ return null } let sourceCode = fs.readFileSync(filePath, 'utf8') let compiler = COMPILERS[path.extname(filePath)] let fileData = readCachedJavascript(compiler.getCachePath(sourceCode, filePath)) if (fileData == null) { return null } let match, lastMatch InlineSourceMapRegExp.lastIndex = 0 while ((match = InlineSourceMapRegExp.exec(fileData))) { lastMatch = match } if (lastMatch == null){ return null } let sourceMappingURL = lastMatch[1] let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1) let sourceMapData = new Buffer(rawData, 'base64').toString() return { map: JSON.parse(sourceMapData), url: null } } })
Don't match newlines when finding source-map data
src/compile-cache.js
Don't match newlines when finding source-map data
<ide><path>rc/compile-cache.js <ide> fs.writeFileSync(cachePath, code, 'utf8') <ide> } <ide> <del>const InlineSourceMapRegExp = /\/\/[#@]\s*sourceMappingURL=([^'"]+)\s*$/g <add>const InlineSourceMapRegExp = /\/\/[#@]\s*sourceMappingURL=([^'"\n]+)\s*$/g <ide> <ide> require('source-map-support').install({ <ide> handleUncaughtExceptions: false,
Java
mit
dd375f4c62f0fecdf6eb76f62eedd2f9bfc15d66
0
algoliareadmebot/algoliasearch-client-android,algoliareadmebot/algoliasearch-client-android,algolia/algoliasearch-client-android,algolia/algoliasearch-client-android,algolia/algoliasearch-client-android
/* * Copyright (c) 2015 Algolia * http://www.algolia.com/ * * 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 com.algolia.search.saas; import android.support.annotation.NonNull; import org.apache.http.HttpException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; /** * Abstract Entry point in the Java API. */ abstract class BaseAPIClient { private int httpSocketTimeoutMS = 30000; private int httpConnectTimeoutMS = 2000; private int httpSearchTimeoutMS = 5000; private final static String version = "2.6.4"; private final String applicationID; private final String apiKey; private List<String> readHosts; private List<String> writeHosts; /** * HTTP headers that will be sent with every request. */ private HashMap<String, String> headers; private ExpiringCache<String, String> cache; private boolean isCacheEnabled = false; /** * Algolia Search initialization * * @param applicationID the application ID you have in your admin interface * @param apiKey a valid API key for the service * @param hosts the list of hosts that you have received for the service */ protected BaseAPIClient(String applicationID, String apiKey, String[] hosts) { if (applicationID == null || applicationID.length() == 0) { throw new RuntimeException("AlgoliaSearch requires an applicationID."); } this.applicationID = applicationID; if (apiKey == null || apiKey.length() == 0) { throw new RuntimeException("AlgoliaSearch requires an apiKey."); } this.apiKey = apiKey; if (hosts != null) { setReadHosts(hosts); setWriteHosts(hosts); } else { setReadHosts( applicationID + "-dsn.algolia.net", applicationID + "-1.algolianet.com", applicationID + "-2.algolianet.com", applicationID + "-3.algolianet.com" ); setWriteHosts( applicationID + ".algolia.net", applicationID + "-1.algolianet.com", applicationID + "-2.algolianet.com", applicationID + "-3.algolianet.com" ); } headers = new HashMap<String, String>(); } public String getApplicationID() { return applicationID; } /** * Enables search cache with default parameters */ public void enableSearchCache() { isCacheEnabled = true; if (cache == null) { cache = new ExpiringCache<>(); } } /** * Enables search cache with default parameters * * @param timeoutInSeconds duration during wich an request is kept in cache * @param maxRequests maximum amount of requests to keep before removing the least recently used */ public void enableSearchCache(int timeoutInSeconds, int maxRequests) { isCacheEnabled = true; cache = new ExpiringCache<>(timeoutInSeconds, maxRequests); } /** * Disable and reset cache */ public void disableSearchCache() { isCacheEnabled = false; if (cache != null) { cache.reset(); cache = null; } } /** * Remove all entries from cache */ public void clearSearchCache() { if (cache != null) { cache.reset(); } } /** * Set an HTTP header that will be sent with every request. * * @param name Header name. * @param value Value for the header. If null, the header will be removed. */ public void setHeader(@NonNull String name, String value) { if (value == null) { headers.remove(name); } else { headers.put(name, value); } } /** * Get an HTTP header. * * @param name Header name. */ public String getHeader(@NonNull String name) { return headers.get(name); } public String[] getReadHosts() { return readHosts.toArray(new String[readHosts.size()]); } public void setReadHosts(@NonNull String... hosts) { if (hosts.length == 0) { throw new IllegalArgumentException("Hosts array cannot be empty"); } readHosts = Arrays.asList(hosts); } public String[] getWriteHosts() { return writeHosts.toArray(new String[writeHosts.size()]); } public void setWriteHosts(@NonNull String... hosts) { if (hosts.length == 0) { throw new IllegalArgumentException("Hosts array cannot be empty"); } writeHosts = Arrays.asList(hosts); } /** * Set read and write hosts to the same value (convenience method). * * @param hosts New hosts. Must not be empty. */ public void setHosts(@NonNull String... hosts) { setReadHosts(hosts); setWriteHosts(hosts); } /** * Allow to set timeout * * @param connectTimeout connection timeout in MS * @param readTimeout socket timeout in MS */ public void setTimeout(int connectTimeout, int readTimeout) { httpSocketTimeoutMS = readTimeout; httpConnectTimeoutMS = httpSearchTimeoutMS = connectTimeout; } /** * Allow to set timeout * * @param connectTimeout connection timeout in MS * @param readTimeout socket timeout in MS * @param searchTimeout socket timeout in MS */ public void setTimeout(int connectTimeout, int readTimeout, int searchTimeout) { httpSocketTimeoutMS = readTimeout; httpConnectTimeoutMS = connectTimeout; httpSearchTimeoutMS = searchTimeout; } /** * List all existing indexes * * @return a JSON Object in the form: * { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"}, * {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]} */ protected JSONObject listIndexes() throws AlgoliaException { return getRequest("/1/indexes/", false); } /** * Delete an index * * @param indexName the name of index to delete * @return an object containing a "deletedAt" attribute */ protected JSONObject deleteIndex(String indexName) throws AlgoliaException { try { return deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Move an existing index. * * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). */ protected JSONObject moveIndex(String srcIndexName, String dstIndexName) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("operation", "move"); content.put("destination", dstIndexName); return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Copy an existing index. * * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). */ protected JSONObject copyIndex(String srcIndexName, String dstIndexName) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("operation", "copy"); content.put("destination", dstIndexName); return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } protected JSONObject multipleQueries(List<IndexQuery> queries, String strategy) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (IndexQuery indexQuery : queries) { String paramsString = indexQuery.build(); requests.put(new JSONObject().put("indexName", indexQuery.getIndex()).put("params", paramsString)); } JSONObject body = new JSONObject().put("requests", requests); return postRequest("/1/indexes/*/queries?strategy=" + strategy, body.toString(), true); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Custom batch * * @param actions the array of actions * @throws AlgoliaException if the response is not valid json */ protected JSONObject batch(JSONArray actions) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("requests", actions); return postRequest("/1/indexes/*/batch", content.toString(), false); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } private enum Method { GET, POST, PUT, DELETE } protected byte[] getRequestRaw(String url, boolean search) throws AlgoliaException { return _requestRaw(Method.GET, url, null, readHosts, httpConnectTimeoutMS, search ? httpSearchTimeoutMS : httpSocketTimeoutMS); } protected JSONObject getRequest(String url, boolean search) throws AlgoliaException { return _request(Method.GET, url, null, readHosts, httpConnectTimeoutMS, search ? httpSearchTimeoutMS : httpSocketTimeoutMS); } protected JSONObject deleteRequest(String url) throws AlgoliaException { return _request(Method.DELETE, url, null, writeHosts, httpConnectTimeoutMS, httpSocketTimeoutMS); } protected JSONObject postRequest(String url, String obj, boolean readOperation) throws AlgoliaException { return _request(Method.POST, url, obj, (readOperation ? readHosts : writeHosts), httpConnectTimeoutMS, (readOperation ? httpSearchTimeoutMS : httpSocketTimeoutMS)); } protected JSONObject putRequest(String url, String obj) throws AlgoliaException { return _request(Method.PUT, url, obj, writeHosts, httpConnectTimeoutMS, httpSocketTimeoutMS); } /** * Reads the InputStream as UTF-8 * * @param stream the InputStream to read * @return the stream's content as a String * @throws IOException if the stream can't be read, decoded as UTF-8 or closed */ private String _toCharArray(InputStream stream) throws IOException { InputStreamReader is = new InputStreamReader(stream, "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[1000]; int l = 0; while (l >= 0) { builder.append(buf, 0, l); l = is.read(buf); } is.close(); return builder.toString(); } /** * Reads the InputStream into a byte array * * @param stream the InputStream to read * @return the stream's content as a byte[] * @throws AlgoliaException if the stream can't be read or flushed */ private byte[] _toByteArray(InputStream stream) throws AlgoliaException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int read; byte[] buffer = new byte[1024]; try { while ((read = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, read); } out.flush(); return out.toByteArray(); } catch (IOException e) { throw new AlgoliaException("Error while reading stream: " + e.getMessage()); } } private JSONObject _getJSONObject(String input) throws JSONException { return new JSONObject(new JSONTokener(input)); } private JSONObject _getJSONObject(byte[] bytes) throws JSONException, UnsupportedEncodingException { return new JSONObject(new String(bytes, "UTF-8")); } private JSONObject _getAnswerJSONObject(InputStream istream) throws IOException, JSONException { return _getJSONObject(_toCharArray(istream)); } /** * Send the query according to parameters and returns its result as a JSONObject * * @param m HTTP Method to use * @param url endpoint URL * @param json optional JSON Object to send * @param hostsArray array of hosts to try successively * @param connectTimeout maximum wait time to open connection * @param readTimeout maximum time to read data on socket * @return a JSONObject containing the resulting data or error * @throws AlgoliaException if the request data is not valid json */ private synchronized JSONObject _request(Method m, String url, String json, List<String> hostsArray, int connectTimeout, int readTimeout) throws AlgoliaException { String cacheKey = null; String jsonStr = null; if (isCacheEnabled) { cacheKey = String.format("%s:%s(%s)", m, url, json); jsonStr = cache.get(cacheKey); } try { if (jsonStr == null) { final byte[] requestRaw = _requestRaw(m, url, json, hostsArray, connectTimeout, readTimeout); jsonStr = new String(requestRaw, "UTF-8"); if (isCacheEnabled) { cache.put(cacheKey, jsonStr); } } return new JSONObject(jsonStr); } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("UTF-8 decode error:" + e.getMessage()); } } /** * Send the query according to parameters and returns its result as a JSONObject * * @param m HTTP Method to use * @param url endpoint URL * @param json optional JSON Object to send * @param hostsArray array of hosts to try successively * @param connectTimeout maximum wait time to open connection * @param readTimeout maximum time to read data on socket * @return a JSONObject containing the resulting data or error * @throws AlgoliaException in case of connection or data handling error */ private synchronized byte[] _requestRaw(Method m, String url, String json, List<String> hostsArray, int connectTimeout, int readTimeout) throws AlgoliaException { String requestMethod; HashMap<String, String> errors = new HashMap<String, String>(); // for each host for (String host : hostsArray) { switch (m) { case DELETE: requestMethod = "DELETE"; break; case GET: requestMethod = "GET"; break; case POST: requestMethod = "POST"; break; case PUT: requestMethod = "PUT"; break; default: throw new IllegalArgumentException("Method " + m + " is not supported"); } // set URL try { URL hostURL = new URL("https://" + host + url); HttpURLConnection hostConnection = (HttpURLConnection) hostURL.openConnection(); //set timeouts hostConnection.setRequestMethod(requestMethod); hostConnection.setConnectTimeout(connectTimeout); hostConnection.setReadTimeout(readTimeout); // set auth headers hostConnection.setRequestProperty("X-Algolia-Application-Id", this.applicationID); hostConnection.setRequestProperty("X-Algolia-API-Key", this.apiKey); for (Map.Entry<String, String> entry : headers.entrySet()) { hostConnection.setRequestProperty(entry.getKey(), entry.getValue()); } // set user agent hostConnection.setRequestProperty("User-Agent", "Algolia for Android " + version); // write JSON entity if (json != null) { if (!(requestMethod.equals("PUT") || requestMethod.equals("POST"))) { throw new IllegalArgumentException("Method " + m + " cannot enclose entity"); } hostConnection.setRequestProperty("Content-type", "application/json"); hostConnection.setDoOutput(true); StringEntity se = new StringEntity(json, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.writeTo(hostConnection.getOutputStream()); } // read response int code = hostConnection.getResponseCode(); final boolean codeIsError = code / 100 != 2; InputStream stream = codeIsError ? hostConnection.getErrorStream() : hostConnection.getInputStream(); final byte[] rawResponse; String encoding = hostConnection.getContentEncoding(); if (encoding != null && encoding.contains("gzip")) { rawResponse = _toByteArray(new GZIPInputStream(stream)); } else { rawResponse = _toByteArray(stream); } // handle http errors if (codeIsError) { if (code / 100 == 4) { String message = _getJSONObject(rawResponse).getString("message"); consumeQuietly(hostConnection); throw new AlgoliaException(message); } else { final String errorMessage = _toCharArray(stream); consumeQuietly(hostConnection); addError(errors, host, new HttpException(errorMessage)); continue; } } return rawResponse; } catch (JSONException e) { // fatal throw new AlgoliaException("JSON decode error:" + e.getMessage()); } catch (UnsupportedEncodingException e) { // fatal throw new AlgoliaException("Invalid JSON Object: " + json); } catch (IOException e) { // host error, continue on the next host addError(errors, host, e); } } StringBuilder builder = new StringBuilder("Hosts unreachable: "); Boolean first = true; for (Map.Entry<String, String> entry : errors.entrySet()) { if (!first) { builder.append(", "); } builder.append(entry.toString()); first = false; } throw new AlgoliaException(builder.toString()); } private void addError(HashMap<String, String> errors, String host, Exception e) { errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage())); } /** * Ensures that the entity content is fully consumed and the content stream, if exists, * is closed. */ private void consumeQuietly(final HttpURLConnection connection) { try { int read = 0; while (read != -1) { read = connection.getInputStream().read(); } connection.getInputStream().close(); read = 0; while (read != -1) { read = connection.getErrorStream().read(); } connection.getErrorStream().close(); connection.disconnect(); } catch (IOException e) { // no inputStream to close } } }
algoliasearch/src/main/java/com/algolia/search/saas/BaseAPIClient.java
/* * Copyright (c) 2015 Algolia * http://www.algolia.com/ * * 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 com.algolia.search.saas; import android.support.annotation.NonNull; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; /** * Abstract Entry point in the Java API. */ abstract class BaseAPIClient { private int httpSocketTimeoutMS = 30000; private int httpConnectTimeoutMS = 2000; private int httpSearchTimeoutMS = 5000; private final static String version = "2.6.4"; private final String applicationID; private final String apiKey; private List<String> readHosts; private List<String> writeHosts; /** * HTTP headers that will be sent with every request. */ private HashMap<String, String> headers; private ExpiringCache<String, String> cache; private boolean isCacheEnabled = false; /** * Algolia Search initialization * * @param applicationID the application ID you have in your admin interface * @param apiKey a valid API key for the service * @param hosts the list of hosts that you have received for the service */ protected BaseAPIClient(String applicationID, String apiKey, String[] hosts) { if (applicationID == null || applicationID.length() == 0) { throw new RuntimeException("AlgoliaSearch requires an applicationID."); } this.applicationID = applicationID; if (apiKey == null || apiKey.length() == 0) { throw new RuntimeException("AlgoliaSearch requires an apiKey."); } this.apiKey = apiKey; if (hosts != null) { setReadHosts(hosts); setWriteHosts(hosts); } else { setReadHosts( applicationID + "-dsn.algolia.net", applicationID + "-1.algolianet.com", applicationID + "-2.algolianet.com", applicationID + "-3.algolianet.com" ); setWriteHosts( applicationID + ".algolia.net", applicationID + "-1.algolianet.com", applicationID + "-2.algolianet.com", applicationID + "-3.algolianet.com" ); } headers = new HashMap<String, String>(); } public String getApplicationID() { return applicationID; } /** * Enables search cache with default parameters */ public void enableSearchCache() { isCacheEnabled = true; if (cache == null) { cache = new ExpiringCache<>(); } } /** * Enables search cache with default parameters * * @param timeoutInSeconds duration during wich an request is kept in cache * @param maxRequests maximum amount of requests to keep before removing the least recently used */ public void enableSearchCache(int timeoutInSeconds, int maxRequests) { isCacheEnabled = true; cache = new ExpiringCache<>(timeoutInSeconds, maxRequests); } /** * Disable and reset cache */ public void disableSearchCache() { isCacheEnabled = false; if (cache != null) { cache.reset(); cache = null; } } /** * Remove all entries from cache */ public void clearSearchCache() { if (cache != null) { cache.reset(); } } /** * Set an HTTP header that will be sent with every request. * * @param name Header name. * @param value Value for the header. If null, the header will be removed. */ public void setHeader(@NonNull String name, String value) { if (value == null) { headers.remove(name); } else { headers.put(name, value); } } /** * Get an HTTP header. * * @param name Header name. */ public String getHeader(@NonNull String name) { return headers.get(name); } public String[] getReadHosts() { return readHosts.toArray(new String[readHosts.size()]); } public void setReadHosts(@NonNull String... hosts) { if (hosts.length == 0) { throw new IllegalArgumentException("Hosts array cannot be empty"); } readHosts = Arrays.asList(hosts); } public String[] getWriteHosts() { return writeHosts.toArray(new String[writeHosts.size()]); } public void setWriteHosts(@NonNull String... hosts) { if (hosts.length == 0) { throw new IllegalArgumentException("Hosts array cannot be empty"); } writeHosts = Arrays.asList(hosts); } /** * Set read and write hosts to the same value (convenience method). * * @param hosts New hosts. Must not be empty. */ public void setHosts(@NonNull String... hosts) { setReadHosts(hosts); setWriteHosts(hosts); } /** * Allow to set timeout * * @param connectTimeout connection timeout in MS * @param readTimeout socket timeout in MS */ public void setTimeout(int connectTimeout, int readTimeout) { httpSocketTimeoutMS = readTimeout; httpConnectTimeoutMS = httpSearchTimeoutMS = connectTimeout; } /** * Allow to set timeout * * @param connectTimeout connection timeout in MS * @param readTimeout socket timeout in MS * @param searchTimeout socket timeout in MS */ public void setTimeout(int connectTimeout, int readTimeout, int searchTimeout) { httpSocketTimeoutMS = readTimeout; httpConnectTimeoutMS = connectTimeout; httpSearchTimeoutMS = searchTimeout; } /** * List all existing indexes * * @return a JSON Object in the form: * { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"}, * {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]} */ protected JSONObject listIndexes() throws AlgoliaException { return getRequest("/1/indexes/", false); } /** * Delete an index * * @param indexName the name of index to delete * @return an object containing a "deletedAt" attribute */ protected JSONObject deleteIndex(String indexName) throws AlgoliaException { try { return deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Move an existing index. * * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). */ protected JSONObject moveIndex(String srcIndexName, String dstIndexName) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("operation", "move"); content.put("destination", dstIndexName); return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Copy an existing index. * * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). */ protected JSONObject copyIndex(String srcIndexName, String dstIndexName) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("operation", "copy"); content.put("destination", dstIndexName); return postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString(), false); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } protected JSONObject multipleQueries(List<IndexQuery> queries, String strategy) throws AlgoliaException { try { JSONArray requests = new JSONArray(); for (IndexQuery indexQuery : queries) { String paramsString = indexQuery.build(); requests.put(new JSONObject().put("indexName", indexQuery.getIndex()).put("params", paramsString)); } JSONObject body = new JSONObject().put("requests", requests); return postRequest("/1/indexes/*/queries?strategy=" + strategy, body.toString(), true); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Custom batch * * @param actions the array of actions * @throws AlgoliaException if the response is not valid json */ protected JSONObject batch(JSONArray actions) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("requests", actions); return postRequest("/1/indexes/*/batch", content.toString(), false); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } private enum Method { GET, POST, PUT, DELETE } protected byte[] getRequestRaw(String url, boolean search) throws AlgoliaException { return _requestRaw(Method.GET, url, null, readHosts, httpConnectTimeoutMS, search ? httpSearchTimeoutMS : httpSocketTimeoutMS); } protected JSONObject getRequest(String url, boolean search) throws AlgoliaException { return _request(Method.GET, url, null, readHosts, httpConnectTimeoutMS, search ? httpSearchTimeoutMS : httpSocketTimeoutMS); } protected JSONObject deleteRequest(String url) throws AlgoliaException { return _request(Method.DELETE, url, null, writeHosts, httpConnectTimeoutMS, httpSocketTimeoutMS); } protected JSONObject postRequest(String url, String obj, boolean readOperation) throws AlgoliaException { return _request(Method.POST, url, obj, (readOperation ? readHosts : writeHosts), httpConnectTimeoutMS, (readOperation ? httpSearchTimeoutMS : httpSocketTimeoutMS)); } protected JSONObject putRequest(String url, String obj) throws AlgoliaException { return _request(Method.PUT, url, obj, writeHosts, httpConnectTimeoutMS, httpSocketTimeoutMS); } /** * Reads the InputStream as UTF-8 * * @param stream the InputStream to read * @return the stream's content as a String * @throws IOException if the stream can't be read, decoded as UTF-8 or closed */ private String _toCharArray(InputStream stream) throws IOException { InputStreamReader is = new InputStreamReader(stream, "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[1000]; int l = 0; while (l >= 0) { builder.append(buf, 0, l); l = is.read(buf); } is.close(); return builder.toString(); } /** * Reads the InputStream into a byte array * * @param stream the InputStream to read * @return the stream's content as a byte[] * @throws AlgoliaException if the stream can't be read or flushed */ private byte[] _toByteArray(InputStream stream) throws AlgoliaException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int read; byte[] buffer = new byte[1024]; try { while ((read = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, read); } out.flush(); return out.toByteArray(); } catch (IOException e) { throw new AlgoliaException("Error while reading stream: " + e.getMessage()); } } private JSONObject _getJSONObject(String input) throws JSONException { return new JSONObject(new JSONTokener(input)); } private JSONObject _getJSONObject(byte[] bytes) throws JSONException, UnsupportedEncodingException { return new JSONObject(new String(bytes, "UTF-8")); } private JSONObject _getAnswerJSONObject(InputStream istream) throws IOException, JSONException { return _getJSONObject(_toCharArray(istream)); } /** * Send the query according to parameters and returns its result as a JSONObject * * @param m HTTP Method to use * @param url endpoint URL * @param json optional JSON Object to send * @param hostsArray array of hosts to try successively * @param connectTimeout maximum wait time to open connection * @param readTimeout maximum time to read data on socket * @return a JSONObject containing the resulting data or error * @throws AlgoliaException if the request data is not valid json */ private synchronized JSONObject _request(Method m, String url, String json, List<String> hostsArray, int connectTimeout, int readTimeout) throws AlgoliaException { String cacheKey = null; String jsonStr = null; if (isCacheEnabled) { cacheKey = String.format("%s:%s(%s)", m, url, json); jsonStr = cache.get(cacheKey); } try { if (jsonStr == null) { final byte[] requestRaw = _requestRaw(m, url, json, hostsArray, connectTimeout, readTimeout); jsonStr = new String(requestRaw, "UTF-8"); if (isCacheEnabled) { cache.put(cacheKey, jsonStr); } } return new JSONObject(jsonStr); } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("UTF-8 decode error:" + e.getMessage()); } } /** * Send the query according to parameters and returns its result as a JSONObject * * @param m HTTP Method to use * @param url endpoint URL * @param json optional JSON Object to send * @param hostsArray array of hosts to try successively * @param connectTimeout maximum wait time to open connection * @param readTimeout maximum time to read data on socket * @return a JSONObject containing the resulting data or error * @throws AlgoliaException in case of connection or data handling error */ private synchronized byte[] _requestRaw(Method m, String url, String json, List<String> hostsArray, int connectTimeout, int readTimeout) throws AlgoliaException { String requestMethod; HashMap<String, String> errors = new HashMap<String, String>(); // for each host for (String host : hostsArray) { switch (m) { case DELETE: requestMethod = "DELETE"; break; case GET: requestMethod = "GET"; break; case POST: requestMethod = "POST"; break; case PUT: requestMethod = "PUT"; break; default: throw new IllegalArgumentException("Method " + m + " is not supported"); } // set URL try { URL hostURL = new URL("https://" + host + url); HttpURLConnection hostConnection = (HttpURLConnection) hostURL.openConnection(); //set timeouts hostConnection.setRequestMethod(requestMethod); hostConnection.setConnectTimeout(connectTimeout); hostConnection.setReadTimeout(readTimeout); // set auth headers hostConnection.setRequestProperty("X-Algolia-Application-Id", this.applicationID); hostConnection.setRequestProperty("X-Algolia-API-Key", this.apiKey); for (Map.Entry<String, String> entry : headers.entrySet()) { hostConnection.setRequestProperty(entry.getKey(), entry.getValue()); } // set user agent hostConnection.setRequestProperty("User-Agent", "Algolia for Android " + version); // write JSON entity if (json != null) { if (!(requestMethod.equals("PUT") || requestMethod.equals("POST"))) { throw new IllegalArgumentException("Method " + m + " cannot enclose entity"); } hostConnection.setRequestProperty("Content-type", "application/json"); hostConnection.setDoOutput(true); StringEntity se = new StringEntity(json, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); se.writeTo(hostConnection.getOutputStream()); } // read response int code = hostConnection.getResponseCode(); final boolean codeIsError = code / 100 != 2; InputStream stream = codeIsError ? hostConnection.getErrorStream() : hostConnection.getInputStream(); final byte[] rawResponse; String encoding = hostConnection.getContentEncoding(); if (encoding != null && encoding.contains("gzip")) { rawResponse = _toByteArray(new GZIPInputStream(stream)); } else { rawResponse = _toByteArray(stream); } // handle http errors if (codeIsError) { if (code / 100 == 4) { String message = _getJSONObject(rawResponse).getString("message"); consumeQuietly(hostConnection); throw new AlgoliaException(message); } else { final String errorMessage = _toCharArray(stream); errors.put(host, errorMessage); consumeQuietly(hostConnection); throw new IOException(errorMessage); } } return rawResponse; } catch (JSONException e) { // fatal throw new AlgoliaException("JSON decode error:" + e.getMessage()); } catch (UnsupportedEncodingException e) { // fatal throw new AlgoliaException("Invalid JSON Object: " + json); } catch (IOException e) { // host error, continue on the next host addError(errors, host, e); } } StringBuilder builder = new StringBuilder("Hosts unreachable: "); Boolean first = true; for (Map.Entry<String, String> entry : errors.entrySet()) { if (!first) { builder.append(", "); } builder.append(entry.toString()); first = false; } throw new AlgoliaException(builder.toString()); } private void addError(HashMap<String, String> errors, String host, IOException e) { errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage())); } /** * Ensures that the entity content is fully consumed and the content stream, if exists, * is closed. */ private void consumeQuietly(final HttpURLConnection connection) { try { int read = 0; while (read != -1) { read = connection.getInputStream().read(); } connection.getInputStream().close(); read = 0; while (read != -1) { read = connection.getErrorStream().read(); } connection.getErrorStream().close(); connection.disconnect(); } catch (IOException e) { // no inputStream to close } } }
ApiClient: continue on HTTP errors
algoliasearch/src/main/java/com/algolia/search/saas/BaseAPIClient.java
ApiClient: continue on HTTP errors
<ide><path>lgoliasearch/src/main/java/com/algolia/search/saas/BaseAPIClient.java <ide> <ide> import android.support.annotation.NonNull; <ide> <add>import org.apache.http.HttpException; <ide> import org.apache.http.entity.StringEntity; <ide> import org.apache.http.message.BasicHeader; <ide> import org.apache.http.protocol.HTTP; <ide> throw new AlgoliaException(message); <ide> } else { <ide> final String errorMessage = _toCharArray(stream); <del> errors.put(host, errorMessage); <ide> consumeQuietly(hostConnection); <del> throw new IOException(errorMessage); <add> addError(errors, host, new HttpException(errorMessage)); <add> continue; <ide> } <ide> } <ide> return rawResponse; <ide> throw new AlgoliaException(builder.toString()); <ide> } <ide> <del> private void addError(HashMap<String, String> errors, String host, IOException e) { <add> private void addError(HashMap<String, String> errors, String host, Exception e) { <ide> errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage())); <ide> } <ide>
JavaScript
mit
b3f8a9f31563167e7b49c0973bd5889225375e12
0
bitsteller/witica,bitsteller/witica,bitsteller/witica
/*----------------------------------------------------------*/ /* This is the witica.js client library to access items */ /* from a witica WebTarget including base classes and */ /* common function to write your site specific renderers */ /*----------------------------------------------------------*/ /*-----------------------------------------*/ /* Witica: Namespace */ /*-----------------------------------------*/ var Witica = Witica || {}; Witica.util = Witica.util || {}; /*-----------------------------------------*/ /* Witica: globals */ /*-----------------------------------------*/ Witica.VERSION = "0.8.2" Witica.CACHESIZE = 10; Witica.itemcache = new Array(); Witica._knownHashes = new Array(); Witica.currentItemId = null; Witica.registeredRenderers = new Array(); Witica.mainView = null; Witica.defaultItemId = ""; Witica._virtualItemCount = 0; /*-----------------------------------------*/ /* Common extensions */ /*-----------------------------------------*/ Array.prototype.remove= function (index) { this.splice(index, 1); }; Array.prototype.insert = function (index, item) { this.splice(index, 0, item); }; Array.prototype.contains = function (item) { for (var i = 0; i < this.length; i++) { if (this[i] == item) { return true; } return false; }; } /*-----------------------------------------*/ /* Witica.util */ /*-----------------------------------------*/ Witica.util.timeUnits = { second: 1, minute: 60, hour: 3600, day: 86400, week: 604800, month: 2592000, year: 31536000 }; Witica.util.getHumanReadableDate = function(date) { var dateStr, amount, current = new Date().getTime(), diff = (current - date.getTime()) / 1000; if(diff > Witica.util.timeUnits.week) { dateStr = date.getFullYear() + "-"; if (date.getMonth()+1 < 10) dateStr += "0"; dateStr += (date.getMonth()+1) + "-"; if (date.getDate() < 10) dateStr += "0"; dateStr += date.getDate(); } else if(diff > Witica.util.timeUnits.day) { amount = Math.round(diff/Witica.util.timeUnits.day); dateStr = ((amount > 1) ? amount + " " + "days ago":"one day ago"); } else if(diff > Witica.util.timeUnits.hour) { amount = Math.round(diff/Witica.util.timeUnits.hour); dateStr = ((amount > 1) ? amount + " " + "hour" + "s":"an " + "hour") + " ago"; } else if(diff > Witica.util.timeUnits.minute) { amount = Math.round(diff/Witica.util.timeUnits.minute); dateStr = ((amount > 1) ? amount + " " + "minute" + "s":"a " + "minute") + " ago"; } else { dateStr = "a few seconds ago"; } return dateStr; }; Witica.util.shorten = function (html, maxLength) { plaintext = html.replace(/(<([^>]+)>)/ig,""); var shortstr = ""; var minLength = 0.8*maxLength; var sentences = plaintext.split(". "); var sentenceNo = 0; for (; shortstr.length < minLength && sentenceNo < sentences.length; sentenceNo++) { if ((shortstr.length + sentences[sentenceNo].length + ". ".length) <= maxLength) { shortstr += sentences[sentenceNo]; if (sentenceNo < sentences.length-1) { shortstr += ". "; } } else { var words = sentences[sentenceNo].split(" "); var wordNo = 0; for (; shortstr.length < minLength && wordNo < words.length; wordNo++) { if ((shortstr.length + words[wordNo].length + " ".length) <= maxLength-3) { shortstr += words[wordNo] + " "; } else { shortstr = plaintext.slice(0,maxLength-2); } }; shortstr = shortstr.slice(0,shortstr.length-1) + "..."; } } return shortstr; }; //Finds y value of given object Witica.util.getYCoord = function(element) { return element.offsetTop + (element.parentElement ? Witica.util.getYCoord(element.parentElement) : 0); }; Witica.util.Event = function () { this._listeners = new Array(); }; Witica.util.Event.prototype = { constructor: Witica.util.Event, addListener: function(context, callable) { var listener = {}; listener.context = context; listener.callable = callable; this._listeners.push(listener); }, removeListener: function(context, callable) { for (var i=0; i < this._listeners.length; i++){ if (this._listeners[i].context == context && this._listeners[i].callable == callable) { this._listeners.remove(i); i--; } } }, fire: function(argument) { for (var i=0; i < this._listeners.length; i++){ this._listeners[i].callable.call(this._listeners[i].context,argument); } }, getNumberOfListeners: function () { return this._listeners.length; } } /*-----------------------------------------*/ /* Witica: Item cache */ /*-----------------------------------------*/ Witica.Item = function (itemId, virtual) { this.isLoaded = false; this.itemId = itemId; this.metadata = null; this.contentfiles = new Array(); this.hash = null; this.lastUpdate = null; this.virtual = virtual; this.loadFinished = new Witica.util.Event(); if (this.virtual) { this.isLoaded = true; } }; Witica.Item.prototype.toString = function () { return this.itemId; }; Witica.Item.prototype._loadMeta = function(hash) { var http_request = new XMLHttpRequest(); http_request.open("GET", this.itemId + ".item" + "?bustCache=" + Math.random(), true); http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done) { if (http_request.status == ok) { this.metadata = JSON.parse(http_request.responseText); this.contentfiles = this.metadata["witica:contentfiles"]; } this.isLoaded = true; this.hash = hash; this.loadFinished.fire(this); } }.bind(this); http_request.send(null); }; Witica.Item.prototype.update = function () { if (this.virtual) { throw new Error("Virutal items cannot be updated."); } var http_request = new XMLHttpRequest(); http_request.open("GET", this.itemId + ".itemhash" + "?bustCache=" + Math.random(), true); http_request.onreadystatechange = function () { var done = 4, ok = 200, notfound = 404; if (http_request.readyState == done) { this.lastUpdate = new Date(); if (http_request.status == ok) { var newHash = http_request.responseText; if (this.hash != newHash) { this._loadMeta(newHash); } } //treat as non existing if item couldn't be loaded for the first time or was deleted, but not if it is in cache and only a network error occured during update else if ((this.hash != "" && http_request.readyState == notfound) || (this.hash == null)) { this.metadata = null; this.isLoaded = true; this.hash = ""; this.contentfiles = new Array(); this.loadFinished.fire(this); } } }.bind(this); http_request.send(null); }; Witica.Item.prototype.exists = function () { return !(this.metadata == null); }; Witica.Item.prototype.downloadContent = function (filename,callback) { //get file hash var hash = null; for (var i = 0; i < this.contentfiles.length; i++) { if (this.contentfiles[i].filename == filename) { hash = this.contentfiles[i].hash; } } if (hash == null) { throw new Error("Item '" + this.itemId + "' has no content file '" + filename + "'"); } var http_request = new XMLHttpRequest(); if (Witica._knownHashes.contains(hash)) { //file with same hash was requested before -> allow loading from cache http_request.open("GET", filename + "?bustCache=" + hash, true); } else { //new hash -> force redownloading file http_request.open("GET", filename + "?bustCache=" + Math.random(), true); } http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done && http_request.status == ok) { callback(http_request.responseText, true); } else if (http_request.readyState == done && http_request.status != ok) { callback(null,false); } }; http_request.send(null); //add file hash to the list of known hashes if (hash != "") { if (!Witica._knownHashes.contains(hash)) { Witica._knownHashes.push(hash); } } return http_request; }; Witica.Item.prototype.requestLoad = function (update, callback) { var requestObj = {}; requestObj.callback = callback; requestObj.item = this; requestObj.abort = function () { this.item.loadFinished.removeListener(this, this._finished); }; if (this.isLoaded) { callback(true); requestObj._finished = null; if (update) { requestObj._finished = function () { this.callback(true); } this.loadFinished.addListener(requestObj, requestObj._finished); } } else { requestObj._finished = function () { this.callback(true); if (!update) { this.item.loadFinished.removeListener(this, this._finished); } } this.loadFinished.addListener(requestObj, requestObj._finished); } return requestObj; } Witica.createVirtualItem = function (metadata) { var itemId = "witica:virtual-" + Witica._virtualItemCount; var item = new Witica.Item(itemId, true); item.metadata = metadata; Witica._virtualItemCount++; return item; }; Witica.updateItemCache = function () { currentTime = (new Date()).getTime(); len = Witica.itemcache.length; //console.log("Cached:"); for (var i = 0; i < len; i++) { var item = Witica.itemcache[i]; //console.log(item.itemId + "(" + item.loadFinished.getNumberOfListeners() + ")"); if (item.isLoaded) { //delete from cache if unused and cache full if (len > Witica.CACHESIZE && item.loadFinished.getNumberOfListeners() == 0) { Witica.itemcache.remove(i); len--; i--; continue; } //update item var nextUpdate = item.lastUpdate.getTime() + 600000; //if no modification time available, update every 10min if (item.exists() && item.metadata.hasOwnProperty("last-modified")) { //update at most every 60 sec, items with older modification date less often var interval = Math.round(150*Math.log(0.0001*((currentTime/1000)-item.metadata["last-modified"])+1)+30)*1000; if (interval < 1000) { //make sure interval is not negative (in case of wrong modification date) interval = 600000; } nextUpdate = item.lastUpdate.getTime() + interval; } if (currentTime >= nextUpdate) { item.update(); } } } setTimeout("Witica.updateItemCache()",10000); //update cache every 10s }; Witica.getItem = function (itemId) { //try to find in cache for (var i = Witica.itemcache.length - 1; i >= 0; i--) { if (Witica.itemcache[i].itemId == itemId) { Witica.itemcache[i].update(); return Witica.itemcache[i]; } }; //not in cache: download item add put in cache var item = new Witica.Item(itemId, false); item.update(); Witica.itemcache.push(item); return item; }; Witica.loadItem = function () { if (location.hash.indexOf("#!") == 0) { //location begins with #! var itemId = location.hash.substring(2).toLowerCase(); Witica.currentItemId = itemId; var item = Witica.getItem(itemId); Witica.mainView.showItem(item); } else { Witica.mainView.showItem(Witica.getItem(Witica.defaultItemId)); } }; /*-----------------------------------------*/ /* Witica: Views and renderer */ /*-----------------------------------------*/ Witica.View = function (element){ this.element = element; this.renderer = null; this.subviews = new Array(); this.item = null; this.params = {}; this._scrollToTopOnNextRenderRequest = false; this._itemLoadRequest = null; }; Witica.View.prototype = { showItem: function (item, params) { //update hash if main view and item not virtual if (this == Witica.mainView && (!item.virtual)) { window.onhashchange = null; location.hash = "#!" + item.itemId; Witica.currentItemId = item.itemId; window.onhashchange = Witica.loadItem; } //stop listening for updates of the previous item if (this.item) { this.item.loadFinished.removeListener(this, this._showLoadedItem); } this.item = item; this.params = params; this._scrollToTopOnNextRenderRequest = true; //scroll to top when showItem() was called but not on item udpate this._itemLoadRequest = item.requestLoad(true, this._showLoadedItem.bind(this)); }, _showLoadedItem: function () { //find appropriate renderer var oldRenderer = this.renderer; var newRendererClass = null; for (var i = Witica.registeredRenderers.length - 1; i >= 0; i--) { try { if (Witica.registeredRenderers[i].supports(this.item)) { newRendererClass = Witica.registeredRenderers[i].renderer; break; } } catch (exception) { } }; if (newRendererClass == null) { this.showErrorMessage("Error 404: Not loaded", "Sorry, but the item with the ID '" + this.item.itemId + "' cannot be displayed, because no appropriate renderer was not found. " + '<br/><br/>Try the following: <ul><li>Click <a href="index.html">here</a> to go back to the start page.</li></ul>'); return; } //unrender and render if (oldRenderer != null && oldRenderer.constructor == newRendererClass) { this.renderer.changeItem(this.item, this.params); } else { if (oldRenderer != null) { oldRenderer.stopRendering(); oldRenderer.unrender(this); } this.renderer = new newRendererClass(this); this.renderer.initWithItem(this.item, oldRenderer, this.params); } if (this._scrollToTopOnNextRenderRequest && this == Witica.mainView && document.body.scrollTop > Witica.util.getYCoord(this.element)) { window.scrollTo(0,Witica.util.getYCoord(this.element)); } this._scrollToTopOnNextRenderRequest = false; }, loadSubviews: function (element) { if (!element) { element = this.element; } var viewElements = element.getElementsByTagName("view"); for (var i = 0; i < viewElements.length; i++) { var view = new Witica.View(viewElements[i]); var params = null; try { params = JSON.parse(viewElements[i].childNodes[0].textContent); } catch (e) { //ignore } view.showItem(Witica.getItem(viewElements[i].getAttribute("item")), params); this.subviews.push(view); }; }, destroy: function () { this._itemLoadRequest.abort(); //stop listening for updates for current item this.destroySubviews(); if (this.renderer != null) { this.renderer.stopRendering(); this.renderer.unrender(null); } }, destroySubviews: function () { for (var subview = this.subviews[0]; this.subviews.length > 0; subview = this.subviews[0]) { subview.destroy(); this.subviews.remove(0); }; }, showErrorMessage: function (title, body) { var error = {}; error.type = "error"; error.title = title error.description = body; errorItem = Witica.createVirtualItem(error); this.showItem(errorItem); } }; Witica.Renderer = function (){ this.view = null; this.item = null; this.renderRequests = Array(); this.rendered = false; this.params = {}; }; Witica.Renderer.prototype = { initWithItem: function (item, previousRenderer, params) { if (this.rendered) { this.view.showErrorMessage("Error", "Renderer is already initialized."); return; } if (params) { this.params = params; } else { this.params = {}; } this.item = item; if (this.item.isLoaded) { this.render(previousRenderer); this.rendered = true; } else { this.view.showErrorMessage("Error 404: Not loaded", "Sorry, but the item with the ID '" + this.item.itemId + "' was not loaded."); } }, changeItem: function (item, params) { if (!this.rendered) { this.view.showErrorMessage("Error", "Renderer is not initialized."); return; } if (params) { this.params = params; } else { this.params = {}; } this.stopRendering(); this.item = item; if (this.item.isLoaded) { this.unrender(this); this.render(this); } else { this.view.showErrorMessage("Error 404: Not loaded", "Sorry, but the item with the ID '" + this.item.itemId + "' was not loaded."); return; } }, requireContent: function(filename, callback) { var request = this.item.downloadContent(filename, function (content,success) { if (success) { callback(content); } }); this.addRenderRequest(request); return request; }, requireItem: function(item, callback) { var request = item.requestLoad(true, function (success) { if (success) { callback(); } }); this.addRenderRequest(request); return request; }, addRenderRequest: function (request) { this.renderRequests.push(request); }, stopRendering: function () { //stop requests spawned during rendering if necessary for (var i = 0; i < this.renderRequests.length; i++) { var request = this.renderRequests[i]; try { if(typeof request.abort == 'function') { request.abort(); } } catch (err) { //ignore } } this.renderRequests = []; } }; /*-----------------------------------------*/ /* Witica: Initialization */ /*-----------------------------------------*/ Witica.registerRenderer = function (renderer, supports) { supportFunction = null; if (typeof supports === "string") { supportFunction = function (item) { return item.metadata.type == supports; } } else { supportFunction = supports; } renderObj = {}; renderObj.renderer = renderer; renderObj.supports = supportFunction; Witica.registeredRenderers.push(renderObj); }; Witica.initWitica = function (mainView, defaultItemId) { Witica.mainView = mainView; Witica.defaultItemId = defaultItemId; window.onhashchange = Witica.loadItem; Witica.loadItem(); Witica.updateItemCache(); }
client/js/witica.js
/*----------------------------------------------------------*/ /* This is the witica.js client library to access items */ /* from a witica WebTarget including base classes and */ /* common function to write your site specific renderers */ /*----------------------------------------------------------*/ /*-----------------------------------------*/ /* Witica: Namespace */ /*-----------------------------------------*/ var Witica = Witica || {}; Witica.util = Witica.util || {}; /*-----------------------------------------*/ /* Witica: globals */ /*-----------------------------------------*/ Witica.VERSION = "0.8.2" Witica.CACHESIZE = 10; Witica.itemcache = new Array(); Witica._knownHashes = new Array(); Witica.currentItemId = null; Witica.registeredRenderers = new Array(); Witica.mainView = null; Witica.defaultItemId = ""; Witica._virtualItemCount = 0; /*-----------------------------------------*/ /* Common extensions */ /*-----------------------------------------*/ Array.prototype.remove= function (index) { this.splice(index, 1); }; Array.prototype.insert = function (index, item) { this.splice(index, 0, item); }; Array.prototype.contains = function (item) { for (var i = 0; i < this.length; i++) { if (this[i] == item) { return true; } return false; }; } /*-----------------------------------------*/ /* Witica.util */ /*-----------------------------------------*/ Witica.util.timeUnits = { second: 1, minute: 60, hour: 3600, day: 86400, week: 604800, month: 2592000, year: 31536000 }; Witica.util.getHumanReadableDate = function(date) { var dateStr, amount, current = new Date().getTime(), diff = (current - date.getTime()) / 1000; if(diff > Witica.util.timeUnits.week) { dateStr = date.getFullYear() + "-"; if (date.getMonth()+1 < 10) dateStr += "0"; dateStr += (date.getMonth()+1) + "-"; if (date.getDate() < 10) dateStr += "0"; dateStr += date.getDate(); } else if(diff > Witica.util.timeUnits.day) { amount = Math.round(diff/Witica.util.timeUnits.day); dateStr = ((amount > 1) ? amount + " " + "days ago":"one day ago"); } else if(diff > Witica.util.timeUnits.hour) { amount = Math.round(diff/Witica.util.timeUnits.hour); dateStr = ((amount > 1) ? amount + " " + "hour" + "s":"an " + "hour") + " ago"; } else if(diff > Witica.util.timeUnits.minute) { amount = Math.round(diff/Witica.util.timeUnits.minute); dateStr = ((amount > 1) ? amount + " " + "minute" + "s":"a " + "minute") + " ago"; } else { dateStr = "a few seconds ago"; } return dateStr; }; Witica.util.shorten = function (html, maxLength) { plaintext = html.replace(/(<([^>]+)>)/ig,""); var shortstr = ""; var minLength = 0.8*maxLength; var sentences = plaintext.split(". "); var sentenceNo = 0; for (; shortstr.length < minLength && sentenceNo < sentences.length; sentenceNo++) { if ((shortstr.length + sentences[sentenceNo].length + ". ".length) <= maxLength) { shortstr += sentences[sentenceNo]; if (sentenceNo < sentences.length-1) { shortstr += ". "; } } else { var words = sentences[sentenceNo].split(" "); var wordNo = 0; for (; shortstr.length < minLength && wordNo < words.length; wordNo++) { if ((shortstr.length + words[wordNo].length + " ".length) <= maxLength-3) { shortstr += words[wordNo] + " "; } else { shortstr = plaintext.slice(0,maxLength-2); } }; shortstr = shortstr.slice(0,shortstr.length-1) + "..."; } } return shortstr; }; //Finds y value of given object Witica.util.getYCoord = function(element) { return element.offsetTop + (element.parentElement ? Witica.util.getYCoord(element.parentElement) : 0); }; Witica.util.Event = function () { this._listeners = new Array(); }; Witica.util.Event.prototype = { constructor: Witica.util.Event, addListener: function(context, callable) { var listener = {}; listener.context = context; listener.callable = callable; this._listeners.push(listener); }, removeListener: function(context, callable) { for (var i=0; i < this._listeners.length; i++){ if (this._listeners[i].context == context && this._listeners[i].callable == callable) { this._listeners.remove(i); i--; } } }, fire: function(argument) { for (var i=0; i < this._listeners.length; i++){ this._listeners[i].callable.call(this._listeners[i].context,argument); } }, getNumberOfListeners: function () { return this._listeners.length; } } /*-----------------------------------------*/ /* Witica: Item cache */ /*-----------------------------------------*/ Witica.Item = function (itemId, virtual) { this.isLoaded = false; this.itemId = itemId; this.metadata = null; this.contentfiles = new Array(); this.hash = null; this.lastUpdate = null; this.virtual = virtual; this.loadFinished = new Witica.util.Event(); if (this.virtual) { this.isLoaded = true; } }; Witica.Item.prototype.toString = function () { return this.itemId; }; Witica.Item.prototype._loadMeta = function(hash) { var http_request = new XMLHttpRequest(); http_request.open("GET", this.itemId + ".item" + "?bustCache=" + Math.random(), true); http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done) { if (http_request.status == ok) { this.metadata = JSON.parse(http_request.responseText); this.contentfiles = this.metadata["witica:contentfiles"]; } this.isLoaded = true; this.hash = hash; this.loadFinished.fire(this); } }.bind(this); http_request.send(null); }; Witica.Item.prototype.update = function () { if (this.virtual) { throw new Error("Virutal items cannot be updated."); } var http_request = new XMLHttpRequest(); http_request.open("GET", this.itemId + ".itemhash" + "?bustCache=" + Math.random(), true); http_request.onreadystatechange = function () { var done = 4, ok = 200, notfound = 404; if (http_request.readyState == done) { this.lastUpdate = new Date(); if (http_request.status == ok) { var newHash = http_request.responseText; if (this.hash != newHash) { this._loadMeta(newHash); } } //treat as non existing if item couldn't be loaded for the first time or was deleted, but not if it is in cache and only a network error occured during update else if ((this.hash != "" && http_request.readyState == notfound) || (this.hash == null)) { this.metadata = null; this.isLoaded = true; this.hash = ""; this.contentfiles = new Array(); this.loadFinished.fire(this); } } }.bind(this); http_request.send(null); }; Witica.Item.prototype.exists = function () { return !(this.metadata == null); }; Witica.Item.prototype.downloadContent = function (filename,callback) { //get file hash var hash = null; for (var i = 0; i < this.contentfiles.length; i++) { if (this.contentfiles[i].filename == filename) { hash = this.contentfiles[i].hash; } } if (hash == null) { throw new Error("Item '" + this.itemId + "' has no content file '" + filename + "'"); } var http_request = new XMLHttpRequest(); if (Witica._knownHashes.contains(hash)) { //file with same hash was requested before -> allow loading from cache http_request.open("GET", filename + "?bustCache=" + hash, true); } else { //new hash -> force redownloading file http_request.open("GET", filename + "?bustCache=" + Math.random(), true); } http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done && http_request.status == ok) { callback(http_request.responseText, true); } else if (http_request.readyState == done && http_request.status != ok) { callback(null,false); } }; http_request.send(null); //add file hash to the list of known hashes if (hash != "") { if (!Witica._knownHashes.contains(hash)) { Witica._knownHashes.push(hash); } } return http_request; }; Witica.Item.prototype.requestLoad = function (update, callback) { var requestObj = {}; requestObj.callback = callback; requestObj.item = this; requestObj.abort = function () { this.item.loadFinished.removeListener(this, this._finished); }; if (this.isLoaded) { callback(true); requestObj._finished = null; if (update) { requestObj._finished = function () { this.callback(true); } this.loadFinished.addListener(requestObj, requestObj._finished); } } else { requestObj._finished = function () { this.callback(true); if (!update) { this.item.loadFinished.removeListener(this, this._finished); } } this.loadFinished.addListener(requestObj, requestObj._finished); } return requestObj; } Witica.createVirtualItem = function (metadata) { var itemId = "witica:virtual-" + Witica._virtualItemCount; var item = new Witica.Item(itemId, true); item.metadata = metadata; Witica._virtualItemCount++; return item; }; Witica.updateItemCache = function () { currentTime = (new Date()).getTime(); len = Witica.itemcache.length; //console.log("Cached:"); for (var i = 0; i < len; i++) { var item = Witica.itemcache[i]; //console.log(item.itemId + "(" + item.loadFinished.getNumberOfListeners() + ")"); if (item.isLoaded) { //delete from cache if unused and cache full if (len > Witica.CACHESIZE && item.loadFinished.getNumberOfListeners() == 0) { Witica.itemcache.remove(i); len--; i--; continue; } //update item var nextUpdate = item.lastUpdate.getTime() + 600000; //if no modification time available, update every 10min if (item.exists() && item.metadata.hasOwnProperty("last-modified")) { //update at most every 60 sec, items with older modification date less often var interval = Math.round(150*Math.log(0.0001*((currentTime/1000)-item.metadata["last-modified"])+1)+30)*1000; if (interval < 1000) { //make sure interval is not negative (in case of wrong modification date) interval = 600000; } nextUpdate = item.lastUpdate.getTime() + interval; } if (currentTime >= nextUpdate) { item.update(); } } } setTimeout("Witica.updateItemCache()",10000); //update cache every 10s }; Witica.getItem = function (itemId) { //try to find in cache for (var i = Witica.itemcache.length - 1; i >= 0; i--) { if (Witica.itemcache[i].itemId == itemId) { Witica.itemcache[i].update(); return Witica.itemcache[i]; } }; //not in cache: download item add put in cache var item = new Witica.Item(itemId, false); item.update(); Witica.itemcache.push(item); return item; }; Witica.loadItem = function () { if (location.hash.indexOf("#!") == 0) { //location begins with #! var itemId = location.hash.substring(2).toLowerCase(); Witica.currentItemId = itemId; var item = Witica.getItem(itemId); Witica.mainView.showItem(item); } else { Witica.mainView.showItem(Witica.getItem(Witica.defaultItemId)); } }; /*-----------------------------------------*/ /* Witica: Views and renderer */ /*-----------------------------------------*/ Witica.View = function (element){ this.element = element; this.renderer = null; this.subviews = new Array(); this.item = null; this.params = {}; this._scrollToTopOnNextRenderRequest = false; }; Witica.View.prototype = { showItem: function (item, params) { //update hash if main view and item not virtual if (this == Witica.mainView && (!item.virtual)) { window.onhashchange = null; location.hash = "#!" + item.itemId; Witica.currentItemId = item.itemId; window.onhashchange = Witica.loadItem; } //stop listening for updates of the previous item if (this.item) { this.item.loadFinished.removeListener(this, this._showLoadedItem); } this.item = item; this.params = params; this._scrollToTopOnNextRenderRequest = true; //scroll to top when showItem() was called but not on item udpate if (item.isLoaded) { this._showLoadedItem(); } item.loadFinished.addListener(this,this._showLoadedItem); //watch out for coming updates of the new item }, _showLoadedItem: function () { //find appropriate renderer var oldRenderer = this.renderer; var newRendererClass = null; for (var i = Witica.registeredRenderers.length - 1; i >= 0; i--) { try { if (Witica.registeredRenderers[i].supports(this.item)) { newRendererClass = Witica.registeredRenderers[i].renderer; break; } } catch (exception) { } }; if (newRendererClass == null) { this.showErrorMessage("Error 404: Not loaded", "Sorry, but the item with the ID '" + this.item.itemId + "' cannot be displayed, because no appropriate renderer was not found. " + '<br/><br/>Try the following: <ul><li>Click <a href="index.html">here</a> to go back to the start page.</li></ul>'); return; } //unrender and render if (oldRenderer != null && oldRenderer.constructor == newRendererClass) { this.renderer.changeItem(this.item, this.params); } else { if (oldRenderer != null) { oldRenderer.stopRendering(); oldRenderer.unrender(this); } this.renderer = new newRendererClass(this); this.renderer.initWithItem(this.item, oldRenderer, this.params); } if (this._scrollToTopOnNextRenderRequest && this == Witica.mainView && document.body.scrollTop > Witica.util.getYCoord(this.element)) { window.scrollTo(0,Witica.util.getYCoord(this.element)); } this._scrollToTopOnNextRenderRequest = false; }, loadSubviews: function (element) { if (!element) { element = this.element; } var viewElements = element.getElementsByTagName("view"); for (var i = 0; i < viewElements.length; i++) { var view = new Witica.View(viewElements[i]); var params = null; try { params = JSON.parse(viewElements[i].childNodes[0].textContent); } catch (e) { //ignore } view.showItem(Witica.getItem(viewElements[i].getAttribute("item")), params); this.subviews.push(view); }; }, destroy: function () { //stop listening for updates of the previous item this.item.loadFinished.removeListener(this, this._showLoadedItem); this.destroySubviews(); if (this.renderer != null) { this.renderer.stopRendering(); this.renderer.unrender(null); } }, destroySubviews: function () { for (var subview = this.subviews[0]; this.subviews.length > 0; subview = this.subviews[0]) { subview.destroy(); this.subviews.remove(0); }; }, showErrorMessage: function (title, body) { var error = {}; error.type = "error"; error.title = title error.description = body; errorItem = Witica.createVirtualItem(error); this.showItem(errorItem); } }; Witica.Renderer = function (){ this.view = null; this.item = null; this.renderRequests = Array(); this.rendered = false; this.params = {}; }; Witica.Renderer.prototype = { initWithItem: function (item, previousRenderer, params) { if (this.rendered) { this.view.showErrorMessage("Error", "Renderer is already initialized."); return; } if (params) { this.params = params; } else { this.params = {}; } this.item = item; if (this.item.isLoaded) { this.render(previousRenderer); this.rendered = true; } else { this.view.showErrorMessage("Error 404: Not loaded", "Sorry, but the item with the ID '" + this.item.itemId + "' was not loaded."); } }, changeItem: function (item, params) { if (!this.rendered) { this.view.showErrorMessage("Error", "Renderer is not initialized."); return; } if (params) { this.params = params; } else { this.params = {}; } this.stopRendering(); this.item = item; if (this.item.isLoaded) { this.unrender(this); this.render(this); } else { this.view.showErrorMessage("Error 404: Not loaded", "Sorry, but the item with the ID '" + this.item.itemId + "' was not loaded."); return; } }, requireContent: function(filename, callback) { var request = this.item.downloadContent(filename, function (content,success) { if (success) { callback(content); } }); this.addRenderRequest(request); return request; }, requireItem: function(item, callback) { var request = item.requestLoad(true, function (success) { if (success) { callback(); } }); this.addRenderRequest(request); return request; }, addRenderRequest: function (request) { this.renderRequests.push(request); }, stopRendering: function () { //stop requests spawned during rendering if necessary for (var i = 0; i < this.renderRequests.length; i++) { var request = this.renderRequests[i]; try { if(typeof request.abort == 'function') { request.abort(); } } catch (err) { //ignore } } this.renderRequests = []; } }; /*-----------------------------------------*/ /* Witica: Initialization */ /*-----------------------------------------*/ Witica.registerRenderer = function (renderer, supports) { supportFunction = null; if (typeof supports === "string") { supportFunction = function (item) { return item.metadata.type == supports; } } else { supportFunction = supports; } renderObj = {}; renderObj.renderer = renderer; renderObj.supports = supportFunction; Witica.registeredRenderers.push(renderObj); }; Witica.initWitica = function (mainView, defaultItemId) { Witica.mainView = mainView; Witica.defaultItemId = defaultItemId; window.onhashchange = Witica.loadItem; Witica.loadItem(); Witica.updateItemCache(); }
Refactoring: use loadRequest in View.showItem()
client/js/witica.js
Refactoring: use loadRequest in View.showItem()
<ide><path>lient/js/witica.js <ide> this.item = null; <ide> this.params = {}; <ide> this._scrollToTopOnNextRenderRequest = false; <add> this._itemLoadRequest = null; <ide> }; <ide> <ide> Witica.View.prototype = { <ide> this.item = item; <ide> this.params = params; <ide> this._scrollToTopOnNextRenderRequest = true; //scroll to top when showItem() was called but not on item udpate <del> if (item.isLoaded) { <del> this._showLoadedItem(); <del> } <del> item.loadFinished.addListener(this,this._showLoadedItem); //watch out for coming updates of the new item <add> <add> this._itemLoadRequest = item.requestLoad(true, this._showLoadedItem.bind(this)); <ide> }, <ide> <ide> _showLoadedItem: function () { <ide> }, <ide> <ide> destroy: function () { <del> //stop listening for updates of the previous item <del> this.item.loadFinished.removeListener(this, this._showLoadedItem); <add> this._itemLoadRequest.abort(); //stop listening for updates for current item <ide> <ide> this.destroySubviews(); <ide> if (this.renderer != null) {
Java
bsd-3-clause
704717a0d87c5b961eda15ac724373a49631614c
0
Open-MBEE/MDK,Open-MBEE/MDK
/******************************************************************************* * Copyright (c) <2013>, California Institute of Technology ("Caltech"). * U.S. Government sponsorship acknowledged. * * 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 Caltech nor its operating division, the Jet Propulsion Laboratory, * 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 gov.nasa.jpl.mbee.ems.validation.actions; import gov.nasa.jpl.mbee.DocGen3Profile; import gov.nasa.jpl.mbee.ems.ExportUtility; import gov.nasa.jpl.mbee.ems.ImportUtility; import gov.nasa.jpl.mbee.ems.sync.AutoSyncCommitListener; import gov.nasa.jpl.mbee.ems.sync.ProjectListenerMapping; import gov.nasa.jpl.mbee.generator.DocumentGenerator; import gov.nasa.jpl.mbee.lib.Utils; import gov.nasa.jpl.mbee.model.Document; import gov.nasa.jpl.mbee.viewedit.ViewHierarchyVisitor; import gov.nasa.jpl.mgss.mbee.docgen.validation.IRuleViolationAction; import gov.nasa.jpl.mgss.mbee.docgen.validation.RuleViolationAction; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.uml2.uml.AggregationKind; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.nomagic.magicdraw.annotation.Annotation; import com.nomagic.magicdraw.annotation.AnnotationAction; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.openapi.uml.ModelElementsManager; import com.nomagic.magicdraw.openapi.uml.ReadOnlyElementException; import com.nomagic.magicdraw.openapi.uml.SessionManager; import com.nomagic.uml2.ext.jmi.helpers.ModelHelper; import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKindEnum; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Association; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Type; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; import com.nomagic.uml2.impl.ElementsFactory; public class ImportHierarchy extends RuleViolationAction implements AnnotationAction, IRuleViolationAction { private static final long serialVersionUID = 1L; private Element view; private JSONObject keyed; private JSONObject md; public ImportHierarchy(Element e, JSONObject md, JSONObject keyed) { super("ImportHierarchy", "Import Hierarchy", null, null); this.view = e; this.keyed = keyed; this.md = md; } @Override public boolean canExecute(Collection<Annotation> arg0) { return false; } @Override public void execute(Collection<Annotation> annos) { /*Collection<Annotation> toremove = new ArrayList<Annotation>(); for (Annotation anno : annos) { Element e = (Element) anno.getTarget(); if (importHierarchy(e)) { toremove.add(anno); } } if (!toremove.isEmpty()) { this.removeViolationsAndUpdateWindow(toremove); }*/ } @Override public void actionPerformed(ActionEvent e) { Project project = Application.getInstance().getProject(); Map<String, ?> projectInstances = ProjectListenerMapping.getInstance().get(project); AutoSyncCommitListener listener = (AutoSyncCommitListener)projectInstances.get("AutoSyncCommitListener"); if (listener != null) listener.disable(); SessionManager.getInstance().createSession("Change Hierarchy"); try { if (importHierarchy(view)) this.removeViolationAndUpdateWindow(); SessionManager.getInstance().closeSession(); } catch (Exception ex) { SessionManager.getInstance().cancelSession(); Utils.printException(ex); } } @SuppressWarnings("unchecked") private boolean importHierarchy(Element document) throws ReadOnlyElementException { ElementsFactory ef = Application.getInstance().getProject().getElementsFactory(); Stereotype viewS = Utils.getViewClassStereotype(); Map<String, List<Property>> viewId2props = new HashMap<String, List<Property>>(); //curate all properties in current model with type of view that's referenced on mms for (Object vid: keyed.keySet()) { String viewid = (String)vid; Element view = ExportUtility.getElementFromID(viewid); if (view != null && view instanceof Class) { for (Property p: ((Class)view).getOwnedAttribute()) { Type t = p.getType(); if (keyed.keySet().contains(t.getID())) { List<Property> viewprops = viewId2props.get(t.getID()); if (viewprops == null) { viewprops = new ArrayList<Property>(); viewId2props.put(t.getID(), viewprops); } viewprops.add(p); } } } else { //create the view } } for (Object vid: keyed.keySet()) { //go through all parent views on mms String viewid = (String)vid; JSONArray children = (JSONArray)keyed.get(vid); List<Property> cprops = new ArrayList<Property>(); //new owned attribute array for the parent view Element view = ExportUtility.getElementFromID(viewid); if (view != null && view instanceof Class) { for (Object cid: children) { //for all children views String childId = (String)cid; List<Property> availableProps = viewId2props.get(childId); //get a list of properties we can repurpose with type of the child view if (availableProps == null || availableProps.isEmpty()) { //no free property available, make one Element cview = ExportUtility.getElementFromID(childId); if (cview instanceof Type) { Association association = ef.createAssociationInstance(); //ModelHelper.setSupplierElement(association, viewType); Property propType1 = ModelHelper.getFirstMemberEnd(association); propType1.setName(((NamedElement)cview).getName().toLowerCase()); propType1.setAggregation(AggregationKindEnum.COMPOSITE); propType1.setType((Type)cview); ModelHelper.setNavigable(propType1, true); Stereotype partPropertyST = Utils.getStereotype("PartProperty"); StereotypesHelper.addStereotype(propType1, partPropertyST); Property propType2 = ModelHelper.getSecondMemberEnd(association); propType2.setType((Type)view); propType2.setOwner(association); //ModelHelper.setClientElement(association, document); association.setOwner(document.getOwner()); cprops.add(propType1); } } else { //add the property to owned attribute array cprops.add(availableProps.remove(0)); } } for (Property p: ((Class)view).getOwnedAttribute()) { //keep any non view owned attribute ("regular" attribute) if (p.getType() == null || !StereotypesHelper.hasStereotypeOrDerived(p.getType(), viewS)) { cprops.add(p); } } // ((Class)view).getOwnedAttribute().clear(); ((Class)view).getOwnedAttribute().addAll(cprops); } } for (List<Property> props: viewId2props.values()) { for (Property p: props) { ModelElementsManager.getInstance().removeElement(p); } } return true; /* // go through all web child elements for (String webChild : webChildrenObjectArray) { // is element in MagicDraw? // Checking if element with MagicDraw ID exists is possible - but no guarantee of element being in the correct hierarchy // Comparing document child elements of Alfresco and MagicDraw boolean isElementInMagicDraw = false; for (String modelChild : modelChildrenObjectArray) { if(webChild.equals(modelChild)){ isElementInMagicDraw = true; break; } } // add element to MagicDraw if necessary Element viewType = null; if(isElementInMagicDraw){ continue; } else{ // check if Magicdraw View Class exists boolean magicDrawViewClassExists = false; viewType = (Element) project.getElementByID((String) webChild); if(viewType != null){ magicDrawViewClassExists = true; } // create Magicdraw View Class if it doesn't exist if(!magicDrawViewClassExists){ // get JSON of Alfresco element String elementUrl = "https://ems-stg.jpl.nasa.gov/alfresco/service/workspaces/master/elements/" + webChild; String elementResponse = ExportUtility.get(elementUrl, false); if (docresponse == null) return false; JSONObject elementJSONResponse = (JSONObject) JSONValue.parse(elementResponse); JSONArray elementJSONArray = (JSONArray) elementJSONResponse.get("elements"); JSONObject elementJSONObject = (JSONObject) elementJSONArray.get(0); // create new MagicDraw view class com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class newClass = ef.createClassInstance(); // set class name String elementName = (String)elementJSONObject.get("name"); newClass.setName(elementName); // place class under the same owner as document view Element owner = ExportUtility.getElementFromID(view.getOwner().getID()); newClass.setOwner(owner); // add view stereotype Stereotype sysmlView = Utils.getViewClassStereotype(); StereotypesHelper.addStereotype(newClass, sysmlView); viewType = newClass; } // define association and part property Association association = ef.createAssociationInstance(); ModelHelper.setSupplierElement(association, viewType); Property propType1 = ModelHelper.getFirstMemberEnd(association); propType1.setName(((NamedElement)viewType).getName().toLowerCase()); propType1.setAggregation(AggregationKindEnum.COMPOSITE); ModelHelper.setNavigable(propType1, true); Stereotype partPropertyST = Utils.getStereotype("PartProperty"); StereotypesHelper.addStereotype(propType1, partPropertyST); propType1.setOwner(document); ModelHelper.setClientElement(association, document); // set id of part property identical to Alfresco element // class can have any id. // propType1.setID((String) webChild); // association owner association.setOwner(document.getOwner()); // go recursively through all children elements ? } } // go through all model child elements // if MagicDraw element not in Alfresco, delete it in MagicDraw return true;*/ } }
src/main/java/gov/nasa/jpl/mbee/ems/validation/actions/ImportHierarchy.java
/******************************************************************************* * Copyright (c) <2013>, California Institute of Technology ("Caltech"). * U.S. Government sponsorship acknowledged. * * 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 Caltech nor its operating division, the Jet Propulsion Laboratory, * 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 gov.nasa.jpl.mbee.ems.validation.actions; import gov.nasa.jpl.mbee.DocGen3Profile; import gov.nasa.jpl.mbee.ems.ExportUtility; import gov.nasa.jpl.mbee.ems.ImportUtility; import gov.nasa.jpl.mbee.ems.sync.AutoSyncCommitListener; import gov.nasa.jpl.mbee.ems.sync.ProjectListenerMapping; import gov.nasa.jpl.mbee.generator.DocumentGenerator; import gov.nasa.jpl.mbee.lib.Utils; import gov.nasa.jpl.mbee.model.Document; import gov.nasa.jpl.mbee.viewedit.ViewHierarchyVisitor; import gov.nasa.jpl.mgss.mbee.docgen.validation.IRuleViolationAction; import gov.nasa.jpl.mgss.mbee.docgen.validation.RuleViolationAction; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.uml2.uml.AggregationKind; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.nomagic.magicdraw.annotation.Annotation; import com.nomagic.magicdraw.annotation.AnnotationAction; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.openapi.uml.ModelElementsManager; import com.nomagic.magicdraw.openapi.uml.ReadOnlyElementException; import com.nomagic.magicdraw.openapi.uml.SessionManager; import com.nomagic.uml2.ext.jmi.helpers.ModelHelper; import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.AggregationKindEnum; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Association; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Type; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; import com.nomagic.uml2.impl.ElementsFactory; public class ImportHierarchy extends RuleViolationAction implements AnnotationAction, IRuleViolationAction { private static final long serialVersionUID = 1L; private Element view; private JSONObject keyed; private JSONObject md; public ImportHierarchy(Element e, JSONObject md, JSONObject keyed) { super("ImportHierarchy", "Import Hierarchy", null, null); this.view = e; this.keyed = keyed; this.md = md; } @Override public boolean canExecute(Collection<Annotation> arg0) { return false; } @Override public void execute(Collection<Annotation> annos) { /*Collection<Annotation> toremove = new ArrayList<Annotation>(); for (Annotation anno : annos) { Element e = (Element) anno.getTarget(); if (importHierarchy(e)) { toremove.add(anno); } } if (!toremove.isEmpty()) { this.removeViolationsAndUpdateWindow(toremove); }*/ } @Override public void actionPerformed(ActionEvent e) { Project project = Application.getInstance().getProject(); Map<String, ?> projectInstances = ProjectListenerMapping.getInstance().get(project); AutoSyncCommitListener listener = (AutoSyncCommitListener)projectInstances.get("AutoSyncCommitListener"); if (listener != null) listener.disable(); SessionManager.getInstance().createSession("Change Hierarchy"); try { if (importHierarchy(view)) this.removeViolationAndUpdateWindow(); SessionManager.getInstance().closeSession(); } catch (Exception ex) { SessionManager.getInstance().cancelSession(); Utils.printException(ex); } } @SuppressWarnings("unchecked") private boolean importHierarchy(Element document) throws ReadOnlyElementException { ElementsFactory ef = Application.getInstance().getProject().getElementsFactory(); Stereotype viewS = Utils.getViewClassStereotype(); Map<String, List<Property>> viewId2props = new HashMap<String, List<Property>>(); //curate all properties in current model with type of view that's referenced on mms for (Object vid: keyed.keySet()) { String viewid = (String)vid; Element view = ExportUtility.getElementFromID(viewid); if (view != null && view instanceof Class) { for (Property p: ((Class)view).getOwnedAttribute()) { Type t = p.getType(); if (keyed.keySet().contains(t.getID())) { List<Property> viewprops = viewId2props.get(t.getID()); if (viewprops == null) { viewprops = new ArrayList<Property>(); viewId2props.put(t.getID(), viewprops); } viewprops.add(p); } } } else { //create the view } } for (Object vid: keyed.keySet()) { String viewid = (String)vid; JSONArray children = (JSONArray)keyed.get(vid); List<Property> cprops = new ArrayList<Property>(); Element view = ExportUtility.getElementFromID(viewid); if (view != null && view instanceof Class) { for (Object cid: children) { String childId = (String)cid; List<Property> availableProps = viewId2props.get(childId); if (availableProps == null || availableProps.isEmpty()) { Element cview = ExportUtility.getElementFromID(childId); if (cview instanceof Type) { Association association = ef.createAssociationInstance(); //ModelHelper.setSupplierElement(association, viewType); Property propType1 = ModelHelper.getFirstMemberEnd(association); propType1.setName(((NamedElement)cview).getName().toLowerCase()); propType1.setAggregation(AggregationKindEnum.COMPOSITE); propType1.setType((Type)cview); ModelHelper.setNavigable(propType1, true); Stereotype partPropertyST = Utils.getStereotype("PartProperty"); StereotypesHelper.addStereotype(propType1, partPropertyST); Property propType2 = ModelHelper.getSecondMemberEnd(association); propType2.setType((Type)view); propType2.setOwner(association); //ModelHelper.setClientElement(association, document); association.setOwner(document.getOwner()); cprops.add(propType1); } } else { cprops.add(availableProps.remove(0)); } } for (Property p: ((Class)view).getOwnedAttribute()) { if (p.getType() == null || !StereotypesHelper.hasStereotypeOrDerived(p.getType(), viewS)) { cprops.add(p); } } ((Class)view).getOwnedAttribute().clear(); ((Class)view).getOwnedAttribute().addAll(cprops); } } for (List<Property> props: viewId2props.values()) { for (Property p: props) { ModelElementsManager.getInstance().removeElement(p); } } return true; /* // go through all web child elements for (String webChild : webChildrenObjectArray) { // is element in MagicDraw? // Checking if element with MagicDraw ID exists is possible - but no guarantee of element being in the correct hierarchy // Comparing document child elements of Alfresco and MagicDraw boolean isElementInMagicDraw = false; for (String modelChild : modelChildrenObjectArray) { if(webChild.equals(modelChild)){ isElementInMagicDraw = true; break; } } // add element to MagicDraw if necessary Element viewType = null; if(isElementInMagicDraw){ continue; } else{ // check if Magicdraw View Class exists boolean magicDrawViewClassExists = false; viewType = (Element) project.getElementByID((String) webChild); if(viewType != null){ magicDrawViewClassExists = true; } // create Magicdraw View Class if it doesn't exist if(!magicDrawViewClassExists){ // get JSON of Alfresco element String elementUrl = "https://ems-stg.jpl.nasa.gov/alfresco/service/workspaces/master/elements/" + webChild; String elementResponse = ExportUtility.get(elementUrl, false); if (docresponse == null) return false; JSONObject elementJSONResponse = (JSONObject) JSONValue.parse(elementResponse); JSONArray elementJSONArray = (JSONArray) elementJSONResponse.get("elements"); JSONObject elementJSONObject = (JSONObject) elementJSONArray.get(0); // create new MagicDraw view class com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class newClass = ef.createClassInstance(); // set class name String elementName = (String)elementJSONObject.get("name"); newClass.setName(elementName); // place class under the same owner as document view Element owner = ExportUtility.getElementFromID(view.getOwner().getID()); newClass.setOwner(owner); // add view stereotype Stereotype sysmlView = Utils.getViewClassStereotype(); StereotypesHelper.addStereotype(newClass, sysmlView); viewType = newClass; } // define association and part property Association association = ef.createAssociationInstance(); ModelHelper.setSupplierElement(association, viewType); Property propType1 = ModelHelper.getFirstMemberEnd(association); propType1.setName(((NamedElement)viewType).getName().toLowerCase()); propType1.setAggregation(AggregationKindEnum.COMPOSITE); ModelHelper.setNavigable(propType1, true); Stereotype partPropertyST = Utils.getStereotype("PartProperty"); StereotypesHelper.addStereotype(propType1, partPropertyST); propType1.setOwner(document); ModelHelper.setClientElement(association, document); // set id of part property identical to Alfresco element // class can have any id. // propType1.setID((String) webChild); // association owner association.setOwner(document.getOwner()); // go recursively through all children elements ? } } // go through all model child elements // if MagicDraw element not in Alfresco, delete it in MagicDraw return true;*/ } }
add more comments
src/main/java/gov/nasa/jpl/mbee/ems/validation/actions/ImportHierarchy.java
add more comments
<ide><path>rc/main/java/gov/nasa/jpl/mbee/ems/validation/actions/ImportHierarchy.java <ide> <ide> } <ide> } <del> for (Object vid: keyed.keySet()) { <add> for (Object vid: keyed.keySet()) { //go through all parent views on mms <ide> String viewid = (String)vid; <ide> JSONArray children = (JSONArray)keyed.get(vid); <del> List<Property> cprops = new ArrayList<Property>(); <add> List<Property> cprops = new ArrayList<Property>(); //new owned attribute array for the parent view <ide> Element view = ExportUtility.getElementFromID(viewid); <ide> if (view != null && view instanceof Class) { <del> for (Object cid: children) { <add> for (Object cid: children) { //for all children views <ide> String childId = (String)cid; <del> List<Property> availableProps = viewId2props.get(childId); <add> List<Property> availableProps = viewId2props.get(childId); <add> //get a list of properties we can repurpose with type of the child view <ide> if (availableProps == null || availableProps.isEmpty()) { <add> //no free property available, make one <ide> Element cview = ExportUtility.getElementFromID(childId); <ide> if (cview instanceof Type) { <ide> Association association = ef.createAssociationInstance(); <ide> cprops.add(propType1); <ide> } <ide> } else { <add> //add the property to owned attribute array <ide> cprops.add(availableProps.remove(0)); <ide> } <ide> } <ide> for (Property p: ((Class)view).getOwnedAttribute()) { <add> //keep any non view owned attribute ("regular" attribute) <ide> if (p.getType() == null || !StereotypesHelper.hasStereotypeOrDerived(p.getType(), viewS)) { <ide> cprops.add(p); <ide> } <ide> } <add> // <ide> ((Class)view).getOwnedAttribute().clear(); <ide> ((Class)view).getOwnedAttribute().addAll(cprops); <ide> }
Java
apache-2.0
f68f3dd7992a9583f5111407317dd3d0f7fc5daa
0
ndimiduk/hbase,mahak/hbase,Apache9/hbase,mahak/hbase,Apache9/hbase,mahak/hbase,ndimiduk/hbase,ndimiduk/hbase,mahak/hbase,apurtell/hbase,Apache9/hbase,ndimiduk/hbase,ndimiduk/hbase,apurtell/hbase,apurtell/hbase,mahak/hbase,apurtell/hbase,apurtell/hbase,mahak/hbase,Apache9/hbase,Apache9/hbase,mahak/hbase,Apache9/hbase,mahak/hbase,apurtell/hbase,Apache9/hbase,apurtell/hbase,Apache9/hbase,apurtell/hbase,ndimiduk/hbase,Apache9/hbase,ndimiduk/hbase,apurtell/hbase,mahak/hbase,Apache9/hbase,apurtell/hbase,ndimiduk/hbase,mahak/hbase,ndimiduk/hbase,ndimiduk/hbase
/** * * 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.hadoop.hbase.regionserver; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.regionserver.compactions.StripeCompactionPolicy; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ConcatenatedLists; import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableCollection; import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableList; /** * Stripe implementation of {@link StoreFileManager}. * Not thread safe - relies on external locking (in HStore). Collections that this class * returns are immutable or unique to the call, so they should be safe. * Stripe store splits the key space of the region into non-overlapping stripes, as well as * some recent files that have all the keys (level 0). Each stripe contains a set of files. * When L0 is compacted, it's split into the files corresponding to existing stripe boundaries, * that can thus be added to stripes. * When scan or get happens, it only has to read the files from the corresponding stripes. * See {@link StripeCompactionPolicy} on how the stripes are determined; this class doesn't care. * * This class should work together with {@link StripeCompactionPolicy} and * {@link org.apache.hadoop.hbase.regionserver.compactions.StripeCompactor}. * With regard to how they work, we make at least the following (reasonable) assumptions: * - Compaction produces one file per new stripe (if any); that is easy to change. * - Compaction has one contiguous set of stripes both in and out, except if L0 is involved. */ @InterfaceAudience.Private public class StripeStoreFileManager implements StoreFileManager, StripeCompactionPolicy.StripeInformationProvider { private static final Logger LOG = LoggerFactory.getLogger(StripeStoreFileManager.class); /** * The file metadata fields that contain the stripe information. */ public static final byte[] STRIPE_START_KEY = Bytes.toBytes("STRIPE_START_KEY"); public static final byte[] STRIPE_END_KEY = Bytes.toBytes("STRIPE_END_KEY"); private final static Bytes.RowEndKeyComparator MAP_COMPARATOR = new Bytes.RowEndKeyComparator(); /** * The key value used for range boundary, indicating that the boundary is open (i.e. +-inf). */ public final static byte[] OPEN_KEY = HConstants.EMPTY_BYTE_ARRAY; final static byte[] INVALID_KEY = null; /** * The state class. Used solely to replace results atomically during * compactions and avoid complicated error handling. */ private static class State { /** * The end rows of each stripe. The last stripe end is always open-ended, so it's not stored * here. It is invariant that the start row of the stripe is the end row of the previous one * (and is an open boundary for the first one). */ public byte[][] stripeEndRows = new byte[0][]; /** * Files by stripe. Each element of the list corresponds to stripeEndRow element with the * same index, except the last one. Inside each list, the files are in reverse order by * seqNum. Note that the length of this is one higher than that of stripeEndKeys. */ public ArrayList<ImmutableList<HStoreFile>> stripeFiles = new ArrayList<>(); /** Level 0. The files are in reverse order by seqNum. */ public ImmutableList<HStoreFile> level0Files = ImmutableList.of(); /** Cached list of all files in the structure, to return from some calls */ public ImmutableList<HStoreFile> allFilesCached = ImmutableList.of(); private ImmutableList<HStoreFile> allCompactedFilesCached = ImmutableList.of(); } private State state = null; /** Cached file metadata (or overrides as the case may be) */ private HashMap<HStoreFile, byte[]> fileStarts = new HashMap<>(); private HashMap<HStoreFile, byte[]> fileEnds = new HashMap<>(); /** Normally invalid key is null, but in the map null is the result for "no key"; so use * the following constant value in these maps instead. Note that this is a constant and * we use it to compare by reference when we read from the map. */ private static final byte[] INVALID_KEY_IN_MAP = new byte[0]; private final CellComparator cellComparator; private StripeStoreConfig config; private final int blockingFileCount; public StripeStoreFileManager( CellComparator kvComparator, Configuration conf, StripeStoreConfig config) { this.cellComparator = kvComparator; this.config = config; this.blockingFileCount = conf.getInt( HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT); } @Override public void loadFiles(List<HStoreFile> storeFiles) { loadUnclassifiedStoreFiles(storeFiles); } @Override public Collection<HStoreFile> getStorefiles() { return state.allFilesCached; } @Override public Collection<HStoreFile> getCompactedfiles() { return state.allCompactedFilesCached; } @Override public int getCompactedFilesCount() { return state.allCompactedFilesCached.size(); } @Override public void insertNewFiles(Collection<HStoreFile> sfs) throws IOException { CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(true); // Passing null does not cause NPE?? cmc.mergeResults(null, sfs); debugDumpState("Added new files"); } @Override public ImmutableCollection<HStoreFile> clearFiles() { ImmutableCollection<HStoreFile> result = state.allFilesCached; this.state = new State(); this.fileStarts.clear(); this.fileEnds.clear(); return result; } @Override public ImmutableCollection<HStoreFile> clearCompactedFiles() { ImmutableCollection<HStoreFile> result = state.allCompactedFilesCached; this.state = new State(); return result; } @Override public int getStorefileCount() { return state.allFilesCached.size(); } /** See {@link StoreFileManager#getCandidateFilesForRowKeyBefore(KeyValue)} * for details on this methods. */ @Override public Iterator<HStoreFile> getCandidateFilesForRowKeyBefore(final KeyValue targetKey) { KeyBeforeConcatenatedLists result = new KeyBeforeConcatenatedLists(); // Order matters for this call. result.addSublist(state.level0Files); if (!state.stripeFiles.isEmpty()) { int lastStripeIndex = findStripeForRow(CellUtil.cloneRow(targetKey), false); for (int stripeIndex = lastStripeIndex; stripeIndex >= 0; --stripeIndex) { result.addSublist(state.stripeFiles.get(stripeIndex)); } } return result.iterator(); } /** See {@link StoreFileManager#getCandidateFilesForRowKeyBefore(KeyValue)} and * {@link StoreFileManager#updateCandidateFilesForRowKeyBefore(Iterator, KeyValue, Cell)} * for details on this methods. */ @Override public Iterator<HStoreFile> updateCandidateFilesForRowKeyBefore( Iterator<HStoreFile> candidateFiles, final KeyValue targetKey, final Cell candidate) { KeyBeforeConcatenatedLists.Iterator original = (KeyBeforeConcatenatedLists.Iterator)candidateFiles; assert original != null; ArrayList<List<HStoreFile>> components = original.getComponents(); for (int firstIrrelevant = 0; firstIrrelevant < components.size(); ++firstIrrelevant) { HStoreFile sf = components.get(firstIrrelevant).get(0); byte[] endKey = endOf(sf); // Entries are ordered as such: L0, then stripes in reverse order. We never remove // level 0; we remove the stripe, and all subsequent ones, as soon as we find the // first one that cannot possibly have better candidates. if (!isInvalid(endKey) && !isOpen(endKey) && (nonOpenRowCompare(targetKey, endKey) >= 0)) { original.removeComponents(firstIrrelevant); break; } } return original; } /** * Override of getSplitPoint that determines the split point as the boundary between two * stripes, unless it causes significant imbalance between split sides' sizes. In that * case, the split boundary will be chosen from the middle of one of the stripes to * minimize imbalance. * @return The split point, or null if no split is possible. */ @Override public Optional<byte[]> getSplitPoint() throws IOException { if (this.getStorefileCount() == 0) { return Optional.empty(); } if (state.stripeFiles.size() <= 1) { return getSplitPointFromAllFiles(); } int leftIndex = -1, rightIndex = state.stripeFiles.size(); long leftSize = 0, rightSize = 0; long lastLeftSize = 0, lastRightSize = 0; while (rightIndex - 1 != leftIndex) { if (leftSize >= rightSize) { --rightIndex; lastRightSize = getStripeFilesSize(rightIndex); rightSize += lastRightSize; } else { ++leftIndex; lastLeftSize = getStripeFilesSize(leftIndex); leftSize += lastLeftSize; } } if (leftSize == 0 || rightSize == 0) { String errMsg = String.format("Cannot split on a boundary - left index %d size %d, " + "right index %d size %d", leftIndex, leftSize, rightIndex, rightSize); debugDumpState(errMsg); LOG.warn(errMsg); return getSplitPointFromAllFiles(); } double ratio = (double)rightSize / leftSize; if (ratio < 1) { ratio = 1 / ratio; } if (config.getMaxSplitImbalance() > ratio) { return Optional.of(state.stripeEndRows[leftIndex]); } // If the difference between the sides is too large, we could get the proportional key on // the a stripe to equalize the difference, but there's no proportional key method at the // moment, and it's not extremely important. // See if we can achieve better ratio if we split the bigger side in half. boolean isRightLarger = rightSize >= leftSize; double newRatio = isRightLarger ? getMidStripeSplitRatio(leftSize, rightSize, lastRightSize) : getMidStripeSplitRatio(rightSize, leftSize, lastLeftSize); if (newRatio < 1) { newRatio = 1 / newRatio; } if (newRatio >= ratio) { return Optional.of(state.stripeEndRows[leftIndex]); } LOG.debug("Splitting the stripe - ratio w/o split " + ratio + ", ratio with split " + newRatio + " configured ratio " + config.getMaxSplitImbalance()); // OK, we may get better ratio, get it. return StoreUtils.getSplitPoint(state.stripeFiles.get(isRightLarger ? rightIndex : leftIndex), cellComparator); } private Optional<byte[]> getSplitPointFromAllFiles() throws IOException { ConcatenatedLists<HStoreFile> sfs = new ConcatenatedLists<>(); sfs.addSublist(state.level0Files); sfs.addAllSublists(state.stripeFiles); return StoreUtils.getSplitPoint(sfs, cellComparator); } private double getMidStripeSplitRatio(long smallerSize, long largerSize, long lastLargerSize) { return (double)(largerSize - lastLargerSize / 2f) / (smallerSize + lastLargerSize / 2f); } @Override public Collection<HStoreFile> getFilesForScan(byte[] startRow, boolean includeStartRow, byte[] stopRow, boolean includeStopRow) { if (state.stripeFiles.isEmpty()) { return state.level0Files; // There's just L0. } int firstStripe = findStripeForRow(startRow, true); int lastStripe = findStripeForRow(stopRow, false); assert firstStripe <= lastStripe; if (firstStripe == lastStripe && state.level0Files.isEmpty()) { return state.stripeFiles.get(firstStripe); // There's just one stripe we need. } if (firstStripe == 0 && lastStripe == (state.stripeFiles.size() - 1)) { return state.allFilesCached; // We need to read all files. } ConcatenatedLists<HStoreFile> result = new ConcatenatedLists<>(); result.addAllSublists(state.stripeFiles.subList(firstStripe, lastStripe + 1)); result.addSublist(state.level0Files); return result; } @Override public void addCompactionResults( Collection<HStoreFile> compactedFiles, Collection<HStoreFile> results) throws IOException { // See class comment for the assumptions we make here. LOG.debug("Attempting to merge compaction results: " + compactedFiles.size() + " files replaced by " + results.size()); // In order to be able to fail in the middle of the operation, we'll operate on lazy // copies and apply the result at the end. CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(false); cmc.mergeResults(compactedFiles, results); markCompactedAway(compactedFiles); debugDumpState("Merged compaction results"); } // Mark the files as compactedAway once the storefiles and compactedfiles list is finalised // Let a background thread close the actual reader on these compacted files and also // ensure to evict the blocks from block cache so that they are no longer in // cache private void markCompactedAway(Collection<HStoreFile> compactedFiles) { for (HStoreFile file : compactedFiles) { file.markCompactedAway(); } } @Override public void removeCompactedFiles(Collection<HStoreFile> compactedFiles) throws IOException { // See class comment for the assumptions we make here. LOG.debug("Attempting to delete compaction results: " + compactedFiles.size()); // In order to be able to fail in the middle of the operation, we'll operate on lazy // copies and apply the result at the end. CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(false); cmc.deleteResults(compactedFiles); debugDumpState("Deleted compaction results"); } @Override public int getStoreCompactionPriority() { // If there's only L0, do what the default store does. // If we are in critical priority, do the same - we don't want to trump all stores all // the time due to how many files we have. int fc = getStorefileCount(); if (state.stripeFiles.isEmpty() || (this.blockingFileCount <= fc)) { return this.blockingFileCount - fc; } // If we are in good shape, we don't want to be trumped by all other stores due to how // many files we have, so do an approximate mapping to normal priority range; L0 counts // for all stripes. int l0 = state.level0Files.size(), sc = state.stripeFiles.size(); int priority = (int)Math.ceil(((double)(this.blockingFileCount - fc + l0) / sc) - l0); return (priority <= HStore.PRIORITY_USER) ? (HStore.PRIORITY_USER + 1) : priority; } /** * Gets the total size of all files in the stripe. * @param stripeIndex Stripe index. * @return Size. */ private long getStripeFilesSize(int stripeIndex) { long result = 0; for (HStoreFile sf : state.stripeFiles.get(stripeIndex)) { result += sf.getReader().length(); } return result; } /** * Loads initial store files that were picked up from some physical location pertaining to * this store (presumably). Unlike adding files after compaction, assumes empty initial * sets, and is forgiving with regard to stripe constraints - at worst, many/all files will * go to level 0. * @param storeFiles Store files to add. */ private void loadUnclassifiedStoreFiles(List<HStoreFile> storeFiles) { LOG.debug("Attempting to load " + storeFiles.size() + " store files."); TreeMap<byte[], ArrayList<HStoreFile>> candidateStripes = new TreeMap<>(MAP_COMPARATOR); ArrayList<HStoreFile> level0Files = new ArrayList<>(); // Separate the files into tentative stripes; then validate. Currently, we rely on metadata. // If needed, we could dynamically determine the stripes in future. for (HStoreFile sf : storeFiles) { byte[] startRow = startOf(sf), endRow = endOf(sf); // Validate the range and put the files into place. if (isInvalid(startRow) || isInvalid(endRow)) { insertFileIntoStripe(level0Files, sf); // No metadata - goes to L0. ensureLevel0Metadata(sf); } else if (!isOpen(startRow) && !isOpen(endRow) && nonOpenRowCompare(startRow, endRow) >= 0) { LOG.error("Unexpected metadata - start row [" + Bytes.toString(startRow) + "], end row [" + Bytes.toString(endRow) + "] in file [" + sf.getPath() + "], pushing to L0"); insertFileIntoStripe(level0Files, sf); // Bad metadata - goes to L0 also. ensureLevel0Metadata(sf); } else { ArrayList<HStoreFile> stripe = candidateStripes.get(endRow); if (stripe == null) { stripe = new ArrayList<>(); candidateStripes.put(endRow, stripe); } insertFileIntoStripe(stripe, sf); } } // Possible improvement - for variable-count stripes, if all the files are in L0, we can // instead create single, open-ended stripe with all files. boolean hasOverlaps = false; byte[] expectedStartRow = null; // first stripe can start wherever Iterator<Map.Entry<byte[], ArrayList<HStoreFile>>> entryIter = candidateStripes.entrySet().iterator(); while (entryIter.hasNext()) { Map.Entry<byte[], ArrayList<HStoreFile>> entry = entryIter.next(); ArrayList<HStoreFile> files = entry.getValue(); // Validate the file start rows, and remove the bad ones to level 0. for (int i = 0; i < files.size(); ++i) { HStoreFile sf = files.get(i); byte[] startRow = startOf(sf); if (expectedStartRow == null) { expectedStartRow = startRow; // ensure that first stripe is still consistent } else if (!rowEquals(expectedStartRow, startRow)) { hasOverlaps = true; LOG.warn("Store file doesn't fit into the tentative stripes - expected to start at [" + Bytes.toString(expectedStartRow) + "], but starts at [" + Bytes.toString(startRow) + "], to L0 it goes"); HStoreFile badSf = files.remove(i); insertFileIntoStripe(level0Files, badSf); ensureLevel0Metadata(badSf); --i; } } // Check if any files from the candidate stripe are valid. If so, add a stripe. byte[] endRow = entry.getKey(); if (!files.isEmpty()) { expectedStartRow = endRow; // Next stripe must start exactly at that key. } else { entryIter.remove(); } } // In the end, there must be open ends on two sides. If not, and there were no errors i.e. // files are consistent, they might be coming from a split. We will treat the boundaries // as open keys anyway, and log the message. // If there were errors, we'll play it safe and dump everything into L0. if (!candidateStripes.isEmpty()) { HStoreFile firstFile = candidateStripes.firstEntry().getValue().get(0); boolean isOpen = isOpen(startOf(firstFile)) && isOpen(candidateStripes.lastKey()); if (!isOpen) { LOG.warn("The range of the loaded files does not cover full key space: from [" + Bytes.toString(startOf(firstFile)) + "], to [" + Bytes.toString(candidateStripes.lastKey()) + "]"); if (!hasOverlaps) { ensureEdgeStripeMetadata(candidateStripes.firstEntry().getValue(), true); ensureEdgeStripeMetadata(candidateStripes.lastEntry().getValue(), false); } else { LOG.warn("Inconsistent files, everything goes to L0."); for (ArrayList<HStoreFile> files : candidateStripes.values()) { for (HStoreFile sf : files) { insertFileIntoStripe(level0Files, sf); ensureLevel0Metadata(sf); } } candidateStripes.clear(); } } } // Copy the results into the fields. State state = new State(); state.level0Files = ImmutableList.copyOf(level0Files); state.stripeFiles = new ArrayList<>(candidateStripes.size()); state.stripeEndRows = new byte[Math.max(0, candidateStripes.size() - 1)][]; ArrayList<HStoreFile> newAllFiles = new ArrayList<>(level0Files); int i = candidateStripes.size() - 1; for (Map.Entry<byte[], ArrayList<HStoreFile>> entry : candidateStripes.entrySet()) { state.stripeFiles.add(ImmutableList.copyOf(entry.getValue())); newAllFiles.addAll(entry.getValue()); if (i > 0) { state.stripeEndRows[state.stripeFiles.size() - 1] = entry.getKey(); } --i; } state.allFilesCached = ImmutableList.copyOf(newAllFiles); this.state = state; debugDumpState("Files loaded"); } private void ensureEdgeStripeMetadata(ArrayList<HStoreFile> stripe, boolean isFirst) { HashMap<HStoreFile, byte[]> targetMap = isFirst ? fileStarts : fileEnds; for (HStoreFile sf : stripe) { targetMap.put(sf, OPEN_KEY); } } private void ensureLevel0Metadata(HStoreFile sf) { if (!isInvalid(startOf(sf))) this.fileStarts.put(sf, INVALID_KEY_IN_MAP); if (!isInvalid(endOf(sf))) this.fileEnds.put(sf, INVALID_KEY_IN_MAP); } private void debugDumpState(String string) { if (!LOG.isDebugEnabled()) return; StringBuilder sb = new StringBuilder(); sb.append("\n" + string + "; current stripe state is as such:"); sb.append("\n level 0 with ") .append(state.level0Files.size()) .append( " files: " + TraditionalBinaryPrefix.long2String( StripeCompactionPolicy.getTotalFileSize(state.level0Files), "", 1) + ";"); for (int i = 0; i < state.stripeFiles.size(); ++i) { String endRow = (i == state.stripeEndRows.length) ? "(end)" : "[" + Bytes.toString(state.stripeEndRows[i]) + "]"; sb.append("\n stripe ending in ") .append(endRow) .append(" with ") .append(state.stripeFiles.get(i).size()) .append( " files: " + TraditionalBinaryPrefix.long2String( StripeCompactionPolicy.getTotalFileSize(state.stripeFiles.get(i)), "", 1) + ";"); } sb.append("\n").append(state.stripeFiles.size()).append(" stripes total."); sb.append("\n").append(getStorefileCount()).append(" files total."); LOG.debug(sb.toString()); } /** * Checks whether the key indicates an open interval boundary (i.e. infinity). */ private static final boolean isOpen(byte[] key) { return key != null && key.length == 0; } private static final boolean isOpen(Cell key) { return key != null && key.getRowLength() == 0; } /** * Checks whether the key is invalid (e.g. from an L0 file, or non-stripe-compacted files). */ private static final boolean isInvalid(byte[] key) { // No need to use Arrays.equals because INVALID_KEY is null return key == INVALID_KEY; } /** * Compare two keys for equality. */ private final boolean rowEquals(byte[] k1, byte[] k2) { return Bytes.equals(k1, 0, k1.length, k2, 0, k2.length); } /** * Compare two keys. Keys must not be open (isOpen(row) == false). */ private final int nonOpenRowCompare(byte[] k1, byte[] k2) { assert !isOpen(k1) && !isOpen(k2); return Bytes.compareTo(k1, k2); } private final int nonOpenRowCompare(Cell k1, byte[] k2) { assert !isOpen(k1) && !isOpen(k2); return cellComparator.compareRows(k1, k2, 0, k2.length); } /** * Finds the stripe index by end row. */ private final int findStripeIndexByEndRow(byte[] endRow) { assert !isInvalid(endRow); if (isOpen(endRow)) return state.stripeEndRows.length; return Arrays.binarySearch(state.stripeEndRows, endRow, Bytes.BYTES_COMPARATOR); } /** * Finds the stripe index for the stripe containing a row provided externally for get/scan. */ private final int findStripeForRow(byte[] row, boolean isStart) { if (isStart && Arrays.equals(row, HConstants.EMPTY_START_ROW)) return 0; if (!isStart && Arrays.equals(row, HConstants.EMPTY_END_ROW)) { return state.stripeFiles.size() - 1; } // If there's an exact match below, a stripe ends at "row". Stripe right boundary is // exclusive, so that means the row is in the next stripe; thus, we need to add one to index. // If there's no match, the return value of binarySearch is (-(insertion point) - 1), where // insertion point is the index of the next greater element, or list size if none. The // insertion point happens to be exactly what we need, so we need to add one to the result. return Math.abs(Arrays.binarySearch(state.stripeEndRows, row, Bytes.BYTES_COMPARATOR) + 1); } @Override public final byte[] getStartRow(int stripeIndex) { return (stripeIndex == 0 ? OPEN_KEY : state.stripeEndRows[stripeIndex - 1]); } @Override public final byte[] getEndRow(int stripeIndex) { return (stripeIndex == state.stripeEndRows.length ? OPEN_KEY : state.stripeEndRows[stripeIndex]); } private byte[] startOf(HStoreFile sf) { byte[] result = fileStarts.get(sf); // result and INVALID_KEY_IN_MAP are compared _only_ by reference on purpose here as the latter // serves only as a marker and is not to be confused with other empty byte arrays. // See Javadoc of INVALID_KEY_IN_MAP for more information return (result == null) ? sf.getMetadataValue(STRIPE_START_KEY) : result == INVALID_KEY_IN_MAP ? INVALID_KEY : result; } private byte[] endOf(HStoreFile sf) { byte[] result = fileEnds.get(sf); // result and INVALID_KEY_IN_MAP are compared _only_ by reference on purpose here as the latter // serves only as a marker and is not to be confused with other empty byte arrays. // See Javadoc of INVALID_KEY_IN_MAP for more information return (result == null) ? sf.getMetadataValue(STRIPE_END_KEY) : result == INVALID_KEY_IN_MAP ? INVALID_KEY : result; } /** * Inserts a file in the correct place (by seqnum) in a stripe copy. * @param stripe Stripe copy to insert into. * @param sf File to insert. */ private static void insertFileIntoStripe(ArrayList<HStoreFile> stripe, HStoreFile sf) { // The only operation for which sorting of the files matters is KeyBefore. Therefore, // we will store the file in reverse order by seqNum from the outset. for (int insertBefore = 0; ; ++insertBefore) { if (insertBefore == stripe.size() || (StoreFileComparators.SEQ_ID.compare(sf, stripe.get(insertBefore)) >= 0)) { stripe.add(insertBefore, sf); break; } } } /** * An extension of ConcatenatedLists that has several peculiar properties. * First, one can cut the tail of the logical list by removing last several sub-lists. * Second, items can be removed thru iterator. * Third, if the sub-lists are immutable, they are replaced with mutable copies when needed. * On average KeyBefore operation will contain half the stripes as potential candidates, * but will quickly cut down on them as it finds something in the more likely ones; thus, * the above allow us to avoid unnecessary copying of a bunch of lists. */ private static class KeyBeforeConcatenatedLists extends ConcatenatedLists<HStoreFile> { @Override public java.util.Iterator<HStoreFile> iterator() { return new Iterator(); } public class Iterator extends ConcatenatedLists<HStoreFile>.Iterator { public ArrayList<List<HStoreFile>> getComponents() { return components; } public void removeComponents(int startIndex) { List<List<HStoreFile>> subList = components.subList(startIndex, components.size()); for (List<HStoreFile> entry : subList) { size -= entry.size(); } assert size >= 0; subList.clear(); } @Override public void remove() { if (!this.nextWasCalled) { throw new IllegalStateException("No element to remove"); } this.nextWasCalled = false; List<HStoreFile> src = components.get(currentComponent); if (src instanceof ImmutableList<?>) { src = new ArrayList<>(src); components.set(currentComponent, src); } src.remove(indexWithinComponent); --size; --indexWithinComponent; if (src.isEmpty()) { components.remove(currentComponent); // indexWithinComponent is already -1 here. } } } } /** * Non-static helper class for merging compaction or flush results. * Since we want to merge them atomically (more or less), it operates on lazy copies, * then creates a new state object and puts it in place. */ private class CompactionOrFlushMergeCopy { private ArrayList<List<HStoreFile>> stripeFiles = null; private ArrayList<HStoreFile> level0Files = null; private ArrayList<byte[]> stripeEndRows = null; private Collection<HStoreFile> compactedFiles = null; private Collection<HStoreFile> results = null; private List<HStoreFile> l0Results = new ArrayList<>(); private final boolean isFlush; public CompactionOrFlushMergeCopy(boolean isFlush) { // Create a lazy mutable copy (other fields are so lazy they start out as nulls). this.stripeFiles = new ArrayList<>(StripeStoreFileManager.this.state.stripeFiles); this.isFlush = isFlush; } private void mergeResults(Collection<HStoreFile> compactedFiles, Collection<HStoreFile> results) throws IOException { assert this.compactedFiles == null && this.results == null; this.compactedFiles = compactedFiles; this.results = results; // Do logical processing. if (!isFlush) removeCompactedFiles(); TreeMap<byte[], HStoreFile> newStripes = processResults(); if (newStripes != null) { processNewCandidateStripes(newStripes); } // Create new state and update parent. State state = createNewState(false); StripeStoreFileManager.this.state = state; updateMetadataMaps(); } private void deleteResults(Collection<HStoreFile> compactedFiles) throws IOException { this.compactedFiles = compactedFiles; // Create new state and update parent. State state = createNewState(true); StripeStoreFileManager.this.state = state; updateMetadataMaps(); } private State createNewState(boolean delCompactedFiles) { State oldState = StripeStoreFileManager.this.state; // Stripe count should be the same unless the end rows changed. assert oldState.stripeFiles.size() == this.stripeFiles.size() || this.stripeEndRows != null; State newState = new State(); newState.level0Files = (this.level0Files == null) ? oldState.level0Files : ImmutableList.copyOf(this.level0Files); newState.stripeEndRows = (this.stripeEndRows == null) ? oldState.stripeEndRows : this.stripeEndRows.toArray(new byte[this.stripeEndRows.size()][]); newState.stripeFiles = new ArrayList<>(this.stripeFiles.size()); for (List<HStoreFile> newStripe : this.stripeFiles) { newState.stripeFiles.add(newStripe instanceof ImmutableList<?> ? (ImmutableList<HStoreFile>)newStripe : ImmutableList.copyOf(newStripe)); } List<HStoreFile> newAllFiles = new ArrayList<>(oldState.allFilesCached); List<HStoreFile> newAllCompactedFiles = new ArrayList<>(oldState.allCompactedFilesCached); if (!isFlush) { newAllFiles.removeAll(compactedFiles); if (delCompactedFiles) { newAllCompactedFiles.removeAll(compactedFiles); } else { newAllCompactedFiles.addAll(compactedFiles); } } if (results != null) { newAllFiles.addAll(results); } newState.allFilesCached = ImmutableList.copyOf(newAllFiles); newState.allCompactedFilesCached = ImmutableList.copyOf(newAllCompactedFiles); return newState; } private void updateMetadataMaps() { StripeStoreFileManager parent = StripeStoreFileManager.this; if (!isFlush) { for (HStoreFile sf : this.compactedFiles) { parent.fileStarts.remove(sf); parent.fileEnds.remove(sf); } } if (this.l0Results != null) { for (HStoreFile sf : this.l0Results) { parent.ensureLevel0Metadata(sf); } } } /** * @param index Index of the stripe we need. * @return A lazy stripe copy from current stripes. */ private final ArrayList<HStoreFile> getStripeCopy(int index) { List<HStoreFile> stripeCopy = this.stripeFiles.get(index); ArrayList<HStoreFile> result = null; if (stripeCopy instanceof ImmutableList<?>) { result = new ArrayList<>(stripeCopy); this.stripeFiles.set(index, result); } else { result = (ArrayList<HStoreFile>)stripeCopy; } return result; } /** * @return A lazy L0 copy from current state. */ private final ArrayList<HStoreFile> getLevel0Copy() { if (this.level0Files == null) { this.level0Files = new ArrayList<>(StripeStoreFileManager.this.state.level0Files); } return this.level0Files; } /** * Process new files, and add them either to the structure of existing stripes, * or to the list of new candidate stripes. * @return New candidate stripes. */ private TreeMap<byte[], HStoreFile> processResults() throws IOException { TreeMap<byte[], HStoreFile> newStripes = null; for (HStoreFile sf : this.results) { byte[] startRow = startOf(sf), endRow = endOf(sf); if (isInvalid(endRow) || isInvalid(startRow)) { if (!isFlush) { LOG.warn("The newly compacted file doesn't have stripes set: " + sf.getPath()); } insertFileIntoStripe(getLevel0Copy(), sf); this.l0Results.add(sf); continue; } if (!this.stripeFiles.isEmpty()) { int stripeIndex = findStripeIndexByEndRow(endRow); if ((stripeIndex >= 0) && rowEquals(getStartRow(stripeIndex), startRow)) { // Simple/common case - add file to an existing stripe. insertFileIntoStripe(getStripeCopy(stripeIndex), sf); continue; } } // Make a new candidate stripe. if (newStripes == null) { newStripes = new TreeMap<>(MAP_COMPARATOR); } HStoreFile oldSf = newStripes.put(endRow, sf); if (oldSf != null) { throw new IOException("Compactor has produced multiple files for the stripe ending in [" + Bytes.toString(endRow) + "], found " + sf.getPath() + " and " + oldSf.getPath()); } } return newStripes; } /** * Remove compacted files. */ private void removeCompactedFiles() throws IOException { for (HStoreFile oldFile : this.compactedFiles) { byte[] oldEndRow = endOf(oldFile); List<HStoreFile> source = null; if (isInvalid(oldEndRow)) { source = getLevel0Copy(); } else { int stripeIndex = findStripeIndexByEndRow(oldEndRow); if (stripeIndex < 0) { throw new IOException("An allegedly compacted file [" + oldFile + "] does not belong" + " to a known stripe (end row - [" + Bytes.toString(oldEndRow) + "])"); } source = getStripeCopy(stripeIndex); } if (!source.remove(oldFile)) { throw new IOException("An allegedly compacted file [" + oldFile + "] was not found"); } } } /** * See {@link #addCompactionResults(Collection, Collection)} - updates the stripe list with * new candidate stripes/removes old stripes; produces new set of stripe end rows. * @param newStripes New stripes - files by end row. */ private void processNewCandidateStripes( TreeMap<byte[], HStoreFile> newStripes) throws IOException { // Validate that the removed and added aggregate ranges still make for a full key space. boolean hasStripes = !this.stripeFiles.isEmpty(); this.stripeEndRows = new ArrayList<>(Arrays.asList(StripeStoreFileManager.this.state.stripeEndRows)); int removeFrom = 0; byte[] firstStartRow = startOf(newStripes.firstEntry().getValue()); byte[] lastEndRow = newStripes.lastKey(); if (!hasStripes && (!isOpen(firstStartRow) || !isOpen(lastEndRow))) { throw new IOException("Newly created stripes do not cover the entire key space."); } boolean canAddNewStripes = true; Collection<HStoreFile> filesForL0 = null; if (hasStripes) { // Determine which stripes will need to be removed because they conflict with new stripes. // The new boundaries should match old stripe boundaries, so we should get exact matches. if (isOpen(firstStartRow)) { removeFrom = 0; } else { removeFrom = findStripeIndexByEndRow(firstStartRow); if (removeFrom < 0) throw new IOException("Compaction is trying to add a bad range."); ++removeFrom; } int removeTo = findStripeIndexByEndRow(lastEndRow); if (removeTo < 0) throw new IOException("Compaction is trying to add a bad range."); // See if there are files in the stripes we are trying to replace. ArrayList<HStoreFile> conflictingFiles = new ArrayList<>(); for (int removeIndex = removeTo; removeIndex >= removeFrom; --removeIndex) { conflictingFiles.addAll(this.stripeFiles.get(removeIndex)); } if (!conflictingFiles.isEmpty()) { // This can be caused by two things - concurrent flush into stripes, or a bug. // Unfortunately, we cannot tell them apart without looking at timing or something // like that. We will assume we are dealing with a flush and dump it into L0. if (isFlush) { long newSize = StripeCompactionPolicy.getTotalFileSize(newStripes.values()); LOG.warn("Stripes were created by a flush, but results of size " + newSize + " cannot be added because the stripes have changed"); canAddNewStripes = false; filesForL0 = newStripes.values(); } else { long oldSize = StripeCompactionPolicy.getTotalFileSize(conflictingFiles); LOG.info(conflictingFiles.size() + " conflicting files (likely created by a flush) " + " of size " + oldSize + " are moved to L0 due to concurrent stripe change"); filesForL0 = conflictingFiles; } if (filesForL0 != null) { for (HStoreFile sf : filesForL0) { insertFileIntoStripe(getLevel0Copy(), sf); } l0Results.addAll(filesForL0); } } if (canAddNewStripes) { // Remove old empty stripes. int originalCount = this.stripeFiles.size(); for (int removeIndex = removeTo; removeIndex >= removeFrom; --removeIndex) { if (removeIndex != originalCount - 1) { this.stripeEndRows.remove(removeIndex); } this.stripeFiles.remove(removeIndex); } } } if (!canAddNewStripes) return; // Files were already put into L0. // Now, insert new stripes. The total ranges match, so we can insert where we removed. byte[] previousEndRow = null; int insertAt = removeFrom; for (Map.Entry<byte[], HStoreFile> newStripe : newStripes.entrySet()) { if (previousEndRow != null) { // Validate that the ranges are contiguous. assert !isOpen(previousEndRow); byte[] startRow = startOf(newStripe.getValue()); if (!rowEquals(previousEndRow, startRow)) { throw new IOException("The new stripes produced by " + (isFlush ? "flush" : "compaction") + " are not contiguous"); } } // Add the new stripe. ArrayList<HStoreFile> tmp = new ArrayList<>(); tmp.add(newStripe.getValue()); stripeFiles.add(insertAt, tmp); previousEndRow = newStripe.getKey(); if (!isOpen(previousEndRow)) { stripeEndRows.add(insertAt, previousEndRow); } ++insertAt; } } } @Override public List<HStoreFile> getLevel0Files() { return this.state.level0Files; } @Override public List<byte[]> getStripeBoundaries() { if (this.state.stripeFiles.isEmpty()) { return Collections.emptyList(); } ArrayList<byte[]> result = new ArrayList<>(this.state.stripeEndRows.length + 2); result.add(OPEN_KEY); Collections.addAll(result, this.state.stripeEndRows); result.add(OPEN_KEY); return result; } @Override public ArrayList<ImmutableList<HStoreFile>> getStripes() { return this.state.stripeFiles; } @Override public int getStripeCount() { return this.state.stripeFiles.size(); } @Override public Collection<HStoreFile> getUnneededFiles(long maxTs, List<HStoreFile> filesCompacting) { // 1) We can never get rid of the last file which has the maximum seqid in a stripe. // 2) Files that are not the latest can't become one due to (1), so the rest are fair game. State state = this.state; Collection<HStoreFile> expiredStoreFiles = null; for (ImmutableList<HStoreFile> stripe : state.stripeFiles) { expiredStoreFiles = findExpiredFiles(stripe, maxTs, filesCompacting, expiredStoreFiles); } return findExpiredFiles(state.level0Files, maxTs, filesCompacting, expiredStoreFiles); } private Collection<HStoreFile> findExpiredFiles(ImmutableList<HStoreFile> stripe, long maxTs, List<HStoreFile> filesCompacting, Collection<HStoreFile> expiredStoreFiles) { // Order by seqnum is reversed. for (int i = 1; i < stripe.size(); ++i) { HStoreFile sf = stripe.get(i); synchronized (sf) { long fileTs = sf.getReader().getMaxTimestamp(); if (fileTs < maxTs && !filesCompacting.contains(sf)) { LOG.info("Found an expired store file: " + sf.getPath() + " whose maxTimestamp is " + fileTs + ", which is below " + maxTs); if (expiredStoreFiles == null) { expiredStoreFiles = new ArrayList<>(); } expiredStoreFiles.add(sf); } } } return expiredStoreFiles; } @Override public double getCompactionPressure() { State stateLocal = this.state; if (stateLocal.allFilesCached.size() > blockingFileCount) { // just a hit to tell others that we have reached the blocking file count. return 2.0; } if (stateLocal.stripeFiles.isEmpty()) { return 0.0; } int blockingFilePerStripe = blockingFileCount / stateLocal.stripeFiles.size(); // do not calculate L0 separately because data will be moved to stripe quickly and in most cases // we flush data to stripe directly. int delta = stateLocal.level0Files.isEmpty() ? 0 : 1; double max = 0.0; for (ImmutableList<HStoreFile> stripeFile : stateLocal.stripeFiles) { int stripeFileCount = stripeFile.size(); double normCount = (double) (stripeFileCount + delta - config.getStripeCompactMinFiles()) / (blockingFilePerStripe - config.getStripeCompactMinFiles()); if (normCount >= 1.0) { // This could happen if stripe is not split evenly. Do not return values that larger than // 1.0 because we have not reached the blocking file count actually. return 1.0; } if (normCount > max) { max = normCount; } } return max; } @Override public Comparator<HStoreFile> getStoreFileComparator() { return StoreFileComparators.SEQ_ID; } }
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StripeStoreFileManager.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.hadoop.hbase.regionserver; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.regionserver.compactions.StripeCompactionPolicy; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ConcatenatedLists; import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableCollection; import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableList; /** * Stripe implementation of StoreFileManager. * Not thread safe - relies on external locking (in HStore). Collections that this class * returns are immutable or unique to the call, so they should be safe. * Stripe store splits the key space of the region into non-overlapping stripes, as well as * some recent files that have all the keys (level 0). Each stripe contains a set of files. * When L0 is compacted, it's split into the files corresponding to existing stripe boundaries, * that can thus be added to stripes. * When scan or get happens, it only has to read the files from the corresponding stripes. * See StripeCompationPolicy on how the stripes are determined; this class doesn't care. * * This class should work together with StripeCompactionPolicy and StripeCompactor. * With regard to how they work, we make at least the following (reasonable) assumptions: * - Compaction produces one file per new stripe (if any); that is easy to change. * - Compaction has one contiguous set of stripes both in and out, except if L0 is involved. */ @InterfaceAudience.Private public class StripeStoreFileManager implements StoreFileManager, StripeCompactionPolicy.StripeInformationProvider { private static final Logger LOG = LoggerFactory.getLogger(StripeStoreFileManager.class); /** * The file metadata fields that contain the stripe information. */ public static final byte[] STRIPE_START_KEY = Bytes.toBytes("STRIPE_START_KEY"); public static final byte[] STRIPE_END_KEY = Bytes.toBytes("STRIPE_END_KEY"); private final static Bytes.RowEndKeyComparator MAP_COMPARATOR = new Bytes.RowEndKeyComparator(); /** * The key value used for range boundary, indicating that the boundary is open (i.e. +-inf). */ public final static byte[] OPEN_KEY = HConstants.EMPTY_BYTE_ARRAY; final static byte[] INVALID_KEY = null; /** * The state class. Used solely to replace results atomically during * compactions and avoid complicated error handling. */ private static class State { /** * The end rows of each stripe. The last stripe end is always open-ended, so it's not stored * here. It is invariant that the start row of the stripe is the end row of the previous one * (and is an open boundary for the first one). */ public byte[][] stripeEndRows = new byte[0][]; /** * Files by stripe. Each element of the list corresponds to stripeEndRow element with the * same index, except the last one. Inside each list, the files are in reverse order by * seqNum. Note that the length of this is one higher than that of stripeEndKeys. */ public ArrayList<ImmutableList<HStoreFile>> stripeFiles = new ArrayList<>(); /** Level 0. The files are in reverse order by seqNum. */ public ImmutableList<HStoreFile> level0Files = ImmutableList.of(); /** Cached list of all files in the structure, to return from some calls */ public ImmutableList<HStoreFile> allFilesCached = ImmutableList.of(); private ImmutableList<HStoreFile> allCompactedFilesCached = ImmutableList.of(); } private State state = null; /** Cached file metadata (or overrides as the case may be) */ private HashMap<HStoreFile, byte[]> fileStarts = new HashMap<>(); private HashMap<HStoreFile, byte[]> fileEnds = new HashMap<>(); /** Normally invalid key is null, but in the map null is the result for "no key"; so use * the following constant value in these maps instead. Note that this is a constant and * we use it to compare by reference when we read from the map. */ private static final byte[] INVALID_KEY_IN_MAP = new byte[0]; private final CellComparator cellComparator; private StripeStoreConfig config; private final int blockingFileCount; public StripeStoreFileManager( CellComparator kvComparator, Configuration conf, StripeStoreConfig config) { this.cellComparator = kvComparator; this.config = config; this.blockingFileCount = conf.getInt( HStore.BLOCKING_STOREFILES_KEY, HStore.DEFAULT_BLOCKING_STOREFILE_COUNT); } @Override public void loadFiles(List<HStoreFile> storeFiles) { loadUnclassifiedStoreFiles(storeFiles); } @Override public Collection<HStoreFile> getStorefiles() { return state.allFilesCached; } @Override public Collection<HStoreFile> getCompactedfiles() { return state.allCompactedFilesCached; } @Override public int getCompactedFilesCount() { return state.allCompactedFilesCached.size(); } @Override public void insertNewFiles(Collection<HStoreFile> sfs) throws IOException { CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(true); // Passing null does not cause NPE?? cmc.mergeResults(null, sfs); debugDumpState("Added new files"); } @Override public ImmutableCollection<HStoreFile> clearFiles() { ImmutableCollection<HStoreFile> result = state.allFilesCached; this.state = new State(); this.fileStarts.clear(); this.fileEnds.clear(); return result; } @Override public ImmutableCollection<HStoreFile> clearCompactedFiles() { ImmutableCollection<HStoreFile> result = state.allCompactedFilesCached; this.state = new State(); return result; } @Override public int getStorefileCount() { return state.allFilesCached.size(); } /** See {@link StoreFileManager#getCandidateFilesForRowKeyBefore(KeyValue)} * for details on this methods. */ @Override public Iterator<HStoreFile> getCandidateFilesForRowKeyBefore(final KeyValue targetKey) { KeyBeforeConcatenatedLists result = new KeyBeforeConcatenatedLists(); // Order matters for this call. result.addSublist(state.level0Files); if (!state.stripeFiles.isEmpty()) { int lastStripeIndex = findStripeForRow(CellUtil.cloneRow(targetKey), false); for (int stripeIndex = lastStripeIndex; stripeIndex >= 0; --stripeIndex) { result.addSublist(state.stripeFiles.get(stripeIndex)); } } return result.iterator(); } /** See {@link StoreFileManager#getCandidateFilesForRowKeyBefore(KeyValue)} and * {@link StoreFileManager#updateCandidateFilesForRowKeyBefore(Iterator, KeyValue, Cell)} * for details on this methods. */ @Override public Iterator<HStoreFile> updateCandidateFilesForRowKeyBefore( Iterator<HStoreFile> candidateFiles, final KeyValue targetKey, final Cell candidate) { KeyBeforeConcatenatedLists.Iterator original = (KeyBeforeConcatenatedLists.Iterator)candidateFiles; assert original != null; ArrayList<List<HStoreFile>> components = original.getComponents(); for (int firstIrrelevant = 0; firstIrrelevant < components.size(); ++firstIrrelevant) { HStoreFile sf = components.get(firstIrrelevant).get(0); byte[] endKey = endOf(sf); // Entries are ordered as such: L0, then stripes in reverse order. We never remove // level 0; we remove the stripe, and all subsequent ones, as soon as we find the // first one that cannot possibly have better candidates. if (!isInvalid(endKey) && !isOpen(endKey) && (nonOpenRowCompare(targetKey, endKey) >= 0)) { original.removeComponents(firstIrrelevant); break; } } return original; } /** * Override of getSplitPoint that determines the split point as the boundary between two * stripes, unless it causes significant imbalance between split sides' sizes. In that * case, the split boundary will be chosen from the middle of one of the stripes to * minimize imbalance. * @return The split point, or null if no split is possible. */ @Override public Optional<byte[]> getSplitPoint() throws IOException { if (this.getStorefileCount() == 0) { return Optional.empty(); } if (state.stripeFiles.size() <= 1) { return getSplitPointFromAllFiles(); } int leftIndex = -1, rightIndex = state.stripeFiles.size(); long leftSize = 0, rightSize = 0; long lastLeftSize = 0, lastRightSize = 0; while (rightIndex - 1 != leftIndex) { if (leftSize >= rightSize) { --rightIndex; lastRightSize = getStripeFilesSize(rightIndex); rightSize += lastRightSize; } else { ++leftIndex; lastLeftSize = getStripeFilesSize(leftIndex); leftSize += lastLeftSize; } } if (leftSize == 0 || rightSize == 0) { String errMsg = String.format("Cannot split on a boundary - left index %d size %d, " + "right index %d size %d", leftIndex, leftSize, rightIndex, rightSize); debugDumpState(errMsg); LOG.warn(errMsg); return getSplitPointFromAllFiles(); } double ratio = (double)rightSize / leftSize; if (ratio < 1) { ratio = 1 / ratio; } if (config.getMaxSplitImbalance() > ratio) { return Optional.of(state.stripeEndRows[leftIndex]); } // If the difference between the sides is too large, we could get the proportional key on // the a stripe to equalize the difference, but there's no proportional key method at the // moment, and it's not extremely important. // See if we can achieve better ratio if we split the bigger side in half. boolean isRightLarger = rightSize >= leftSize; double newRatio = isRightLarger ? getMidStripeSplitRatio(leftSize, rightSize, lastRightSize) : getMidStripeSplitRatio(rightSize, leftSize, lastLeftSize); if (newRatio < 1) { newRatio = 1 / newRatio; } if (newRatio >= ratio) { return Optional.of(state.stripeEndRows[leftIndex]); } LOG.debug("Splitting the stripe - ratio w/o split " + ratio + ", ratio with split " + newRatio + " configured ratio " + config.getMaxSplitImbalance()); // OK, we may get better ratio, get it. return StoreUtils.getSplitPoint(state.stripeFiles.get(isRightLarger ? rightIndex : leftIndex), cellComparator); } private Optional<byte[]> getSplitPointFromAllFiles() throws IOException { ConcatenatedLists<HStoreFile> sfs = new ConcatenatedLists<>(); sfs.addSublist(state.level0Files); sfs.addAllSublists(state.stripeFiles); return StoreUtils.getSplitPoint(sfs, cellComparator); } private double getMidStripeSplitRatio(long smallerSize, long largerSize, long lastLargerSize) { return (double)(largerSize - lastLargerSize / 2f) / (smallerSize + lastLargerSize / 2f); } @Override public Collection<HStoreFile> getFilesForScan(byte[] startRow, boolean includeStartRow, byte[] stopRow, boolean includeStopRow) { if (state.stripeFiles.isEmpty()) { return state.level0Files; // There's just L0. } int firstStripe = findStripeForRow(startRow, true); int lastStripe = findStripeForRow(stopRow, false); assert firstStripe <= lastStripe; if (firstStripe == lastStripe && state.level0Files.isEmpty()) { return state.stripeFiles.get(firstStripe); // There's just one stripe we need. } if (firstStripe == 0 && lastStripe == (state.stripeFiles.size() - 1)) { return state.allFilesCached; // We need to read all files. } ConcatenatedLists<HStoreFile> result = new ConcatenatedLists<>(); result.addAllSublists(state.stripeFiles.subList(firstStripe, lastStripe + 1)); result.addSublist(state.level0Files); return result; } @Override public void addCompactionResults( Collection<HStoreFile> compactedFiles, Collection<HStoreFile> results) throws IOException { // See class comment for the assumptions we make here. LOG.debug("Attempting to merge compaction results: " + compactedFiles.size() + " files replaced by " + results.size()); // In order to be able to fail in the middle of the operation, we'll operate on lazy // copies and apply the result at the end. CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(false); cmc.mergeResults(compactedFiles, results); markCompactedAway(compactedFiles); debugDumpState("Merged compaction results"); } // Mark the files as compactedAway once the storefiles and compactedfiles list is finalised // Let a background thread close the actual reader on these compacted files and also // ensure to evict the blocks from block cache so that they are no longer in // cache private void markCompactedAway(Collection<HStoreFile> compactedFiles) { for (HStoreFile file : compactedFiles) { file.markCompactedAway(); } } @Override public void removeCompactedFiles(Collection<HStoreFile> compactedFiles) throws IOException { // See class comment for the assumptions we make here. LOG.debug("Attempting to delete compaction results: " + compactedFiles.size()); // In order to be able to fail in the middle of the operation, we'll operate on lazy // copies and apply the result at the end. CompactionOrFlushMergeCopy cmc = new CompactionOrFlushMergeCopy(false); cmc.deleteResults(compactedFiles); debugDumpState("Deleted compaction results"); } @Override public int getStoreCompactionPriority() { // If there's only L0, do what the default store does. // If we are in critical priority, do the same - we don't want to trump all stores all // the time due to how many files we have. int fc = getStorefileCount(); if (state.stripeFiles.isEmpty() || (this.blockingFileCount <= fc)) { return this.blockingFileCount - fc; } // If we are in good shape, we don't want to be trumped by all other stores due to how // many files we have, so do an approximate mapping to normal priority range; L0 counts // for all stripes. int l0 = state.level0Files.size(), sc = state.stripeFiles.size(); int priority = (int)Math.ceil(((double)(this.blockingFileCount - fc + l0) / sc) - l0); return (priority <= HStore.PRIORITY_USER) ? (HStore.PRIORITY_USER + 1) : priority; } /** * Gets the total size of all files in the stripe. * @param stripeIndex Stripe index. * @return Size. */ private long getStripeFilesSize(int stripeIndex) { long result = 0; for (HStoreFile sf : state.stripeFiles.get(stripeIndex)) { result += sf.getReader().length(); } return result; } /** * Loads initial store files that were picked up from some physical location pertaining to * this store (presumably). Unlike adding files after compaction, assumes empty initial * sets, and is forgiving with regard to stripe constraints - at worst, many/all files will * go to level 0. * @param storeFiles Store files to add. */ private void loadUnclassifiedStoreFiles(List<HStoreFile> storeFiles) { LOG.debug("Attempting to load " + storeFiles.size() + " store files."); TreeMap<byte[], ArrayList<HStoreFile>> candidateStripes = new TreeMap<>(MAP_COMPARATOR); ArrayList<HStoreFile> level0Files = new ArrayList<>(); // Separate the files into tentative stripes; then validate. Currently, we rely on metadata. // If needed, we could dynamically determine the stripes in future. for (HStoreFile sf : storeFiles) { byte[] startRow = startOf(sf), endRow = endOf(sf); // Validate the range and put the files into place. if (isInvalid(startRow) || isInvalid(endRow)) { insertFileIntoStripe(level0Files, sf); // No metadata - goes to L0. ensureLevel0Metadata(sf); } else if (!isOpen(startRow) && !isOpen(endRow) && nonOpenRowCompare(startRow, endRow) >= 0) { LOG.error("Unexpected metadata - start row [" + Bytes.toString(startRow) + "], end row [" + Bytes.toString(endRow) + "] in file [" + sf.getPath() + "], pushing to L0"); insertFileIntoStripe(level0Files, sf); // Bad metadata - goes to L0 also. ensureLevel0Metadata(sf); } else { ArrayList<HStoreFile> stripe = candidateStripes.get(endRow); if (stripe == null) { stripe = new ArrayList<>(); candidateStripes.put(endRow, stripe); } insertFileIntoStripe(stripe, sf); } } // Possible improvement - for variable-count stripes, if all the files are in L0, we can // instead create single, open-ended stripe with all files. boolean hasOverlaps = false; byte[] expectedStartRow = null; // first stripe can start wherever Iterator<Map.Entry<byte[], ArrayList<HStoreFile>>> entryIter = candidateStripes.entrySet().iterator(); while (entryIter.hasNext()) { Map.Entry<byte[], ArrayList<HStoreFile>> entry = entryIter.next(); ArrayList<HStoreFile> files = entry.getValue(); // Validate the file start rows, and remove the bad ones to level 0. for (int i = 0; i < files.size(); ++i) { HStoreFile sf = files.get(i); byte[] startRow = startOf(sf); if (expectedStartRow == null) { expectedStartRow = startRow; // ensure that first stripe is still consistent } else if (!rowEquals(expectedStartRow, startRow)) { hasOverlaps = true; LOG.warn("Store file doesn't fit into the tentative stripes - expected to start at [" + Bytes.toString(expectedStartRow) + "], but starts at [" + Bytes.toString(startRow) + "], to L0 it goes"); HStoreFile badSf = files.remove(i); insertFileIntoStripe(level0Files, badSf); ensureLevel0Metadata(badSf); --i; } } // Check if any files from the candidate stripe are valid. If so, add a stripe. byte[] endRow = entry.getKey(); if (!files.isEmpty()) { expectedStartRow = endRow; // Next stripe must start exactly at that key. } else { entryIter.remove(); } } // In the end, there must be open ends on two sides. If not, and there were no errors i.e. // files are consistent, they might be coming from a split. We will treat the boundaries // as open keys anyway, and log the message. // If there were errors, we'll play it safe and dump everything into L0. if (!candidateStripes.isEmpty()) { HStoreFile firstFile = candidateStripes.firstEntry().getValue().get(0); boolean isOpen = isOpen(startOf(firstFile)) && isOpen(candidateStripes.lastKey()); if (!isOpen) { LOG.warn("The range of the loaded files does not cover full key space: from [" + Bytes.toString(startOf(firstFile)) + "], to [" + Bytes.toString(candidateStripes.lastKey()) + "]"); if (!hasOverlaps) { ensureEdgeStripeMetadata(candidateStripes.firstEntry().getValue(), true); ensureEdgeStripeMetadata(candidateStripes.lastEntry().getValue(), false); } else { LOG.warn("Inconsistent files, everything goes to L0."); for (ArrayList<HStoreFile> files : candidateStripes.values()) { for (HStoreFile sf : files) { insertFileIntoStripe(level0Files, sf); ensureLevel0Metadata(sf); } } candidateStripes.clear(); } } } // Copy the results into the fields. State state = new State(); state.level0Files = ImmutableList.copyOf(level0Files); state.stripeFiles = new ArrayList<>(candidateStripes.size()); state.stripeEndRows = new byte[Math.max(0, candidateStripes.size() - 1)][]; ArrayList<HStoreFile> newAllFiles = new ArrayList<>(level0Files); int i = candidateStripes.size() - 1; for (Map.Entry<byte[], ArrayList<HStoreFile>> entry : candidateStripes.entrySet()) { state.stripeFiles.add(ImmutableList.copyOf(entry.getValue())); newAllFiles.addAll(entry.getValue()); if (i > 0) { state.stripeEndRows[state.stripeFiles.size() - 1] = entry.getKey(); } --i; } state.allFilesCached = ImmutableList.copyOf(newAllFiles); this.state = state; debugDumpState("Files loaded"); } private void ensureEdgeStripeMetadata(ArrayList<HStoreFile> stripe, boolean isFirst) { HashMap<HStoreFile, byte[]> targetMap = isFirst ? fileStarts : fileEnds; for (HStoreFile sf : stripe) { targetMap.put(sf, OPEN_KEY); } } private void ensureLevel0Metadata(HStoreFile sf) { if (!isInvalid(startOf(sf))) this.fileStarts.put(sf, INVALID_KEY_IN_MAP); if (!isInvalid(endOf(sf))) this.fileEnds.put(sf, INVALID_KEY_IN_MAP); } private void debugDumpState(String string) { if (!LOG.isDebugEnabled()) return; StringBuilder sb = new StringBuilder(); sb.append("\n" + string + "; current stripe state is as such:"); sb.append("\n level 0 with ") .append(state.level0Files.size()) .append( " files: " + TraditionalBinaryPrefix.long2String( StripeCompactionPolicy.getTotalFileSize(state.level0Files), "", 1) + ";"); for (int i = 0; i < state.stripeFiles.size(); ++i) { String endRow = (i == state.stripeEndRows.length) ? "(end)" : "[" + Bytes.toString(state.stripeEndRows[i]) + "]"; sb.append("\n stripe ending in ") .append(endRow) .append(" with ") .append(state.stripeFiles.get(i).size()) .append( " files: " + TraditionalBinaryPrefix.long2String( StripeCompactionPolicy.getTotalFileSize(state.stripeFiles.get(i)), "", 1) + ";"); } sb.append("\n").append(state.stripeFiles.size()).append(" stripes total."); sb.append("\n").append(getStorefileCount()).append(" files total."); LOG.debug(sb.toString()); } /** * Checks whether the key indicates an open interval boundary (i.e. infinity). */ private static final boolean isOpen(byte[] key) { return key != null && key.length == 0; } private static final boolean isOpen(Cell key) { return key != null && key.getRowLength() == 0; } /** * Checks whether the key is invalid (e.g. from an L0 file, or non-stripe-compacted files). */ private static final boolean isInvalid(byte[] key) { // No need to use Arrays.equals because INVALID_KEY is null return key == INVALID_KEY; } /** * Compare two keys for equality. */ private final boolean rowEquals(byte[] k1, byte[] k2) { return Bytes.equals(k1, 0, k1.length, k2, 0, k2.length); } /** * Compare two keys. Keys must not be open (isOpen(row) == false). */ private final int nonOpenRowCompare(byte[] k1, byte[] k2) { assert !isOpen(k1) && !isOpen(k2); return Bytes.compareTo(k1, k2); } private final int nonOpenRowCompare(Cell k1, byte[] k2) { assert !isOpen(k1) && !isOpen(k2); return cellComparator.compareRows(k1, k2, 0, k2.length); } /** * Finds the stripe index by end row. */ private final int findStripeIndexByEndRow(byte[] endRow) { assert !isInvalid(endRow); if (isOpen(endRow)) return state.stripeEndRows.length; return Arrays.binarySearch(state.stripeEndRows, endRow, Bytes.BYTES_COMPARATOR); } /** * Finds the stripe index for the stripe containing a row provided externally for get/scan. */ private final int findStripeForRow(byte[] row, boolean isStart) { if (isStart && Arrays.equals(row, HConstants.EMPTY_START_ROW)) return 0; if (!isStart && Arrays.equals(row, HConstants.EMPTY_END_ROW)) { return state.stripeFiles.size() - 1; } // If there's an exact match below, a stripe ends at "row". Stripe right boundary is // exclusive, so that means the row is in the next stripe; thus, we need to add one to index. // If there's no match, the return value of binarySearch is (-(insertion point) - 1), where // insertion point is the index of the next greater element, or list size if none. The // insertion point happens to be exactly what we need, so we need to add one to the result. return Math.abs(Arrays.binarySearch(state.stripeEndRows, row, Bytes.BYTES_COMPARATOR) + 1); } @Override public final byte[] getStartRow(int stripeIndex) { return (stripeIndex == 0 ? OPEN_KEY : state.stripeEndRows[stripeIndex - 1]); } @Override public final byte[] getEndRow(int stripeIndex) { return (stripeIndex == state.stripeEndRows.length ? OPEN_KEY : state.stripeEndRows[stripeIndex]); } private byte[] startOf(HStoreFile sf) { byte[] result = fileStarts.get(sf); // result and INVALID_KEY_IN_MAP are compared _only_ by reference on purpose here as the latter // serves only as a marker and is not to be confused with other empty byte arrays. // See Javadoc of INVALID_KEY_IN_MAP for more information return (result == null) ? sf.getMetadataValue(STRIPE_START_KEY) : result == INVALID_KEY_IN_MAP ? INVALID_KEY : result; } private byte[] endOf(HStoreFile sf) { byte[] result = fileEnds.get(sf); // result and INVALID_KEY_IN_MAP are compared _only_ by reference on purpose here as the latter // serves only as a marker and is not to be confused with other empty byte arrays. // See Javadoc of INVALID_KEY_IN_MAP for more information return (result == null) ? sf.getMetadataValue(STRIPE_END_KEY) : result == INVALID_KEY_IN_MAP ? INVALID_KEY : result; } /** * Inserts a file in the correct place (by seqnum) in a stripe copy. * @param stripe Stripe copy to insert into. * @param sf File to insert. */ private static void insertFileIntoStripe(ArrayList<HStoreFile> stripe, HStoreFile sf) { // The only operation for which sorting of the files matters is KeyBefore. Therefore, // we will store the file in reverse order by seqNum from the outset. for (int insertBefore = 0; ; ++insertBefore) { if (insertBefore == stripe.size() || (StoreFileComparators.SEQ_ID.compare(sf, stripe.get(insertBefore)) >= 0)) { stripe.add(insertBefore, sf); break; } } } /** * An extension of ConcatenatedLists that has several peculiar properties. * First, one can cut the tail of the logical list by removing last several sub-lists. * Second, items can be removed thru iterator. * Third, if the sub-lists are immutable, they are replaced with mutable copies when needed. * On average KeyBefore operation will contain half the stripes as potential candidates, * but will quickly cut down on them as it finds something in the more likely ones; thus, * the above allow us to avoid unnecessary copying of a bunch of lists. */ private static class KeyBeforeConcatenatedLists extends ConcatenatedLists<HStoreFile> { @Override public java.util.Iterator<HStoreFile> iterator() { return new Iterator(); } public class Iterator extends ConcatenatedLists<HStoreFile>.Iterator { public ArrayList<List<HStoreFile>> getComponents() { return components; } public void removeComponents(int startIndex) { List<List<HStoreFile>> subList = components.subList(startIndex, components.size()); for (List<HStoreFile> entry : subList) { size -= entry.size(); } assert size >= 0; subList.clear(); } @Override public void remove() { if (!this.nextWasCalled) { throw new IllegalStateException("No element to remove"); } this.nextWasCalled = false; List<HStoreFile> src = components.get(currentComponent); if (src instanceof ImmutableList<?>) { src = new ArrayList<>(src); components.set(currentComponent, src); } src.remove(indexWithinComponent); --size; --indexWithinComponent; if (src.isEmpty()) { components.remove(currentComponent); // indexWithinComponent is already -1 here. } } } } /** * Non-static helper class for merging compaction or flush results. * Since we want to merge them atomically (more or less), it operates on lazy copies, * then creates a new state object and puts it in place. */ private class CompactionOrFlushMergeCopy { private ArrayList<List<HStoreFile>> stripeFiles = null; private ArrayList<HStoreFile> level0Files = null; private ArrayList<byte[]> stripeEndRows = null; private Collection<HStoreFile> compactedFiles = null; private Collection<HStoreFile> results = null; private List<HStoreFile> l0Results = new ArrayList<>(); private final boolean isFlush; public CompactionOrFlushMergeCopy(boolean isFlush) { // Create a lazy mutable copy (other fields are so lazy they start out as nulls). this.stripeFiles = new ArrayList<>(StripeStoreFileManager.this.state.stripeFiles); this.isFlush = isFlush; } private void mergeResults(Collection<HStoreFile> compactedFiles, Collection<HStoreFile> results) throws IOException { assert this.compactedFiles == null && this.results == null; this.compactedFiles = compactedFiles; this.results = results; // Do logical processing. if (!isFlush) removeCompactedFiles(); TreeMap<byte[], HStoreFile> newStripes = processResults(); if (newStripes != null) { processNewCandidateStripes(newStripes); } // Create new state and update parent. State state = createNewState(false); StripeStoreFileManager.this.state = state; updateMetadataMaps(); } private void deleteResults(Collection<HStoreFile> compactedFiles) throws IOException { this.compactedFiles = compactedFiles; // Create new state and update parent. State state = createNewState(true); StripeStoreFileManager.this.state = state; updateMetadataMaps(); } private State createNewState(boolean delCompactedFiles) { State oldState = StripeStoreFileManager.this.state; // Stripe count should be the same unless the end rows changed. assert oldState.stripeFiles.size() == this.stripeFiles.size() || this.stripeEndRows != null; State newState = new State(); newState.level0Files = (this.level0Files == null) ? oldState.level0Files : ImmutableList.copyOf(this.level0Files); newState.stripeEndRows = (this.stripeEndRows == null) ? oldState.stripeEndRows : this.stripeEndRows.toArray(new byte[this.stripeEndRows.size()][]); newState.stripeFiles = new ArrayList<>(this.stripeFiles.size()); for (List<HStoreFile> newStripe : this.stripeFiles) { newState.stripeFiles.add(newStripe instanceof ImmutableList<?> ? (ImmutableList<HStoreFile>)newStripe : ImmutableList.copyOf(newStripe)); } List<HStoreFile> newAllFiles = new ArrayList<>(oldState.allFilesCached); List<HStoreFile> newAllCompactedFiles = new ArrayList<>(oldState.allCompactedFilesCached); if (!isFlush) { newAllFiles.removeAll(compactedFiles); if (delCompactedFiles) { newAllCompactedFiles.removeAll(compactedFiles); } else { newAllCompactedFiles.addAll(compactedFiles); } } if (results != null) { newAllFiles.addAll(results); } newState.allFilesCached = ImmutableList.copyOf(newAllFiles); newState.allCompactedFilesCached = ImmutableList.copyOf(newAllCompactedFiles); return newState; } private void updateMetadataMaps() { StripeStoreFileManager parent = StripeStoreFileManager.this; if (!isFlush) { for (HStoreFile sf : this.compactedFiles) { parent.fileStarts.remove(sf); parent.fileEnds.remove(sf); } } if (this.l0Results != null) { for (HStoreFile sf : this.l0Results) { parent.ensureLevel0Metadata(sf); } } } /** * @param index Index of the stripe we need. * @return A lazy stripe copy from current stripes. */ private final ArrayList<HStoreFile> getStripeCopy(int index) { List<HStoreFile> stripeCopy = this.stripeFiles.get(index); ArrayList<HStoreFile> result = null; if (stripeCopy instanceof ImmutableList<?>) { result = new ArrayList<>(stripeCopy); this.stripeFiles.set(index, result); } else { result = (ArrayList<HStoreFile>)stripeCopy; } return result; } /** * @return A lazy L0 copy from current state. */ private final ArrayList<HStoreFile> getLevel0Copy() { if (this.level0Files == null) { this.level0Files = new ArrayList<>(StripeStoreFileManager.this.state.level0Files); } return this.level0Files; } /** * Process new files, and add them either to the structure of existing stripes, * or to the list of new candidate stripes. * @return New candidate stripes. */ private TreeMap<byte[], HStoreFile> processResults() throws IOException { TreeMap<byte[], HStoreFile> newStripes = null; for (HStoreFile sf : this.results) { byte[] startRow = startOf(sf), endRow = endOf(sf); if (isInvalid(endRow) || isInvalid(startRow)) { if (!isFlush) { LOG.warn("The newly compacted file doesn't have stripes set: " + sf.getPath()); } insertFileIntoStripe(getLevel0Copy(), sf); this.l0Results.add(sf); continue; } if (!this.stripeFiles.isEmpty()) { int stripeIndex = findStripeIndexByEndRow(endRow); if ((stripeIndex >= 0) && rowEquals(getStartRow(stripeIndex), startRow)) { // Simple/common case - add file to an existing stripe. insertFileIntoStripe(getStripeCopy(stripeIndex), sf); continue; } } // Make a new candidate stripe. if (newStripes == null) { newStripes = new TreeMap<>(MAP_COMPARATOR); } HStoreFile oldSf = newStripes.put(endRow, sf); if (oldSf != null) { throw new IOException("Compactor has produced multiple files for the stripe ending in [" + Bytes.toString(endRow) + "], found " + sf.getPath() + " and " + oldSf.getPath()); } } return newStripes; } /** * Remove compacted files. */ private void removeCompactedFiles() throws IOException { for (HStoreFile oldFile : this.compactedFiles) { byte[] oldEndRow = endOf(oldFile); List<HStoreFile> source = null; if (isInvalid(oldEndRow)) { source = getLevel0Copy(); } else { int stripeIndex = findStripeIndexByEndRow(oldEndRow); if (stripeIndex < 0) { throw new IOException("An allegedly compacted file [" + oldFile + "] does not belong" + " to a known stripe (end row - [" + Bytes.toString(oldEndRow) + "])"); } source = getStripeCopy(stripeIndex); } if (!source.remove(oldFile)) { throw new IOException("An allegedly compacted file [" + oldFile + "] was not found"); } } } /** * See {@link #addCompactionResults(Collection, Collection)} - updates the stripe list with * new candidate stripes/removes old stripes; produces new set of stripe end rows. * @param newStripes New stripes - files by end row. */ private void processNewCandidateStripes( TreeMap<byte[], HStoreFile> newStripes) throws IOException { // Validate that the removed and added aggregate ranges still make for a full key space. boolean hasStripes = !this.stripeFiles.isEmpty(); this.stripeEndRows = new ArrayList<>(Arrays.asList(StripeStoreFileManager.this.state.stripeEndRows)); int removeFrom = 0; byte[] firstStartRow = startOf(newStripes.firstEntry().getValue()); byte[] lastEndRow = newStripes.lastKey(); if (!hasStripes && (!isOpen(firstStartRow) || !isOpen(lastEndRow))) { throw new IOException("Newly created stripes do not cover the entire key space."); } boolean canAddNewStripes = true; Collection<HStoreFile> filesForL0 = null; if (hasStripes) { // Determine which stripes will need to be removed because they conflict with new stripes. // The new boundaries should match old stripe boundaries, so we should get exact matches. if (isOpen(firstStartRow)) { removeFrom = 0; } else { removeFrom = findStripeIndexByEndRow(firstStartRow); if (removeFrom < 0) throw new IOException("Compaction is trying to add a bad range."); ++removeFrom; } int removeTo = findStripeIndexByEndRow(lastEndRow); if (removeTo < 0) throw new IOException("Compaction is trying to add a bad range."); // See if there are files in the stripes we are trying to replace. ArrayList<HStoreFile> conflictingFiles = new ArrayList<>(); for (int removeIndex = removeTo; removeIndex >= removeFrom; --removeIndex) { conflictingFiles.addAll(this.stripeFiles.get(removeIndex)); } if (!conflictingFiles.isEmpty()) { // This can be caused by two things - concurrent flush into stripes, or a bug. // Unfortunately, we cannot tell them apart without looking at timing or something // like that. We will assume we are dealing with a flush and dump it into L0. if (isFlush) { long newSize = StripeCompactionPolicy.getTotalFileSize(newStripes.values()); LOG.warn("Stripes were created by a flush, but results of size " + newSize + " cannot be added because the stripes have changed"); canAddNewStripes = false; filesForL0 = newStripes.values(); } else { long oldSize = StripeCompactionPolicy.getTotalFileSize(conflictingFiles); LOG.info(conflictingFiles.size() + " conflicting files (likely created by a flush) " + " of size " + oldSize + " are moved to L0 due to concurrent stripe change"); filesForL0 = conflictingFiles; } if (filesForL0 != null) { for (HStoreFile sf : filesForL0) { insertFileIntoStripe(getLevel0Copy(), sf); } l0Results.addAll(filesForL0); } } if (canAddNewStripes) { // Remove old empty stripes. int originalCount = this.stripeFiles.size(); for (int removeIndex = removeTo; removeIndex >= removeFrom; --removeIndex) { if (removeIndex != originalCount - 1) { this.stripeEndRows.remove(removeIndex); } this.stripeFiles.remove(removeIndex); } } } if (!canAddNewStripes) return; // Files were already put into L0. // Now, insert new stripes. The total ranges match, so we can insert where we removed. byte[] previousEndRow = null; int insertAt = removeFrom; for (Map.Entry<byte[], HStoreFile> newStripe : newStripes.entrySet()) { if (previousEndRow != null) { // Validate that the ranges are contiguous. assert !isOpen(previousEndRow); byte[] startRow = startOf(newStripe.getValue()); if (!rowEquals(previousEndRow, startRow)) { throw new IOException("The new stripes produced by " + (isFlush ? "flush" : "compaction") + " are not contiguous"); } } // Add the new stripe. ArrayList<HStoreFile> tmp = new ArrayList<>(); tmp.add(newStripe.getValue()); stripeFiles.add(insertAt, tmp); previousEndRow = newStripe.getKey(); if (!isOpen(previousEndRow)) { stripeEndRows.add(insertAt, previousEndRow); } ++insertAt; } } } @Override public List<HStoreFile> getLevel0Files() { return this.state.level0Files; } @Override public List<byte[]> getStripeBoundaries() { if (this.state.stripeFiles.isEmpty()) { return Collections.emptyList(); } ArrayList<byte[]> result = new ArrayList<>(this.state.stripeEndRows.length + 2); result.add(OPEN_KEY); Collections.addAll(result, this.state.stripeEndRows); result.add(OPEN_KEY); return result; } @Override public ArrayList<ImmutableList<HStoreFile>> getStripes() { return this.state.stripeFiles; } @Override public int getStripeCount() { return this.state.stripeFiles.size(); } @Override public Collection<HStoreFile> getUnneededFiles(long maxTs, List<HStoreFile> filesCompacting) { // 1) We can never get rid of the last file which has the maximum seqid in a stripe. // 2) Files that are not the latest can't become one due to (1), so the rest are fair game. State state = this.state; Collection<HStoreFile> expiredStoreFiles = null; for (ImmutableList<HStoreFile> stripe : state.stripeFiles) { expiredStoreFiles = findExpiredFiles(stripe, maxTs, filesCompacting, expiredStoreFiles); } return findExpiredFiles(state.level0Files, maxTs, filesCompacting, expiredStoreFiles); } private Collection<HStoreFile> findExpiredFiles(ImmutableList<HStoreFile> stripe, long maxTs, List<HStoreFile> filesCompacting, Collection<HStoreFile> expiredStoreFiles) { // Order by seqnum is reversed. for (int i = 1; i < stripe.size(); ++i) { HStoreFile sf = stripe.get(i); synchronized (sf) { long fileTs = sf.getReader().getMaxTimestamp(); if (fileTs < maxTs && !filesCompacting.contains(sf)) { LOG.info("Found an expired store file: " + sf.getPath() + " whose maxTimestamp is " + fileTs + ", which is below " + maxTs); if (expiredStoreFiles == null) { expiredStoreFiles = new ArrayList<>(); } expiredStoreFiles.add(sf); } } } return expiredStoreFiles; } @Override public double getCompactionPressure() { State stateLocal = this.state; if (stateLocal.allFilesCached.size() > blockingFileCount) { // just a hit to tell others that we have reached the blocking file count. return 2.0; } if (stateLocal.stripeFiles.isEmpty()) { return 0.0; } int blockingFilePerStripe = blockingFileCount / stateLocal.stripeFiles.size(); // do not calculate L0 separately because data will be moved to stripe quickly and in most cases // we flush data to stripe directly. int delta = stateLocal.level0Files.isEmpty() ? 0 : 1; double max = 0.0; for (ImmutableList<HStoreFile> stripeFile : stateLocal.stripeFiles) { int stripeFileCount = stripeFile.size(); double normCount = (double) (stripeFileCount + delta - config.getStripeCompactMinFiles()) / (blockingFilePerStripe - config.getStripeCompactMinFiles()); if (normCount >= 1.0) { // This could happen if stripe is not split evenly. Do not return values that larger than // 1.0 because we have not reached the blocking file count actually. return 1.0; } if (normCount > max) { max = normCount; } } return max; } @Override public Comparator<HStoreFile> getStoreFileComparator() { return StoreFileComparators.SEQ_ID; } }
HBASE-25273 fix typo in StripeStoreFileManager java doc (#2653) Co-authored-by: Hossein Zolfi <[email protected]> Signed-off-by: Jan Hentschel <[email protected]>
hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StripeStoreFileManager.java
HBASE-25273 fix typo in StripeStoreFileManager java doc (#2653)
<ide><path>base-server/src/main/java/org/apache/hadoop/hbase/regionserver/StripeStoreFileManager.java <ide> import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableList; <ide> <ide> /** <del> * Stripe implementation of StoreFileManager. <add> * Stripe implementation of {@link StoreFileManager}. <ide> * Not thread safe - relies on external locking (in HStore). Collections that this class <ide> * returns are immutable or unique to the call, so they should be safe. <ide> * Stripe store splits the key space of the region into non-overlapping stripes, as well as <ide> * When L0 is compacted, it's split into the files corresponding to existing stripe boundaries, <ide> * that can thus be added to stripes. <ide> * When scan or get happens, it only has to read the files from the corresponding stripes. <del> * See StripeCompationPolicy on how the stripes are determined; this class doesn't care. <add> * See {@link StripeCompactionPolicy} on how the stripes are determined; this class doesn't care. <ide> * <del> * This class should work together with StripeCompactionPolicy and StripeCompactor. <add> * This class should work together with {@link StripeCompactionPolicy} and <add> * {@link org.apache.hadoop.hbase.regionserver.compactions.StripeCompactor}. <ide> * With regard to how they work, we make at least the following (reasonable) assumptions: <ide> * - Compaction produces one file per new stripe (if any); that is easy to change. <ide> * - Compaction has one contiguous set of stripes both in and out, except if L0 is involved.
Java
lgpl-2.1
error: pathspec 'src/dr/app/bss/Partition.java' did not match any file(s) known to git
3b2adfa2950c8d72ef18d0e85044da4212943aba
1
adamallo/beast-mcmc,codeaudit/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,codeaudit/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,codeaudit/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,codeaudit/beast-mcmc,codeaudit/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,codeaudit/beast-mcmc
package dr.app.bss; import dr.app.beagle.evomodel.sitemodel.BranchSubstitutionModel; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.evolution.sequence.Sequence; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.tree.TreeModel; public class Partition { public int from; public int to; public int every; public TreeModel treeModel; public BranchSubstitutionModel branchSubstitutionModel; public GammaSiteRateModel siteModel; public BranchRateModel branchRateModel; public FrequencyModel freqModel; public int partitionSiteCount; public boolean hasAncestralSequence = false; public Sequence ancestralSequence = null; public Partition( TreeModel treeModel, // BranchSubstitutionModel branchSubstitutionModel, GammaSiteRateModel siteModel, // BranchRateModel branchRateModel, // FrequencyModel freqModel, // int from, // int to, // int every // ) { this.treeModel = treeModel; this.siteModel = siteModel; this.freqModel = freqModel; this.branchSubstitutionModel = branchSubstitutionModel; this.branchRateModel = branchRateModel; this.from = from - 1; this.to = to;// + 1; this.every = every; partitionSiteCount = ((to - from) / every); }//END: Constructor public void setAncestralSequence(Sequence ancestralSequence) { this.ancestralSequence = ancestralSequence; this.hasAncestralSequence = true; }// END: setAncestralSequence }//END: class
src/dr/app/bss/Partition.java
partition object, no parser yet
src/dr/app/bss/Partition.java
partition object, no parser yet
<ide><path>rc/dr/app/bss/Partition.java <add>package dr.app.bss; <add> <add>import dr.app.beagle.evomodel.sitemodel.BranchSubstitutionModel; <add>import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; <add>import dr.app.beagle.evomodel.substmodel.FrequencyModel; <add>import dr.evolution.sequence.Sequence; <add>import dr.evomodel.branchratemodel.BranchRateModel; <add>import dr.evomodel.tree.TreeModel; <add> <add>public class Partition { <add> <add> public int from; <add> public int to; <add> public int every; <add> <add> public TreeModel treeModel; <add> public BranchSubstitutionModel branchSubstitutionModel; <add> public GammaSiteRateModel siteModel; <add> public BranchRateModel branchRateModel; <add> public FrequencyModel freqModel; <add> <add> public int partitionSiteCount; <add> <add> public boolean hasAncestralSequence = false; <add> public Sequence ancestralSequence = null; <add> <add> public Partition( <add> TreeModel treeModel, // <add> BranchSubstitutionModel branchSubstitutionModel, <add> GammaSiteRateModel siteModel, // <add> BranchRateModel branchRateModel, // <add> FrequencyModel freqModel, // <add> int from, // <add> int to, // <add> int every // <add> ) { <add> <add> this.treeModel = treeModel; <add> this.siteModel = siteModel; <add> this.freqModel = freqModel; <add> this.branchSubstitutionModel = branchSubstitutionModel; <add> this.branchRateModel = branchRateModel; <add> <add> this.from = from - 1; <add> this.to = to;// + 1; <add> this.every = every; <add> <add> partitionSiteCount = ((to - from) / every); <add> <add> }//END: Constructor <add> <add> public void setAncestralSequence(Sequence ancestralSequence) { <add> this.ancestralSequence = ancestralSequence; <add> this.hasAncestralSequence = true; <add> }// END: setAncestralSequence <add> <add> <add> <add>}//END: class
JavaScript
apache-2.0
92682e41e49b530d756c1492e3f6eba20a83f5a2
0
Sw0rdstream/appium,appium/appium,appium/appium,appium/appium,appium/appium,appium/appium,appium/appium
"use strict"; var spawn = require('win-spawn') , exec = require('child_process').exec , path = require('path') , fs = require('fs') , net = require('net') , logger = require('../logger').get('appium') , status = require('../app/uiauto/lib/status') , unzipFile = require('../app/helpers').unzipFile , testZipArchive = require('../app/helpers').testZipArchive , async = require('async') , ncp = require('ncp') , mkdirp = require('mkdirp') , _ = require('underscore') , helpers = require('../app/helpers') , AdmZip = require('adm-zip') , getTempPath = helpers.getTempPath , isWindows = helpers.isWindows(); var noop = function() {}; var ADB = function(opts, android) { if (!opts) { opts = {}; } if (typeof opts.sdkRoot === "undefined") { opts.sdkRoot = process.env.ANDROID_HOME || ''; } this.sdkRoot = opts.sdkRoot; this.udid = opts.udid; this.webSocket = opts.webSocket; // Don't uninstall if using fast reset. // Uninstall if reset is set and fast reset isn't. this.skipUninstall = opts.fastReset || !(opts.reset || false); this.systemPort = opts.port || 4724; this.devicePort = opts.devicePort || 4724; this.avdName = opts.avdName; this.appPackage = opts.appPackage; this.appActivity = opts.appActivity; this.appWaitActivity = opts.appWaitActivity; this.appDeviceReadyTimeout = opts.appDeviceReadyTimeout; this.apkPath = opts.apkPath; this.adb = "adb"; this.adbCmd = this.adb; this.curDeviceId = null; this.socketClient = null; this.proc = null; this.onSocketReady = noop; this.onExit = noop; this.alreadyExited = false; this.portForwarded = false; this.emulatorPort = null; this.debugMode = true; this.fastReset = opts.fastReset; this.cleanApp = opts.cleanApp || this.fastReset; this.cleanAPK = path.resolve(helpers.getTempPath(), this.appPackage + '.clean.apk'); // This is set to true when the bootstrap jar crashes. this.restartBootstrap = false; // The android ref is used to resend the command that // detected the crash. this.android = android; this.cmdCb = null; this.binaries = {}; this.resendLastCommand = function() {}; }; ADB.prototype.checkSdkBinaryPresent = function(binary, cb) { logger.info("Checking whether " + binary + " is present"); var binaryLoc = null; var binaryName = binary; if (isWindows) { if (binaryName === "android") { binaryName += ".bat"; } else { if (binaryName.indexOf(".exe", binaryName.length - 4) == -1) { binaryName += ".exe"; } } } if (this.sdkRoot) { var binaryLocs = [ path.resolve(this.sdkRoot, "platform-tools", binaryName) , path.resolve(this.sdkRoot, "tools", binaryName) , path.resolve(this.sdkRoot, "build-tools", "17.0.0", binaryName) , path.resolve(this.sdkRoot, "build-tools", "android-4.2.2", binaryName)]; _.each(binaryLocs, function(loc) { if (fs.existsSync(loc)) binaryLoc = loc; }); if (binaryLoc === null) { cb(new Error("Could not find " + binary + " in tools, platform-tools, or build-tools; " + "do you have android SDK installed?"), null); return; } this.debug("Using " + binary + " from " + binaryLoc); this.binaries[binary] = binaryLoc; cb(null, binaryLoc); } else { exec("which " + binary, _.bind(function(err, stdout) { if (stdout) { this.debug("Using " + binary + " from " + stdout); cb(null, stdout); } else { cb(new Error("Could not find " + binary + "; do you have android " + "SDK installed?"), null); } }, this)); } }; ADB.prototype.checkAdbPresent = function(cb) { this.checkSdkBinaryPresent("adb", _.bind(function(err, binaryLoc) { if (err) return cb(err); this.adb = binaryLoc.trim(); cb(null); }, this)); }; ADB.prototype.checkAppPresent = function(cb) { if (this.apkPath === null) { logger.info("Not checking whether app is present since we are assuming " + "it's already on the device"); cb(null); } else { logger.info("Checking whether app is actually present"); fs.stat(this.apkPath, _.bind(function(err) { if (err) { logger.error("Could not find app apk at " + this.apkPath); cb(new Error("Error locating the app apk, supposedly it's at " + this.apkPath + " but we can't stat it. Filesystem error " + "is " + err)); } else { cb(null); } }, this)); } }; // Fast reset ADB.prototype.buildFastReset = function(skipAppSign, cb) { logger.info("Building fast reset"); // Create manifest var me = this , targetAPK = me.apkPath , cleanAPKSrc = path.resolve(__dirname, '../app/android/Clean.apk') , newPackage = me.appPackage + '.clean' , srcManifest = path.resolve(__dirname, '../app/android/AndroidManifest.xml.src') , dstManifest = path.resolve(getTempPath(), 'AndroidManifest.xml'); fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8"); var resignApks = function(cb) { // Resign clean apk and target apk var apks = [ me.cleanAPK ]; if (!skipAppSign) { logger.debug("Signing app and clean apk."); apks.push(targetAPK); } else { logger.debug("Skip app sign. Sign clean apk."); } me.sign(apks, cb); }; async.series([ function(cb) { me.checkSdkBinaryPresent("aapt", cb); }, function(cb) { me.compileManifest(dstManifest, newPackage, me.appPackage, cb); }, function(cb) { me.insertManifest(dstManifest, cleanAPKSrc, me.cleanAPK, cb); }, function(cb) { resignApks(cb); } ], cb); }; ADB.prototype.insertSelendroidManifest = function(serverPath, cb) { logger.info("Inserting selendroid manifest"); var me = this , newServerPath = me.selendroidServerPath , newPackage = me.appPackage + '.selendroid' , srcManifest = path.resolve(__dirname, "../build/selendroid/AndroidManifest.xml") , dstDir = path.resolve(getTempPath(), this.appPackage) , dstManifest = dstDir + '/AndroidManifest.xml'; try { fs.mkdirSync(dstDir); } catch (e) { if (e.message.indexOf("EEXIST") === -1) { throw e; } } fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8"); async.series([ function(cb) { mkdirp(dstDir, cb); }, function(cb) { me.checkSdkBinaryPresent("aapt", cb); }, function(cb) { me.compileManifest(dstManifest, newPackage, me.appPackage, cb); }, function(cb) { me.insertManifest(dstManifest, serverPath, newServerPath, cb); } ], cb); }; ADB.prototype.compileManifest = function(manifest, manifestPackage, targetPackage, cb) { logger.info("Compiling manifest " + manifest); var androidHome = process.env.ANDROID_HOME , platforms = path.resolve(androidHome , 'platforms') , platform = 'android-17'; // android-17 may be called android-4.2 if (!fs.existsSync(path.resolve(platforms, platform))) { platform = 'android-4.2'; if (!fs.existsSync(path.resolve(platforms, platform))) { return cb(new Error("Platform doesn't exist " + platform)); } } // Compile manifest into manifest.xml.apk var compileManifest = [this.binaries.aapt + ' package -M "', manifest + '"', ' --rename-manifest-package "', manifestPackage + '"', ' --rename-instrumentation-target-package "', targetPackage + '"', ' -I "', path.resolve(platforms, platform, 'android.jar') +'" -F "', manifest, '.apk" -f'].join(''); logger.debug(compileManifest); exec(compileManifest, {}, function(err, stdout, stderr) { if (err) { logger.debug(stderr); return cb("error compiling manifest"); } logger.debug("Compiled manifest"); cb(null); }); }; ADB.prototype.insertManifest = function(manifest, srcApk, dstApk, cb) { logger.info("Inserting manifest, src: " + srcApk + ", dst: " + dstApk); var extractManifest = function(cb) { logger.debug("Extracting manifest"); // Extract compiled manifest from manifest.xml.apk unzipFile(manifest + '.apk', function(err, stderr) { if (err) { logger.info("Error unzipping manifest apk, here's stderr:"); logger.debug(stderr); return cb(err); } cb(null); }); }; var createTmpApk = function(cb) { logger.debug("Writing tmp apk. " + srcApk + ' to ' + dstApk); ncp(srcApk, dstApk, cb); }; var testDstApk = function(cb) { logger.debug("Testing new tmp apk."); testZipArchive(dstApk, cb); }; var moveManifest = function(cb) { if (isWindows) { try { var existingAPKzip = new AdmZip(dstApk); var newAPKzip = new AdmZip(); existingAPKzip.getEntries().forEach(function(entry) { var entryName = entry.entryName; newAPKzip.addZipEntryComment(entry, entryName); }); newAPKzip.addLocalFile(manifest); newAPKzip.writeZip(dstApk); logger.debug("Inserted manifest."); cb(null); } catch(err) { logger.info("Got error moving manifest: " + err); cb(err); } } else { // Insert compiled manifest into /tmp/appPackage.clean.apk // -j = keep only the file, not the dirs // -m = move manifest into target apk. var replaceCmd = 'zip -j -m "' + dstApk + '" "' + manifest + '"'; logger.debug("Moving manifest with: " + replaceCmd); exec(replaceCmd, {}, function(err) { if (err) { logger.info("Got error moving manifest: " + err); return cb(err); } logger.debug("Inserted manifest."); cb(null); }); } }; async.series([ function(cb) { extractManifest(cb); }, function(cb) { createTmpApk(cb); }, function(cb) { testDstApk(cb); }, function(cb) { moveManifest(cb); } ], cb); }; // apks is an array of strings. ADB.prototype.sign = function(apks, cb) { var signPath = path.resolve(__dirname, '../app/android/sign.jar'); var resign = 'java -jar "' + signPath + '" "' + apks.join('" "') + '" --override'; logger.debug("Resigning apks with: " + resign); exec(resign, {}, function(err, stdout, stderr) { if (stderr.indexOf("Input is not an existing file") !== -1) { logger.warn("Could not resign apk(s), got non-existing file error"); return cb(new Error("Could not sign one or more apks. Are you sure " + "the file paths are correct: " + JSON.stringify(apks))); } cb(err); }); }; // returns true when already signed, false otherwise. ADB.prototype.checkApkCert = function(apk, cb) { var verifyPath = path.resolve(__dirname, '../app/android/verify.jar'); var resign = 'java -jar "' + verifyPath + '" "' + apk + '"'; logger.debug("Checking app cert for " + apk + ": " + resign); exec(resign, {}, function(err) { if (err) { logger.debug("App not signed with debug cert."); return cb(false); } logger.debug("App already signed."); cb(true); }); }; ADB.prototype.checkFastReset = function(cb) { logger.info("Checking whether we need to run fast reset"); // NOP if fast reset is not true. if (!this.fastReset) { logger.info("User doesn't want fast reset, doing nothing"); return cb(null); } if (this.apkPath === null) { logger.info("Can't run fast reset on an app that's already on the device " + "so doing nothing"); return cb(null); } if (!this.appPackage) return cb(new Error("appPackage must be set.")); var me = this; me.checkApkCert(me.cleanAPK, function(cleanSigned){ me.checkApkCert(me.apkPath, function(appSigned){ // Only build & resign clean.apk if it doesn't exist or isn't signed. if (!fs.existsSync(me.cleanAPK) || !cleanSigned) { me.buildFastReset(appSigned, function(err){ if (err) return cb(err); cb(null); }); } else { if (!appSigned) { // Resign app apk because it's not signed. me.sign([me.apkPath], cb); } else { // App and clean are already existing and signed. cb(null); } } }); }); }; ADB.prototype.getDeviceWithRetry = function(cb) { logger.info("Trying to find a connected android device"); var me = this; var getDevices = function(innerCb) { me.getConnectedDevices(function(err, devices) { if (typeof devices === "undefined" || devices.length === 0 || err) { return innerCb(new Error("Could not find a connected Android device.")); } innerCb(null); }); }; getDevices(function(err) { if (err) { logger.info("Could not find devices, restarting adb server..."); me.restartAdb(function() { getDevices(cb); }); } else { logger.info("Found device, no need to retry"); cb(null); } }); }; ADB.prototype.prepareDevice = function(onReady) { logger.info("Preparing device for session"); var me = this; async.series([ function(cb) { me.checkAppPresent(cb); }, function(cb) { me.checkAdbPresent(cb); }, function(cb) { me.prepareEmulator(cb); }, function(cb) { me.getDeviceWithRetry(cb);}, function(cb) { me.waitForDevice(cb); }, function(cb) { me.checkFastReset(cb); } ], onReady); }; ADB.prototype.pushStrings = function(cb) { var me = this; var stringsFromApkJarPath = path.resolve(__dirname, '../app/android/strings_from_apk.jar'); var outputPath = path.resolve(getTempPath(), me.appPackage); var makeStrings = ['java -jar ', stringsFromApkJarPath, ' ', me.apkPath, ' ', outputPath].join(''); logger.debug(makeStrings); exec(makeStrings, {}, function(err, stdout, stderr) { if (err) { logger.debug(stderr); return cb("error making strings"); } var jsonFile = path.resolve(outputPath, 'strings.json'); var remotePath = "/data/local/tmp"; var pushCmd = me.adbCmd + " push " + jsonFile + " " + remotePath; exec(pushCmd, {}, function(err, stdout, stderr) { cb(null); }); }); }; ADB.prototype.startAppium = function(onReady, onExit) { logger.info("Starting android appium"); var me = this; this.onExit = onExit; logger.debug("Using fast reset? " + this.fastReset); async.series([ function(cb) { me.prepareDevice(cb); }, function(cb) { me.pushStrings(cb); }, function(cb) { me.uninstallApp(cb); }, function(cb) { me.installApp(cb); }, function(cb) { me.forwardPort(cb); }, function(cb) { me.pushAppium(cb); }, function(cb) { me.runBootstrap(cb, onExit); }, function(cb) { me.wakeUp(cb); }, function(cb) { me.unlockScreen(cb); }, function(cb) { me.startApp(cb); } ], function(err) { onReady(err); }); }; ADB.prototype.startSelendroid = function(serverPath, onReady) { logger.info("Starting selendroid"); var me = this , modServerExists = false , modAppPkg = this.appPackage + '.selendroid'; this.selendroidServerPath = path.resolve(getTempPath(), 'selendroid.' + this.appPackage + '.apk'); var checkModServerExists = function(cb) { fs.stat(me.selendroidServerPath, function(err) { modServerExists = !err; cb(); }); }; var conditionalUninstallSelendroid = function(cb) { if (!modServerExists) { // assume we're going to rebuild selendroid and therefore // need to uninstall it if it's already on device logger.info("Rebuilt selendroid apk does not exist, uninstalling " + "any instances of it on device to make way for new one"); me.uninstallApk(modAppPkg, cb); } else { logger.info("Rebuilt selendroid apk exists, doing nothing"); cb(); } }; var conditionalInsertManifest = function(cb) { if (!modServerExists) { logger.info("Rebuilt selendroid server does not exist, inserting " + "modified manifest"); me.insertSelendroidManifest(serverPath, cb); } else { logger.info("Rebuilt selendroid server already exists, no need to " + "rebuild it with a new manifest"); cb(); } }; var conditionalInstallSelendroid = function(cb) { me.checkAppInstallStatus(modAppPkg, function(e, installed) { if (!installed) { logger.info("Rebuilt selendroid is not installed, installing it"); me.installApk(me.selendroidServerPath, cb); } else { logger.info("Rebuilt selendroid is already installed"); cb(); } }); }; async.series([ function(cb) { me.prepareDevice(cb); }, function(cb) { checkModServerExists(cb); }, function(cb) { conditionalUninstallSelendroid(cb); }, function(cb) { conditionalInsertManifest(cb); }, function(cb) { me.checkSelendroidCerts(me.selendroidServerPath, cb); }, function(cb) { conditionalInstallSelendroid(cb); }, function(cb) { me.installApp(cb); }, function(cb) { me.forwardPort(cb); }, function(cb) { me.unlockScreen(cb); }, function(cb) { me.pushSelendroid(cb); }, function(cb) { logger.info("Selendroid server is launching"); cb(); } ], onReady); }; ADB.prototype.pushSelendroid = function(cb) { var cmd = "adb shell am instrument -e main_activity '" + this.appPackage + "." + this.appActivity + "' " + this.appPackage + ".selendroid/org.openqa.selendroid.ServerInstrumentation"; logger.info("Starting instrumentation process for selendroid with cmd: " + cmd); exec(cmd, function(err, stdout) { if (stdout.indexOf("Exception") !== -1) { logger.error(stdout); var msg = stdout.split("\n")[0] || "Unknown exception starting selendroid"; return cb(new Error(msg)); } cb(); }); }; ADB.prototype.checkSelendroidCerts = function(serverPath, cb) { var me = this , alreadyReturned = false , checks = 0; var onDoneSigning = function() { checks++; if (checks === 2 && !alreadyReturned) { cb(); } }; // these run in parallel var apks = [serverPath, this.apkPath]; _.each(apks, function(apk) { logger.info("Checking signed status of " + apk); me.checkApkCert(apk, function(isSigned) { if (isSigned) return onDoneSigning(); me.sign([apk], function(err) { if (err && !alreadyReturned) { alreadyReturned = true; return cb(err); } onDoneSigning(); }); }); }); }; ADB.prototype.getEmulatorPort = function(cb) { logger.info("Getting running emulator port"); var me = this; if (this.emulatorPort !== null) { return cb(null, this.emulatorPort); } this.getConnectedDevices(function(err, devices) { if (err || devices.length < 1) { cb(new Error("No devices connected")); } else { // pick first device var port = me.getPortFromEmulatorString(devices[0]); if (port) { cb(null, port); } else { cb(new Error("Emulator port not found")); } } }); }; ADB.prototype.getPortFromEmulatorString = function(emStr) { var portPattern = /emulator-(\d+)/; if (portPattern.test(emStr)) { return parseInt(portPattern.exec(emStr)[1], 10); } return false; }; ADB.prototype.getRunningAVDName = function(cb) { logger.info("Getting running AVD name"); this.sendTelnetCommand("avd name", cb); }; ADB.prototype.prepareEmulator = function(cb) { if (this.avdName !== null) { this.getRunningAVDName(_.bind(function(err, runningAVDName) { if (!err && this.avdName.replace('@','') === runningAVDName) { logger.info("Did not launch AVD because it was already running."); cb(null); } else { logger.info("Launching Emulator with AVD " + this.avdName); var killallCmd = isWindows ? "TASKKILL /IM emulator.exe" : "/usr/bin/killall -m emulator*"; exec(killallCmd, _.bind(function(err, stdout) { if (err) { logger.info("Could not kill emulator. It was probably not running. : " + err.message); } this.checkSdkBinaryPresent("emulator",_.bind(function(err, emulatorBinaryPath) { if (err) { return cb(err); } if (this.avdName[0] !== "@") { this.avdName = "@" + this.avdName; } var emulatorProc = spawn(emulatorBinaryPath, [this.avdName]); var timeoutMs = 120000; var now = Date.now(); var checkEmulatorAlive = _.bind(function() { this.restartAdb(_.bind(function() { this.getConnectedDevices(_.bind(function(err, devices) { if (!err && devices.length) { cb(null, true); } else if (Date.now() < (now + timeoutMs)) { setTimeout(checkEmulatorAlive, 2000); } else { cb(new Error("Emulator didn't come up in " + timeoutMs + "ms")); } }, this)); }, this)); }, this); checkEmulatorAlive(); }, this)); }, this)); } }, this)); } else { cb(); } }; ADB.prototype.getConnectedDevices = function(cb) { this.debug("Getting connected devices..."); exec(this.adb + " devices", _.bind(function(err, stdout) { if (err) { logger.error(err); cb(err); } else if (stdout.toLowerCase().indexOf("error") !== -1) { logger.error(stdout); cb(new Error(stdout)); } else { var devices = []; _.each(stdout.split("\n"), function(line) { if (line.trim() !== "" && line.indexOf("List of devices") === -1 && line.indexOf("* daemon") === -1 && line.indexOf("offline") == -1) { devices.push(line.split("\t")); } }); this.debug(devices.length + " device(s) connected"); if (devices.length) { this.debug("Setting device id to " + (this.udid || devices[0][0])); this.emulatorPort = null; var emPort = this.getPortFromEmulatorString(devices[0][0]); this.setDeviceId(this.udid || devices[0][0]); if (emPort && !this.udid) { this.emulatorPort = emPort; } } cb(null, devices); } }, this)); }; ADB.prototype.forwardPort = function(cb) { this.requireDeviceId(); this.debug("Forwarding system:" + this.systemPort + " to device:" + this.devicePort); var arg = "tcp:" + this.systemPort + " tcp:" + this.devicePort; exec(this.adbCmd + " forward " + arg, _.bind(function(err) { if (err) { logger.error(err); cb(err); } else { this.portForwarded = true; cb(null); } }, this)); }; ADB.prototype.runBootstrap = function(readyCb, exitCb) { logger.info("Running bootstrap"); this.requireDeviceId(); var args = ["-s", this.curDeviceId, "shell", "uiautomator", "runtest", "AppiumBootstrap.jar", "-c", "io.appium.android.bootstrap.Bootstrap"]; this.proc = spawn(this.adb, args); this.onSocketReady = readyCb; this.proc.stdout.on('data', _.bind(function(data) { this.outputStreamHandler(data); }, this)); this.proc.stderr.on('data', _.bind(function(data) { this.errorStreamHandler(data); }, this)); var me = this; this.proc.on('exit', _.bind(function(code) { this.cmdCb = null; if (this.socketClient) { this.socketClient.end(); this.socketClient.destroy(); this.socketClient = null; } if (this.restartBootstrap === true) { // The bootstrap jar has crashed so it must be restarted. this.restartBootstrap = false; me.runBootstrap(function() { // Resend last command because the client is still waiting for the // response. me.resendLastCommand(); }, exitCb); return; } if (!this.alreadyExited) { this.alreadyExited = true; exitCb(code); } }, this)); }; ADB.prototype.checkForSocketReady = function(output) { if (/Appium Socket Server Ready/.test(output)) { this.requirePortForwarded(); this.debug("Connecting to server on device..."); this.socketClient = net.connect(this.systemPort, _.bind(function() { this.debug("Connected!"); this.onSocketReady(null); }, this)); this.socketClient.setEncoding('utf8'); this.socketClient.on('data', _.bind(function(data) { this.debug("Received command result from bootstrap"); try { data = JSON.parse(data); } catch (e) { this.debug("Could not parse JSON from data: " + data); data = { status: status.codes.UnknownError.code , value: "Got a bad response from Android server" }; } if (this.cmdCb) { var next = this.cmdCb; this.cmdCb = null; next(data); } else { this.debug("Got data when we weren't expecting it, ignoring:"); this.debug(JSON.stringify(data)); } }, this)); } }; ADB.prototype.sendAutomatorCommand = function(action, params, cb) { if (typeof params === "function") { cb = params; params = {}; } var extra = {action: action, params: params}; this.sendCommand('action', extra, cb); }; ADB.prototype.sendCommand = function(type, extra, cb) { if (this.cmdCb !== null) { logger.warn("Trying to run a command when one is already in progress. " + "Will spin a bit and try again"); var me = this; var start = Date.now(); var timeoutMs = 10000; var intMs = 200; var waitForCmdCbNull = function() { if (me.cmdCb === null) { me.sendCommand(type, extra, cb); } else if ((Date.now() - start) < timeoutMs) { setTimeout(waitForCmdCbNull, intMs); } else { cb(new Error("Never became able to push strings since a command " + "was in process")); } }; waitForCmdCbNull(); } else if (this.socketClient) { this.resendLastCommand = _.bind(function() { this.sendCommand(type, extra, cb); }, this); if (typeof extra === "undefined" || extra === null) { extra = {}; } var cmd = {cmd: type}; cmd = _.extend(cmd, extra); var cmdJson = JSON.stringify(cmd) + "\n"; this.cmdCb = cb; var logCmd = cmdJson.trim(); if (logCmd.length > 1000) { logCmd = logCmd.substr(0, 1000) + "..."; } this.debug("Sending command to android: " + logCmd); this.socketClient.write(cmdJson); } else { cb({ status: status.codes.UnknownError.code , value: "Tried to send command to non-existent Android socket, " + "maybe it's shutting down?" }); } }; ADB.prototype.sendShutdownCommand = function(cb) { setTimeout(_.bind(function() { if (!this.alreadyExited) { logger.warn("Android did not shut down fast enough, calling it gone"); this.alreadyExited = true; this.onExit(1); } }, this), 7000); this.sendCommand('shutdown', null, cb); }; ADB.prototype.outputStreamHandler = function(output) { this.checkForSocketReady(output); this.handleBootstrapOutput(output); }; ADB.prototype.handleBootstrapOutput = function(output) { // for now, assume all intentional logging takes place on one line // and that we don't get half-lines from the stream. // probably bad assumptions output = output.toString().trim(); var lines = output.split("\n"); var re = /^\[APPIUM-UIAUTO\] (.+)\[\/APPIUM-UIAUTO\]$/; var match; var me = this; _.each(lines, function(line) { line = line.trim(); if (line !== '') { match = re.exec(line); if (match) { logger.info("[ANDROID] " + match[1]); var alertRe = /Emitting system alert message/; if (alertRe.test(line)) { logger.info("Emiting alert message..."); me.webSocket.sockets.emit('alert', {message: line}); } } else { // The dump command will always disconnect UiAutomation. // Detect the crash then restart UiAutomation. if (line.indexOf("UiAutomationService not connected") !== -1) { me.restartBootstrap = true; } logger.info(("[ADB STDOUT] " + line).grey); } } }); }; ADB.prototype.errorStreamHandler = function(output) { var lines = output.split("\n"); _.each(lines, function(line) { logger.info(("[ADB STDERR] " + line).yellow); }); }; ADB.prototype.debug = function(msg) { if (this.debugMode) { logger.info("[ADB] " + msg); } }; ADB.prototype.isDeviceConnected = function(cb) { this.getConnectedDevices(function(err, devices) { if (err) { cb(err); } else { cb(null, devices.length > 0); } }); }; ADB.prototype.setDeviceId = function(deviceId) { this.curDeviceId = deviceId; this.adbCmd = this.adb + " -s " + deviceId; }; ADB.prototype.requireDeviceId = function() { if (!this.curDeviceId) { throw new Error("This method requires that a device ID is set. " + "Call getConnectedDevices or setDeviceId"); } }; ADB.prototype.requirePortForwarded = function() { if (!this.portForwarded) { throw new Error("This method requires the port be forwarded on the " + "device. Make sure to call forwardPort()!"); } }; ADB.prototype.requireApp = function() { if (!this.appPackage || !this.appActivity) { throw new Error("This method requires that appPackage and appActivity " + "be sent in with options"); } }; ADB.prototype.requireApk = function() { if (!this.apkPath) { throw new Error("This method requires that apkPath be sent in as option"); } }; ADB.prototype.waitForDevice = function(cb) { var doWait = _.bind(function(innerCb) { this.debug("Waiting for device " + this.curDeviceId + " to be ready " + "and to respond to shell commands (timeout = " + this.appDeviceReadyTimeout + ")"); var movedOn = false , cmd = this.adbCmd + " wait-for-device" , timeoutSecs = parseInt(this.appDeviceReadyTimeout, 10); setTimeout(_.bind(function() { if (!movedOn) { movedOn = true; innerCb("Device did not become ready in " + timeoutSecs + " secs; " + "are you sure it's powered on?"); } }, this), timeoutSecs * 1000); exec(cmd, _.bind(function(err) { if (!movedOn) { if (err) { logger.error("Error running wait-for-device"); movedOn = true; innerCb(err); } else { exec(this.adbCmd + " shell echo 'ready'", _.bind(function(err) { if (!movedOn) { movedOn = true; if (err) { logger.error("Error running shell echo: " + err); innerCb(err); } else { innerCb(null); } } }, this)); } } }, this)); }, this); doWait(_.bind(function(err) { if (err) { this.restartAdb(_.bind(function() { this.getConnectedDevices(function() { doWait(cb); }); }, this)); } else { cb(null); } }, this)); }; ADB.prototype.restartAdb = function(cb) { logger.info("Killing ADB server so it will come back online"); var cmd = this.adb + " kill-server"; exec(cmd, function(err) { if (err) { logger.error("Error killing ADB server, going to see if it's online " + "anyway"); } cb(); }); }; ADB.prototype.pushAppium = function(cb) { this.debug("Pushing appium bootstrap to device..."); var binPath = path.resolve(__dirname, "..", "build", "android_bootstrap", "AppiumBootstrap.jar"); fs.stat(binPath, _.bind(function(err) { if (err) { cb("Could not find AppiumBootstrap.jar; please run " + "'grunt buildAndroidBootstrap'"); } else { var remotePath = "/data/local/tmp"; var cmd = this.adbCmd + " push " + binPath + " " + remotePath; exec(cmd, _.bind(function(err) { if (err) { logger.error(err); cb(err); } else { cb(null); } }, this)); } }, this)); }; ADB.prototype.startApp = function(cb) { logger.info("Starting app"); this.requireDeviceId(); this.requireApp(); var activityString = this.appActivity; var hasNoPrefix = true; var rootPrefixes = ['com', 'net', 'org', 'io']; _.each(rootPrefixes, function(prefix) { if (activityString.indexOf(prefix + ".") !== -1) { hasNoPrefix = false; } }); if (hasNoPrefix) { activityString = this.appPackage + "." + activityString; } var cmd = this.adbCmd + " shell am start -n " + this.appPackage + "/" + activityString; this.debug("Starting app " + this.appPackage + "/" + activityString); exec(cmd, _.bind(function(err) { if(err) { logger.error(err); cb(err); } else { this.waitForActivity(cb); } }, this)); }; ADB.prototype.stopApp = function(cb) { logger.info("Killing app"); this.requireDeviceId(); this.requireApp(); var cmd = this.adbCmd + " shell am force-stop " + this.appPackage; exec(cmd, function(err) { if (err) { logger.error(err); return cb(err); } cb(); }); }; ADB.prototype.getFocusedPackageAndActivity = function(cb) { logger.info("Getting focused package and activity"); this.requireDeviceId(); var cmd = this.adbCmd + " shell dumpsys window windows" , searchRe = new RegExp(/mFocusedApp.+ ([a-zA-Z0-9\.]+)\/\.?([^\}]+)\}/); exec(cmd, _.bind(function(err, stdout) { if (err) { logger.error(err); cb(err); } else { var foundMatch = false; _.each(stdout.split("\n"), function(line) { var match = searchRe.exec(line); if (match) { foundMatch = match; } }); if (foundMatch) { cb(null, foundMatch[1], foundMatch[2]); } else { cb(new Error("Could not parse activity from dumpsys")); } } }, this)); }; ADB.prototype.waitForNotActivity = function(cb) { this.requireApp(); logger.info("Waiting for app's activity to not be focused"); var waitMs = 20000 , intMs = 750 , endAt = Date.now() + waitMs , targetActivity = this.appWaitActivity || this.appActivity; var getFocusedApp = _.bind(function() { this.getFocusedPackageAndActivity(_.bind(function(err, foundPackage, foundActivity) { if (foundPackage !== this.appPackage && foundActivity !== targetActivity) { cb(null); } else if (Date.now() < endAt) { if (err) logger.info(err); setTimeout(getFocusedApp, intMs); } else { var msg = "App never closed. appActivity: " + foundActivity + " != " + targetActivity; logger.error(msg); cb(new Error(msg)); } }, this)); }, this); getFocusedApp(); }; ADB.prototype.waitForActivity = function(cb) { this.requireApp(); logger.info("Waiting for app's activity to become focused"); var waitMs = 20000 , intMs = 750 , endAt = Date.now() + waitMs , targetActivity = this.appWaitActivity || this.appActivity; var getFocusedApp = _.bind(function() { this.getFocusedPackageAndActivity(_.bind(function(err, foundPackage, foundActivity) { if (foundPackage === this.appPackage && foundActivity === targetActivity) { cb(null); } else if (Date.now() < endAt) { if (err) logger.info(err); setTimeout(getFocusedApp, intMs); } else { var msg = "App never showed up as active. appActivity: " + foundActivity + " != " + targetActivity; logger.error(msg); cb(new Error(msg)); } }, this)); }, this); getFocusedApp(); }; ADB.prototype.uninstallApk = function(pkg, cb) { logger.info("Uninstalling " + pkg); var cmd = this.adbCmd + " uninstall " + pkg; exec(cmd, function(err, stdout) { if (err) { logger.error(err); cb(err); } else { stdout = stdout.trim(); if (stdout === "Success") { logger.debug("App was uninstalled"); } else { logger.debug("App was not uninstalled, maybe it wasn't on device?"); } cb(null); } }); }; ADB.prototype.installApk = function(apk, cb) { var cmd = this.adbCmd + ' install -r "' + apk + '"'; logger.info("Installing " + apk); exec(cmd,function(err, stdout) { if (err) { logger.error(err); cb(err); } else { // Useful for debugging. logger.debug(stdout); cb(null); } }); }; ADB.prototype.uninstallApp = function(cb) { var me = this; var next = function() { me.requireDeviceId(); me.requireApp(); me.debug("Uninstalling app " + me.appPackage); me.uninstallApk(me.appPackage, function(err) { if (me.fastReset) { var cleanPkg = me.appPackage + '.clean'; me.debug("Uninstalling app " + cleanPkg); me.uninstallApk(cleanPkg, function(err) { if (err) return cb(err); cb(null); }); } else { if (err) return cb(err); cb(null); } }); }; if (me.skipUninstall) { me.debug("Not uninstalling app since server started with --reset"); cb(); } else { next(); } }; ADB.prototype.runFastReset = function(cb) { // list instruments with: adb shell pm list instrumentation // targetPackage + '.clean' / clean.apk.Clear var me = this; var clearCmd = me.adbCmd + ' shell am instrument ' + me.appPackage + '.clean/clean.apk.Clean'; logger.debug("Running fast reset clean: " + clearCmd); exec(clearCmd, {}, function(err, stdout, stderr) { if (err) { logger.warn(stderr); cb(err); } else { cb(null); } }); }; ADB.prototype.checkAppInstallStatus = function(pkg, cb) { var installed = false , cleanInstalled = false; this.requireDeviceId(); logger.debug("Getting install/clean status for " + pkg); var listPkgCmd = this.adbCmd + " shell pm list packages -3 " + pkg; exec(listPkgCmd, function(err, stdout) { var apkInstalledRgx = new RegExp('^package:' + pkg.replace(/([^a-zA-Z])/g, "\\$1") + '$', 'm'); installed = apkInstalledRgx.test(stdout); var cleanInstalledRgx = new RegExp('^package:' + (pkg + '.clean').replace(/([^a-zA-Z])/g, "\\$1") + '$', 'm'); cleanInstalled = cleanInstalledRgx.test(stdout); cb(null, installed, cleanInstalled); }); }; ADB.prototype.installApp = function(cb) { var me = this , installApp = false , installClean = false; me.requireDeviceId(); if (this.apkPath === null) { logger.info("Not installing app since we launched with a package instead " + "of an app path"); return cb(null); } me.requireApk(); var determineInstallAndCleanStatus = function(cb) { logger.info("Determining app install/clean status"); me.checkAppInstallStatus(me.appPackage, function(err, installed, cleaned) { installApp = !installed; installClean = !cleaned; cb(); }); }; var doInstall = function(cb) { if (installApp) { me.debug("Installing app apk"); me.installApk(me.apkPath, cb); } else { cb(null); } }; var doClean = function(cb) { if (installClean && me.cleanApp) { me.debug("Installing clean apk"); me.installApk(me.cleanAPK, cb); } else { cb(null); } }; var doFastReset = function(cb) { // App is already installed so reset it. if (!installApp && me.fastReset) { me.runFastReset(cb); } else { cb(null); } }; async.series([ function(cb) { determineInstallAndCleanStatus(cb); }, function(cb) { doInstall(cb); }, function(cb) { doClean(cb); }, function(cb) { doFastReset(cb); } ], cb); }; ADB.prototype.back = function(cb) { this.requireDeviceId(); this.debug("Pressing the BACK button"); var cmd = this.adbCmd + " shell input keyevent 4"; exec(cmd, function() { cb(); }); }; ADB.prototype.goToHome = function(cb) { this.requireDeviceId(); this.debug("Pressing the HOME button"); var cmd = this.adbCmd + " shell input keyevent 3"; exec(cmd, function() { cb(); }); }; ADB.prototype.wakeUp = function(cb) { // requires an appium bootstrap connection loaded this.debug("Waking up device if it's not alive"); this.android.proxy(["wake", {}], cb); }; ADB.prototype.keyevent = function(keycode, cb) { this.requireDeviceId(); var code = parseInt(keycode, 10); // keycode must be an int. var cmd = this.adbCmd + ' shell input keyevent ' + code; this.debug("Sending keyevent " + code); exec(cmd, function() { cb(); }); }; ADB.prototype.unlockScreen = function(cb) { this.requireDeviceId(); this.debug("Attempting to unlock screen"); var cmd = this.adbCmd + " shell input keyevent 82"; exec(cmd, function() { cb(); }); }; ADB.prototype.sendTelnetCommand = function(command, cb) { logger.info("Sending telnet command to device: " + command); this.getEmulatorPort(function(err, port) { if (err) return cb(err); var conn = net.createConnection(port, 'localhost'); var connected = false; var readyRegex = /^OK$/m; var dataStream = ""; var res = null; var onReady = function() { logger.info("Socket connection to device ready"); conn.write(command + "\n"); }; conn.on('connect', function() { logger.info("Socket connection to device created"); }); conn.on('data', function(data) { data = data.toString('utf8'); if (!connected) { if (readyRegex.test(data)) { connected = true; onReady(); } } else { dataStream += data; if (readyRegex.test(data)) { res = dataStream.replace(readyRegex, "").trim(); logger.info("Telnet command got response: " + res); conn.write("quit\n"); } } }); conn.on('close', function() { if (res === null) { cb(new Error("Never got a response from command")); } else { cb(null, res); } }); }); }; module.exports = function(opts, android) { return new ADB(opts, android); };
android/adb.js
"use strict"; var spawn = require('win-spawn') , exec = require('child_process').exec , path = require('path') , fs = require('fs') , net = require('net') , logger = require('../logger').get('appium') , status = require('../app/uiauto/lib/status') , unzipFile = require('../app/helpers').unzipFile , testZipArchive = require('../app/helpers').testZipArchive , async = require('async') , ncp = require('ncp') , mkdirp = require('mkdirp') , _ = require('underscore') , helpers = require('../app/helpers') , AdmZip = require('adm-zip') , getTempPath = helpers.getTempPath , isWindows = helpers.isWindows(); var noop = function() {}; var ADB = function(opts, android) { if (!opts) { opts = {}; } if (typeof opts.sdkRoot === "undefined") { opts.sdkRoot = process.env.ANDROID_HOME || ''; } this.sdkRoot = opts.sdkRoot; this.udid = opts.udid; this.webSocket = opts.webSocket; // Don't uninstall if using fast reset. // Uninstall if reset is set and fast reset isn't. this.skipUninstall = opts.fastReset || !(opts.reset || false); this.systemPort = opts.port || 4724; this.devicePort = opts.devicePort || 4724; this.avdName = opts.avdName; this.appPackage = opts.appPackage; this.appActivity = opts.appActivity; this.appWaitActivity = opts.appWaitActivity; this.appDeviceReadyTimeout = opts.appDeviceReadyTimeout; this.apkPath = opts.apkPath; this.adb = "adb"; this.adbCmd = this.adb; this.curDeviceId = null; this.socketClient = null; this.proc = null; this.onSocketReady = noop; this.onExit = noop; this.alreadyExited = false; this.portForwarded = false; this.emulatorPort = null; this.debugMode = true; this.fastReset = opts.fastReset; this.cleanApp = opts.cleanApp || this.fastReset; this.cleanAPK = path.resolve(helpers.getTempPath(), this.appPackage + '.clean.apk'); // This is set to true when the bootstrap jar crashes. this.restartBootstrap = false; // The android ref is used to resend the command that // detected the crash. this.android = android; this.cmdCb = null; this.binaries = {}; }; ADB.prototype.checkSdkBinaryPresent = function(binary, cb) { logger.info("Checking whether " + binary + " is present"); var binaryLoc = null; var binaryName = binary; if (isWindows) { if (binaryName === "android") { binaryName += ".bat"; } else { if (binaryName.indexOf(".exe", binaryName.length - 4) == -1) { binaryName += ".exe"; } } } if (this.sdkRoot) { var binaryLocs = [ path.resolve(this.sdkRoot, "platform-tools", binaryName) , path.resolve(this.sdkRoot, "tools", binaryName) , path.resolve(this.sdkRoot, "build-tools", "17.0.0", binaryName) , path.resolve(this.sdkRoot, "build-tools", "android-4.2.2", binaryName)]; _.each(binaryLocs, function(loc) { if (fs.existsSync(loc)) binaryLoc = loc; }); if (binaryLoc === null) { cb(new Error("Could not find " + binary + " in tools, platform-tools, or build-tools; " + "do you have android SDK installed?"), null); return; } this.debug("Using " + binary + " from " + binaryLoc); this.binaries[binary] = binaryLoc; cb(null, binaryLoc); } else { exec("which " + binary, _.bind(function(err, stdout) { if (stdout) { this.debug("Using " + binary + " from " + stdout); cb(null, stdout); } else { cb(new Error("Could not find " + binary + "; do you have android " + "SDK installed?"), null); } }, this)); } }; ADB.prototype.checkAdbPresent = function(cb) { this.checkSdkBinaryPresent("adb", _.bind(function(err, binaryLoc) { if (err) return cb(err); this.adb = binaryLoc.trim(); cb(null); }, this)); }; ADB.prototype.checkAppPresent = function(cb) { if (this.apkPath === null) { logger.info("Not checking whether app is present since we are assuming " + "it's already on the device"); cb(null); } else { logger.info("Checking whether app is actually present"); fs.stat(this.apkPath, _.bind(function(err) { if (err) { logger.error("Could not find app apk at " + this.apkPath); cb(new Error("Error locating the app apk, supposedly it's at " + this.apkPath + " but we can't stat it. Filesystem error " + "is " + err)); } else { cb(null); } }, this)); } }; // Fast reset ADB.prototype.buildFastReset = function(skipAppSign, cb) { logger.info("Building fast reset"); // Create manifest var me = this , targetAPK = me.apkPath , cleanAPKSrc = path.resolve(__dirname, '../app/android/Clean.apk') , newPackage = me.appPackage + '.clean' , srcManifest = path.resolve(__dirname, '../app/android/AndroidManifest.xml.src') , dstManifest = path.resolve(getTempPath(), 'AndroidManifest.xml'); fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8"); var resignApks = function(cb) { // Resign clean apk and target apk var apks = [ me.cleanAPK ]; if (!skipAppSign) { logger.debug("Signing app and clean apk."); apks.push(targetAPK); } else { logger.debug("Skip app sign. Sign clean apk."); } me.sign(apks, cb); }; async.series([ function(cb) { me.checkSdkBinaryPresent("aapt", cb); }, function(cb) { me.compileManifest(dstManifest, newPackage, me.appPackage, cb); }, function(cb) { me.insertManifest(dstManifest, cleanAPKSrc, me.cleanAPK, cb); }, function(cb) { resignApks(cb); } ], cb); }; ADB.prototype.insertSelendroidManifest = function(serverPath, cb) { logger.info("Inserting selendroid manifest"); var me = this , newServerPath = me.selendroidServerPath , newPackage = me.appPackage + '.selendroid' , srcManifest = path.resolve(__dirname, "../build/selendroid/AndroidManifest.xml") , dstDir = path.resolve(getTempPath(), this.appPackage) , dstManifest = dstDir + '/AndroidManifest.xml'; try { fs.mkdirSync(dstDir); } catch (e) { if (e.message.indexOf("EEXIST") === -1) { throw e; } } fs.writeFileSync(dstManifest, fs.readFileSync(srcManifest, "utf8"), "utf8"); async.series([ function(cb) { mkdirp(dstDir, cb); }, function(cb) { me.checkSdkBinaryPresent("aapt", cb); }, function(cb) { me.compileManifest(dstManifest, newPackage, me.appPackage, cb); }, function(cb) { me.insertManifest(dstManifest, serverPath, newServerPath, cb); } ], cb); }; ADB.prototype.compileManifest = function(manifest, manifestPackage, targetPackage, cb) { logger.info("Compiling manifest " + manifest); var androidHome = process.env.ANDROID_HOME , platforms = path.resolve(androidHome , 'platforms') , platform = 'android-17'; // android-17 may be called android-4.2 if (!fs.existsSync(path.resolve(platforms, platform))) { platform = 'android-4.2'; if (!fs.existsSync(path.resolve(platforms, platform))) { return cb(new Error("Platform doesn't exist " + platform)); } } // Compile manifest into manifest.xml.apk var compileManifest = [this.binaries.aapt + ' package -M "', manifest + '"', ' --rename-manifest-package "', manifestPackage + '"', ' --rename-instrumentation-target-package "', targetPackage + '"', ' -I "', path.resolve(platforms, platform, 'android.jar') +'" -F "', manifest, '.apk" -f'].join(''); logger.debug(compileManifest); exec(compileManifest, {}, function(err, stdout, stderr) { if (err) { logger.debug(stderr); return cb("error compiling manifest"); } logger.debug("Compiled manifest"); cb(null); }); }; ADB.prototype.insertManifest = function(manifest, srcApk, dstApk, cb) { logger.info("Inserting manifest, src: " + srcApk + ", dst: " + dstApk); var extractManifest = function(cb) { logger.debug("Extracting manifest"); // Extract compiled manifest from manifest.xml.apk unzipFile(manifest + '.apk', function(err, stderr) { if (err) { logger.info("Error unzipping manifest apk, here's stderr:"); logger.debug(stderr); return cb(err); } cb(null); }); }; var createTmpApk = function(cb) { logger.debug("Writing tmp apk. " + srcApk + ' to ' + dstApk); ncp(srcApk, dstApk, cb); }; var testDstApk = function(cb) { logger.debug("Testing new tmp apk."); testZipArchive(dstApk, cb); }; var moveManifest = function(cb) { if (isWindows) { try { var existingAPKzip = new AdmZip(dstApk); var newAPKzip = new AdmZip(); existingAPKzip.getEntries().forEach(function(entry) { var entryName = entry.entryName; newAPKzip.addZipEntryComment(entry, entryName); }); newAPKzip.addLocalFile(manifest); newAPKzip.writeZip(dstApk); logger.debug("Inserted manifest."); cb(null); } catch(err) { logger.info("Got error moving manifest: " + err); cb(err); } } else { // Insert compiled manifest into /tmp/appPackage.clean.apk // -j = keep only the file, not the dirs // -m = move manifest into target apk. var replaceCmd = 'zip -j -m "' + dstApk + '" "' + manifest + '"'; logger.debug("Moving manifest with: " + replaceCmd); exec(replaceCmd, {}, function(err) { if (err) { logger.info("Got error moving manifest: " + err); return cb(err); } logger.debug("Inserted manifest."); cb(null); }); } }; async.series([ function(cb) { extractManifest(cb); }, function(cb) { createTmpApk(cb); }, function(cb) { testDstApk(cb); }, function(cb) { moveManifest(cb); } ], cb); }; // apks is an array of strings. ADB.prototype.sign = function(apks, cb) { var signPath = path.resolve(__dirname, '../app/android/sign.jar'); var resign = 'java -jar "' + signPath + '" "' + apks.join('" "') + '" --override'; logger.debug("Resigning apks with: " + resign); exec(resign, {}, function(err, stdout, stderr) { if (stderr.indexOf("Input is not an existing file") !== -1) { logger.warn("Could not resign apk(s), got non-existing file error"); return cb(new Error("Could not sign one or more apks. Are you sure " + "the file paths are correct: " + JSON.stringify(apks))); } cb(err); }); }; // returns true when already signed, false otherwise. ADB.prototype.checkApkCert = function(apk, cb) { var verifyPath = path.resolve(__dirname, '../app/android/verify.jar'); var resign = 'java -jar "' + verifyPath + '" "' + apk + '"'; logger.debug("Checking app cert for " + apk + ": " + resign); exec(resign, {}, function(err) { if (err) { logger.debug("App not signed with debug cert."); return cb(false); } logger.debug("App already signed."); cb(true); }); }; ADB.prototype.checkFastReset = function(cb) { logger.info("Checking whether we need to run fast reset"); // NOP if fast reset is not true. if (!this.fastReset) { logger.info("User doesn't want fast reset, doing nothing"); return cb(null); } if (this.apkPath === null) { logger.info("Can't run fast reset on an app that's already on the device " + "so doing nothing"); return cb(null); } if (!this.appPackage) return cb(new Error("appPackage must be set.")); var me = this; me.checkApkCert(me.cleanAPK, function(cleanSigned){ me.checkApkCert(me.apkPath, function(appSigned){ // Only build & resign clean.apk if it doesn't exist or isn't signed. if (!fs.existsSync(me.cleanAPK) || !cleanSigned) { me.buildFastReset(appSigned, function(err){ if (err) return cb(err); cb(null); }); } else { if (!appSigned) { // Resign app apk because it's not signed. me.sign([me.apkPath], cb); } else { // App and clean are already existing and signed. cb(null); } } }); }); }; ADB.prototype.getDeviceWithRetry = function(cb) { logger.info("Trying to find a connected android device"); var me = this; var getDevices = function(innerCb) { me.getConnectedDevices(function(err, devices) { if (typeof devices === "undefined" || devices.length === 0 || err) { return innerCb(new Error("Could not find a connected Android device.")); } innerCb(null); }); }; getDevices(function(err) { if (err) { logger.info("Could not find devices, restarting adb server..."); me.restartAdb(function() { getDevices(cb); }); } else { logger.info("Found device, no need to retry"); cb(null); } }); }; ADB.prototype.prepareDevice = function(onReady) { logger.info("Preparing device for session"); var me = this; async.series([ function(cb) { me.checkAppPresent(cb); }, function(cb) { me.checkAdbPresent(cb); }, function(cb) { me.prepareEmulator(cb); }, function(cb) { me.getDeviceWithRetry(cb);}, function(cb) { me.waitForDevice(cb); }, function(cb) { me.checkFastReset(cb); } ], onReady); }; ADB.prototype.pushStrings = function(cb) { var me = this; var stringsFromApkJarPath = path.resolve(__dirname, '../app/android/strings_from_apk.jar'); var outputPath = path.resolve(getTempPath(), me.appPackage); var makeStrings = ['java -jar ', stringsFromApkJarPath, ' ', me.apkPath, ' ', outputPath].join(''); logger.debug(makeStrings); exec(makeStrings, {}, function(err, stdout, stderr) { if (err) { logger.debug(stderr); return cb("error making strings"); } var jsonFile = path.resolve(outputPath, 'strings.json'); var remotePath = "/data/local/tmp"; var pushCmd = me.adbCmd + " push " + jsonFile + " " + remotePath; exec(pushCmd, {}, function(err, stdout, stderr) { cb(null); }); }); }; ADB.prototype.startAppium = function(onReady, onExit) { logger.info("Starting android appium"); var me = this; this.onExit = onExit; logger.debug("Using fast reset? " + this.fastReset); async.series([ function(cb) { me.prepareDevice(cb); }, function(cb) { me.pushStrings(cb); }, function(cb) { me.uninstallApp(cb); }, function(cb) { me.installApp(cb); }, function(cb) { me.forwardPort(cb); }, function(cb) { me.pushAppium(cb); }, function(cb) { me.runBootstrap(cb, onExit); }, function(cb) { me.wakeUp(cb); }, function(cb) { me.unlockScreen(cb); }, function(cb) { me.startApp(cb); } ], function(err) { onReady(err); }); }; ADB.prototype.startSelendroid = function(serverPath, onReady) { logger.info("Starting selendroid"); var me = this , modServerExists = false , modAppPkg = this.appPackage + '.selendroid'; this.selendroidServerPath = path.resolve(getTempPath(), 'selendroid.' + this.appPackage + '.apk'); var checkModServerExists = function(cb) { fs.stat(me.selendroidServerPath, function(err) { modServerExists = !err; cb(); }); }; var conditionalUninstallSelendroid = function(cb) { if (!modServerExists) { // assume we're going to rebuild selendroid and therefore // need to uninstall it if it's already on device logger.info("Rebuilt selendroid apk does not exist, uninstalling " + "any instances of it on device to make way for new one"); me.uninstallApk(modAppPkg, cb); } else { logger.info("Rebuilt selendroid apk exists, doing nothing"); cb(); } }; var conditionalInsertManifest = function(cb) { if (!modServerExists) { logger.info("Rebuilt selendroid server does not exist, inserting " + "modified manifest"); me.insertSelendroidManifest(serverPath, cb); } else { logger.info("Rebuilt selendroid server already exists, no need to " + "rebuild it with a new manifest"); cb(); } }; var conditionalInstallSelendroid = function(cb) { me.checkAppInstallStatus(modAppPkg, function(e, installed) { if (!installed) { logger.info("Rebuilt selendroid is not installed, installing it"); me.installApk(me.selendroidServerPath, cb); } else { logger.info("Rebuilt selendroid is already installed"); cb(); } }); }; async.series([ function(cb) { me.prepareDevice(cb); }, function(cb) { checkModServerExists(cb); }, function(cb) { conditionalUninstallSelendroid(cb); }, function(cb) { conditionalInsertManifest(cb); }, function(cb) { me.checkSelendroidCerts(me.selendroidServerPath, cb); }, function(cb) { conditionalInstallSelendroid(cb); }, function(cb) { me.installApp(cb); }, function(cb) { me.forwardPort(cb); }, function(cb) { me.unlockScreen(cb); }, function(cb) { me.pushSelendroid(cb); }, function(cb) { logger.info("Selendroid server is launching"); cb(); } ], onReady); }; ADB.prototype.pushSelendroid = function(cb) { var cmd = "adb shell am instrument -e main_activity '" + this.appPackage + "." + this.appActivity + "' " + this.appPackage + ".selendroid/org.openqa.selendroid.ServerInstrumentation"; logger.info("Starting instrumentation process for selendroid with cmd: " + cmd); exec(cmd, function(err, stdout) { if (stdout.indexOf("Exception") !== -1) { logger.error(stdout); var msg = stdout.split("\n")[0] || "Unknown exception starting selendroid"; return cb(new Error(msg)); } cb(); }); }; ADB.prototype.checkSelendroidCerts = function(serverPath, cb) { var me = this , alreadyReturned = false , checks = 0; var onDoneSigning = function() { checks++; if (checks === 2 && !alreadyReturned) { cb(); } }; // these run in parallel var apks = [serverPath, this.apkPath]; _.each(apks, function(apk) { logger.info("Checking signed status of " + apk); me.checkApkCert(apk, function(isSigned) { if (isSigned) return onDoneSigning(); me.sign([apk], function(err) { if (err && !alreadyReturned) { alreadyReturned = true; return cb(err); } onDoneSigning(); }); }); }); }; ADB.prototype.getEmulatorPort = function(cb) { logger.info("Getting running emulator port"); var me = this; if (this.emulatorPort !== null) { return cb(null, this.emulatorPort); } this.getConnectedDevices(function(err, devices) { if (err || devices.length < 1) { cb(new Error("No devices connected")); } else { // pick first device var port = me.getPortFromEmulatorString(devices[0]); if (port) { cb(null, port); } else { cb(new Error("Emulator port not found")); } } }); }; ADB.prototype.getPortFromEmulatorString = function(emStr) { var portPattern = /emulator-(\d+)/; if (portPattern.test(emStr)) { return parseInt(portPattern.exec(emStr)[1], 10); } return false; }; ADB.prototype.getRunningAVDName = function(cb) { logger.info("Getting running AVD name"); this.sendTelnetCommand("avd name", cb); }; ADB.prototype.prepareEmulator = function(cb) { if (this.avdName !== null) { this.getRunningAVDName(_.bind(function(err, runningAVDName) { if (!err && this.avdName.replace('@','') === runningAVDName) { logger.info("Did not launch AVD because it was already running."); cb(null); } else { logger.info("Launching Emulator with AVD " + this.avdName); var killallCmd = isWindows ? "TASKKILL /IM emulator.exe" : "/usr/bin/killall -m emulator*"; exec(killallCmd, _.bind(function(err, stdout) { if (err) { logger.info("Could not kill emulator. It was probably not running. : " + err.message); } this.checkSdkBinaryPresent("emulator",_.bind(function(err, emulatorBinaryPath) { if (err) { return cb(err); } if (this.avdName[0] !== "@") { this.avdName = "@" + this.avdName; } var emulatorProc = spawn(emulatorBinaryPath, [this.avdName]); var timeoutMs = 120000; var now = Date.now(); var checkEmulatorAlive = _.bind(function() { this.restartAdb(_.bind(function() { this.getConnectedDevices(_.bind(function(err, devices) { if (!err && devices.length) { cb(null, true); } else if (Date.now() < (now + timeoutMs)) { setTimeout(checkEmulatorAlive, 2000); } else { cb(new Error("Emulator didn't come up in " + timeoutMs + "ms")); } }, this)); }, this)); }, this); checkEmulatorAlive(); }, this)); }, this)); } }, this)); } else { cb(); } }; ADB.prototype.getConnectedDevices = function(cb) { this.debug("Getting connected devices..."); exec(this.adb + " devices", _.bind(function(err, stdout) { if (err) { logger.error(err); cb(err); } else if (stdout.toLowerCase().indexOf("error") !== -1) { logger.error(stdout); cb(new Error(stdout)); } else { var devices = []; _.each(stdout.split("\n"), function(line) { if (line.trim() !== "" && line.indexOf("List of devices") === -1 && line.indexOf("* daemon") === -1 && line.indexOf("offline") == -1) { devices.push(line.split("\t")); } }); this.debug(devices.length + " device(s) connected"); if (devices.length) { this.debug("Setting device id to " + (this.udid || devices[0][0])); this.emulatorPort = null; var emPort = this.getPortFromEmulatorString(devices[0][0]); this.setDeviceId(this.udid || devices[0][0]); if (emPort && !this.udid) { this.emulatorPort = emPort; } } cb(null, devices); } }, this)); }; ADB.prototype.forwardPort = function(cb) { this.requireDeviceId(); this.debug("Forwarding system:" + this.systemPort + " to device:" + this.devicePort); var arg = "tcp:" + this.systemPort + " tcp:" + this.devicePort; exec(this.adbCmd + " forward " + arg, _.bind(function(err) { if (err) { logger.error(err); cb(err); } else { this.portForwarded = true; cb(null); } }, this)); }; ADB.prototype.runBootstrap = function(readyCb, exitCb) { logger.info("Running bootstrap"); this.requireDeviceId(); var args = ["-s", this.curDeviceId, "shell", "uiautomator", "runtest", "AppiumBootstrap.jar", "-c", "io.appium.android.bootstrap.Bootstrap"]; this.proc = spawn(this.adb, args); this.onSocketReady = readyCb; this.proc.stdout.on('data', _.bind(function(data) { this.outputStreamHandler(data); }, this)); this.proc.stderr.on('data', _.bind(function(data) { this.errorStreamHandler(data); }, this)); var me = this; this.proc.on('exit', _.bind(function(code) { if (this.socketClient) { this.socketClient.end(); this.socketClient.destroy(); this.socketClient = null; } if (this.restartBootstrap === true) { // The bootstrap jar has crashed so it must be restarted. this.restartBootstrap = false; me.runBootstrap(function() { // Resend last command because the client is still waiting for the // response. me.android.push(null, true); }, exitCb); return; } if (!this.alreadyExited) { this.alreadyExited = true; exitCb(code); } }, this)); }; ADB.prototype.checkForSocketReady = function(output) { if (/Appium Socket Server Ready/.test(output)) { this.requirePortForwarded(); this.debug("Connecting to server on device..."); this.socketClient = net.connect(this.systemPort, _.bind(function() { this.debug("Connected!"); this.onSocketReady(null); }, this)); this.socketClient.setEncoding('utf8'); this.socketClient.on('data', _.bind(function(data) { this.debug("Received command result from bootstrap"); try { data = JSON.parse(data); } catch (e) { this.debug("Could not parse JSON from data: " + data); data = { status: status.codes.UnknownError.code , value: "Got a bad response from Android server" }; } if (this.cmdCb) { var next = this.cmdCb; this.cmdCb = null; next(data); } else { this.debug("Got data when we weren't expecting it, ignoring:"); this.debug(JSON.stringify(data)); } }, this)); } }; ADB.prototype.sendAutomatorCommand = function(action, params, cb) { if (typeof params === "function") { cb = params; params = {}; } var extra = {action: action, params: params}; this.sendCommand('action', extra, cb); }; ADB.prototype.sendCommand = function(type, extra, cb) { if (this.cmdCb !== null) { logger.warn("Trying to run a command when one is already in progress. " + "Will spin a bit and try again"); var me = this; var start = Date.now(); var timeoutMs = 10000; var intMs = 200; var waitForCmdCbNull = function() { if (me.cmdCb === null) { me.sendCommand(type, extra, cb); } else if ((Date.now() - start) < timeoutMs) { setTimeout(waitForCmdCbNull, intMs); } else { cb(new Error("Never became able to push strings since a command " + "was in process")); } }; waitForCmdCbNull(); } else if (this.socketClient) { if (typeof extra === "undefined" || extra === null) { extra = {}; } var cmd = {cmd: type}; cmd = _.extend(cmd, extra); var cmdJson = JSON.stringify(cmd) + "\n"; this.cmdCb = cb; var logCmd = cmdJson.trim(); if (logCmd.length > 1000) { logCmd = logCmd.substr(0, 1000) + "..."; } this.debug("Sending command to android: " + logCmd); this.socketClient.write(cmdJson); } else { cb({ status: status.codes.UnknownError.code , value: "Tried to send command to non-existent Android socket, " + "maybe it's shutting down?" }); } }; ADB.prototype.sendShutdownCommand = function(cb) { setTimeout(_.bind(function() { if (!this.alreadyExited) { logger.warn("Android did not shut down fast enough, calling it gone"); this.alreadyExited = true; this.onExit(1); } }, this), 7000); this.sendCommand('shutdown', null, cb); }; ADB.prototype.outputStreamHandler = function(output) { this.checkForSocketReady(output); this.handleBootstrapOutput(output); }; ADB.prototype.handleBootstrapOutput = function(output) { // for now, assume all intentional logging takes place on one line // and that we don't get half-lines from the stream. // probably bad assumptions output = output.toString().trim(); var lines = output.split("\n"); var re = /^\[APPIUM-UIAUTO\] (.+)\[\/APPIUM-UIAUTO\]$/; var match; var me = this; _.each(lines, function(line) { line = line.trim(); if (line !== '') { match = re.exec(line); if (match) { logger.info("[ANDROID] " + match[1]); var alertRe = /Emitting system alert message/; if (alertRe.test(line)) { logger.info("Emiting alert message..."); me.webSocket.sockets.emit('alert', {message: line}); } } else { // The dump command will always disconnect UiAutomation. // Detect the crash then restart UiAutomation. if (line.indexOf("UiAutomationService not connected") !== -1) { me.restartBootstrap = true; } logger.info(("[ADB STDOUT] " + line).grey); } } }); }; ADB.prototype.errorStreamHandler = function(output) { var lines = output.split("\n"); _.each(lines, function(line) { logger.info(("[ADB STDERR] " + line).yellow); }); }; ADB.prototype.debug = function(msg) { if (this.debugMode) { logger.info("[ADB] " + msg); } }; ADB.prototype.isDeviceConnected = function(cb) { this.getConnectedDevices(function(err, devices) { if (err) { cb(err); } else { cb(null, devices.length > 0); } }); }; ADB.prototype.setDeviceId = function(deviceId) { this.curDeviceId = deviceId; this.adbCmd = this.adb + " -s " + deviceId; }; ADB.prototype.requireDeviceId = function() { if (!this.curDeviceId) { throw new Error("This method requires that a device ID is set. " + "Call getConnectedDevices or setDeviceId"); } }; ADB.prototype.requirePortForwarded = function() { if (!this.portForwarded) { throw new Error("This method requires the port be forwarded on the " + "device. Make sure to call forwardPort()!"); } }; ADB.prototype.requireApp = function() { if (!this.appPackage || !this.appActivity) { throw new Error("This method requires that appPackage and appActivity " + "be sent in with options"); } }; ADB.prototype.requireApk = function() { if (!this.apkPath) { throw new Error("This method requires that apkPath be sent in as option"); } }; ADB.prototype.waitForDevice = function(cb) { var doWait = _.bind(function(innerCb) { this.debug("Waiting for device " + this.curDeviceId + " to be ready " + "and to respond to shell commands (timeout = " + this.appDeviceReadyTimeout + ")"); var movedOn = false , cmd = this.adbCmd + " wait-for-device" , timeoutSecs = parseInt(this.appDeviceReadyTimeout, 10); setTimeout(_.bind(function() { if (!movedOn) { movedOn = true; innerCb("Device did not become ready in " + timeoutSecs + " secs; " + "are you sure it's powered on?"); } }, this), timeoutSecs * 1000); exec(cmd, _.bind(function(err) { if (!movedOn) { if (err) { logger.error("Error running wait-for-device"); movedOn = true; innerCb(err); } else { exec(this.adbCmd + " shell echo 'ready'", _.bind(function(err) { if (!movedOn) { movedOn = true; if (err) { logger.error("Error running shell echo: " + err); innerCb(err); } else { innerCb(null); } } }, this)); } } }, this)); }, this); doWait(_.bind(function(err) { if (err) { this.restartAdb(_.bind(function() { this.getConnectedDevices(function() { doWait(cb); }); }, this)); } else { cb(null); } }, this)); }; ADB.prototype.restartAdb = function(cb) { logger.info("Killing ADB server so it will come back online"); var cmd = this.adb + " kill-server"; exec(cmd, function(err) { if (err) { logger.error("Error killing ADB server, going to see if it's online " + "anyway"); } cb(); }); }; ADB.prototype.pushAppium = function(cb) { this.debug("Pushing appium bootstrap to device..."); var binPath = path.resolve(__dirname, "..", "build", "android_bootstrap", "AppiumBootstrap.jar"); fs.stat(binPath, _.bind(function(err) { if (err) { cb("Could not find AppiumBootstrap.jar; please run " + "'grunt buildAndroidBootstrap'"); } else { var remotePath = "/data/local/tmp"; var cmd = this.adbCmd + " push " + binPath + " " + remotePath; exec(cmd, _.bind(function(err) { if (err) { logger.error(err); cb(err); } else { cb(null); } }, this)); } }, this)); }; ADB.prototype.startApp = function(cb) { logger.info("Starting app"); this.requireDeviceId(); this.requireApp(); var activityString = this.appActivity; var hasNoPrefix = true; var rootPrefixes = ['com', 'net', 'org', 'io']; _.each(rootPrefixes, function(prefix) { if (activityString.indexOf(prefix + ".") !== -1) { hasNoPrefix = false; } }); if (hasNoPrefix) { activityString = this.appPackage + "." + activityString; } var cmd = this.adbCmd + " shell am start -n " + this.appPackage + "/" + activityString; this.debug("Starting app " + this.appPackage + "/" + activityString); exec(cmd, _.bind(function(err) { if(err) { logger.error(err); cb(err); } else { this.waitForActivity(cb); } }, this)); }; ADB.prototype.stopApp = function(cb) { logger.info("Killing app"); this.requireDeviceId(); this.requireApp(); var cmd = this.adbCmd + " shell am force-stop " + this.appPackage; exec(cmd, function(err) { if (err) { logger.error(err); return cb(err); } cb(); }); }; ADB.prototype.getFocusedPackageAndActivity = function(cb) { logger.info("Getting focused package and activity"); this.requireDeviceId(); var cmd = this.adbCmd + " shell dumpsys window windows" , searchRe = new RegExp(/mFocusedApp.+ ([a-zA-Z0-9\.]+)\/\.?([^\}]+)\}/); exec(cmd, _.bind(function(err, stdout) { if (err) { logger.error(err); cb(err); } else { var foundMatch = false; _.each(stdout.split("\n"), function(line) { var match = searchRe.exec(line); if (match) { foundMatch = match; } }); if (foundMatch) { cb(null, foundMatch[1], foundMatch[2]); } else { cb(new Error("Could not parse activity from dumpsys")); } } }, this)); }; ADB.prototype.waitForNotActivity = function(cb) { this.requireApp(); logger.info("Waiting for app's activity to not be focused"); var waitMs = 20000 , intMs = 750 , endAt = Date.now() + waitMs , targetActivity = this.appWaitActivity || this.appActivity; var getFocusedApp = _.bind(function() { this.getFocusedPackageAndActivity(_.bind(function(err, foundPackage, foundActivity) { if (foundPackage !== this.appPackage && foundActivity !== targetActivity) { cb(null); } else if (Date.now() < endAt) { if (err) logger.info(err); setTimeout(getFocusedApp, intMs); } else { var msg = "App never closed. appActivity: " + foundActivity + " != " + targetActivity; logger.error(msg); cb(new Error(msg)); } }, this)); }, this); getFocusedApp(); }; ADB.prototype.waitForActivity = function(cb) { this.requireApp(); logger.info("Waiting for app's activity to become focused"); var waitMs = 20000 , intMs = 750 , endAt = Date.now() + waitMs , targetActivity = this.appWaitActivity || this.appActivity; var getFocusedApp = _.bind(function() { this.getFocusedPackageAndActivity(_.bind(function(err, foundPackage, foundActivity) { if (foundPackage === this.appPackage && foundActivity === targetActivity) { cb(null); } else if (Date.now() < endAt) { if (err) logger.info(err); setTimeout(getFocusedApp, intMs); } else { var msg = "App never showed up as active. appActivity: " + foundActivity + " != " + targetActivity; logger.error(msg); cb(new Error(msg)); } }, this)); }, this); getFocusedApp(); }; ADB.prototype.uninstallApk = function(pkg, cb) { logger.info("Uninstalling " + pkg); var cmd = this.adbCmd + " uninstall " + pkg; exec(cmd, function(err, stdout) { if (err) { logger.error(err); cb(err); } else { stdout = stdout.trim(); if (stdout === "Success") { logger.debug("App was uninstalled"); } else { logger.debug("App was not uninstalled, maybe it wasn't on device?"); } cb(null); } }); }; ADB.prototype.installApk = function(apk, cb) { var cmd = this.adbCmd + ' install -r "' + apk + '"'; logger.info("Installing " + apk); exec(cmd,function(err, stdout) { if (err) { logger.error(err); cb(err); } else { // Useful for debugging. logger.debug(stdout); cb(null); } }); }; ADB.prototype.uninstallApp = function(cb) { var me = this; var next = function() { me.requireDeviceId(); me.requireApp(); me.debug("Uninstalling app " + me.appPackage); me.uninstallApk(me.appPackage, function(err) { if (me.fastReset) { var cleanPkg = me.appPackage + '.clean'; me.debug("Uninstalling app " + cleanPkg); me.uninstallApk(cleanPkg, function(err) { if (err) return cb(err); cb(null); }); } else { if (err) return cb(err); cb(null); } }); }; if (me.skipUninstall) { me.debug("Not uninstalling app since server started with --reset"); cb(); } else { next(); } }; ADB.prototype.runFastReset = function(cb) { // list instruments with: adb shell pm list instrumentation // targetPackage + '.clean' / clean.apk.Clear var me = this; var clearCmd = me.adbCmd + ' shell am instrument ' + me.appPackage + '.clean/clean.apk.Clean'; logger.debug("Running fast reset clean: " + clearCmd); exec(clearCmd, {}, function(err, stdout, stderr) { if (err) { logger.warn(stderr); cb(err); } else { cb(null); } }); }; ADB.prototype.checkAppInstallStatus = function(pkg, cb) { var installed = false , cleanInstalled = false; this.requireDeviceId(); logger.debug("Getting install/clean status for " + pkg); var listPkgCmd = this.adbCmd + " shell pm list packages -3 " + pkg; exec(listPkgCmd, function(err, stdout) { var apkInstalledRgx = new RegExp('^package:' + pkg.replace(/([^a-zA-Z])/g, "\\$1") + '$', 'm'); installed = apkInstalledRgx.test(stdout); var cleanInstalledRgx = new RegExp('^package:' + (pkg + '.clean').replace(/([^a-zA-Z])/g, "\\$1") + '$', 'm'); cleanInstalled = cleanInstalledRgx.test(stdout); cb(null, installed, cleanInstalled); }); }; ADB.prototype.installApp = function(cb) { var me = this , installApp = false , installClean = false; me.requireDeviceId(); if (this.apkPath === null) { logger.info("Not installing app since we launched with a package instead " + "of an app path"); return cb(null); } me.requireApk(); var determineInstallAndCleanStatus = function(cb) { logger.info("Determining app install/clean status"); me.checkAppInstallStatus(me.appPackage, function(err, installed, cleaned) { installApp = !installed; installClean = !cleaned; cb(); }); }; var doInstall = function(cb) { if (installApp) { me.debug("Installing app apk"); me.installApk(me.apkPath, cb); } else { cb(null); } }; var doClean = function(cb) { if (installClean && me.cleanApp) { me.debug("Installing clean apk"); me.installApk(me.cleanAPK, cb); } else { cb(null); } }; var doFastReset = function(cb) { // App is already installed so reset it. if (!installApp && me.fastReset) { me.runFastReset(cb); } else { cb(null); } }; async.series([ function(cb) { determineInstallAndCleanStatus(cb); }, function(cb) { doInstall(cb); }, function(cb) { doClean(cb); }, function(cb) { doFastReset(cb); } ], cb); }; ADB.prototype.back = function(cb) { this.requireDeviceId(); this.debug("Pressing the BACK button"); var cmd = this.adbCmd + " shell input keyevent 4"; exec(cmd, function() { cb(); }); }; ADB.prototype.goToHome = function(cb) { this.requireDeviceId(); this.debug("Pressing the HOME button"); var cmd = this.adbCmd + " shell input keyevent 3"; exec(cmd, function() { cb(); }); }; ADB.prototype.wakeUp = function(cb) { // requires an appium bootstrap connection loaded this.debug("Waking up device if it's not alive"); this.android.proxy(["wake", {}], cb); }; ADB.prototype.keyevent = function(keycode, cb) { this.requireDeviceId(); var code = parseInt(keycode, 10); // keycode must be an int. var cmd = this.adbCmd + ' shell input keyevent ' + code; this.debug("Sending keyevent " + code); exec(cmd, function() { cb(); }); }; ADB.prototype.unlockScreen = function(cb) { this.requireDeviceId(); this.debug("Attempting to unlock screen"); var cmd = this.adbCmd + " shell input keyevent 82"; exec(cmd, function() { cb(); }); }; ADB.prototype.sendTelnetCommand = function(command, cb) { logger.info("Sending telnet command to device: " + command); this.getEmulatorPort(function(err, port) { if (err) return cb(err); var conn = net.createConnection(port, 'localhost'); var connected = false; var readyRegex = /^OK$/m; var dataStream = ""; var res = null; var onReady = function() { logger.info("Socket connection to device ready"); conn.write(command + "\n"); }; conn.on('connect', function() { logger.info("Socket connection to device created"); }); conn.on('data', function(data) { data = data.toString('utf8'); if (!connected) { if (readyRegex.test(data)) { connected = true; onReady(); } } else { dataStream += data; if (readyRegex.test(data)) { res = dataStream.replace(readyRegex, "").trim(); logger.info("Telnet command got response: " + res); conn.write("quit\n"); } } }); conn.on('close', function() { if (res === null) { cb(new Error("Never got a response from command")); } else { cb(null, res); } }); }); }; module.exports = function(opts, android) { return new ADB(opts, android); };
resend last command for adb, not for android (fix #705)
android/adb.js
resend last command for adb, not for android (fix #705)
<ide><path>ndroid/adb.js <ide> this.android = android; <ide> this.cmdCb = null; <ide> this.binaries = {}; <add> this.resendLastCommand = function() {}; <ide> }; <ide> <ide> ADB.prototype.checkSdkBinaryPresent = function(binary, cb) { <ide> <ide> var me = this; <ide> this.proc.on('exit', _.bind(function(code) { <add> this.cmdCb = null; <ide> if (this.socketClient) { <ide> this.socketClient.end(); <ide> this.socketClient.destroy(); <ide> me.runBootstrap(function() { <ide> // Resend last command because the client is still waiting for the <ide> // response. <del> me.android.push(null, true); <add> me.resendLastCommand(); <ide> }, exitCb); <ide> return; <ide> } <ide> }; <ide> waitForCmdCbNull(); <ide> } else if (this.socketClient) { <add> this.resendLastCommand = _.bind(function() { <add> this.sendCommand(type, extra, cb); <add> }, this); <ide> if (typeof extra === "undefined" || extra === null) { <ide> extra = {}; <ide> }
JavaScript
mit
8d6f042b0e4b422cd03eae99125bd4b2b955cb92
0
bustardcelly/cucumberjs-examples
#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var map = require('map-stream'); var tmpl = require('lodash.template'); var watch = require('node-watch'); var child_process = require('child_process'); var mkdirp = require('mkdirp'); var rimraf = require('rimraf'); var browserify = require('browserify'); var http = require('http'); var tinylr = require('tiny-lr'); var connect = require('connect'); var open = require('open'); var S = require('string'); var tempdir = '.tmp'; var outdir = 'test'; var browserCukes; var livereloadPort = 35729; var connectPort = 8080; var JS_EXT = /^.*\.js/i; var options = ['-f', 'ui', '-o', outdir, '--tmpl', tempdir + '/testrunner.html']; var wrap = function(wrapperTemplate) { return map(function(file, cb) { var content = file.toString(); fs.readFile(path.resolve(wrapperTemplate), 'utf8', function(err, filedata) { cb(null, filedata.replace(/[^]<%= yield %>/i, content)); }); }); }; // [TASKS] // a. re-bundle the app. var bundleApplication = function(f, callback) { return function() { browserify(__dirname + '/script/app.js') .bundle({ standalone: 'app' }) .pipe(fs.createWriteStream(path.resolve(outdir + '/script/app.js'))) .on('close', function() { console.log('changed app.js...'); if(callback) { callback(); } }); }; }; // b. template testrunner with app partial. var templateTestRunner = function(callback) { fs.createReadStream(__dirname + '/template/app-main.us') .pipe(wrap(__dirname + '/template/testrunner-wrapper.us')) .pipe(fs.createWriteStream(path.resolve(tempdir + '/testrunner.html'))) .on('close', function() { if(callback) { callback(); } }); }; // c. rerun cucumberjs-browser tool. var cuke = function(f, callback) { return function() { var filename = S(path.basename(f, '.js').split('.').join('-')).camelize().s; templateTestRunner(function() { browserCukes = child_process.spawn('cucumberjs-browser', options) .on('exit', function() { console.log('changed ' + filename + '...'); rimraf(tempdir, function() { if(callback) { callback(); } }); }); }); }; }; // 1. Recursive mkdir /test/script if not exist. mkdirp.sync(outdir + '/script'); mkdirp.sync(tempdir); // 2. Create tiny-livereload server. var lr = tinylr(); lr.listen(livereloadPort, function() { console.log('livereload listening on ' + livereloadPort + '...'); }); // 3. Start server on localhost. var app = connect().use(connect.static(__dirname + '/test')); var server = http.createServer(app).listen(connectPort, function() { console.log('local server started on ' + connectPort + '...'); console.log('Note: Remember to start the livereload browser extension!'); console.log('http://feedback.livereload.com/knowledgebase/articles/86242-how-do-i-install-and-use-the-browser-extensions-'); cuke('./features/support/world', function() { bundleApplication('./script/app.js', function() { open('http://localhost:' + connectPort + '/cucumber-testrunner.html'); })(); })(); }); // 4. Watch source and generate bundles. watch(['./features', './script'], {recursive:true}, function(filename) { // Used to resolve when running operation(s) are complete. var resolver; var running = false; var resolveWatch = function(limit) { var count = 0; running = true; return function() { if(++count === limit) { count = 0; running = false; } else { running = true; } }; }; if(!running && filename.match(JS_EXT)) { var bundleAppInvoke = bundleApplication(filename, function() { lr.changed({ body: { files: ['script/app'] } }); resolver(); }); if(/^script?/i.test(filename)) { resolver = resolveWatch(1); bundleAppInvoke(); } else if(/^features?/i.test(filename)) { resolver = resolveWatch(2); cuke(filename, function() { lr.changed({ body: { files: [filename] } }); resolver(); bundleAppInvoke(); })(); } } });
cuke-browser-watcher.js
#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var map = require('map-stream'); var tmpl = require('lodash.template'); var watch = require('node-watch'); var child_process = require('child_process'); var mkdirp = require('mkdirp'); var rimraf = require('rimraf'); var browserify = require('browserify'); var http = require('http'); var tinylr = require('tiny-lr'); var connect = require('connect'); var open = require('open'); var S = require('string'); var tempdir = '.tmp'; var outdir = 'test'; var browserCukes; var livereloadPort = 35729; var connectPort = 8080; var JS_EXT = /^.*\.js/i; var options = ['-f', 'ui', '-o', outdir, '--tmpl', tempdir + '/testrunner.html']; var wrap = function(wrapperTemplate) { return map(function(file, cb) { var content = file.toString(); fs.readFile(path.resolve(wrapperTemplate), 'utf8', function(err, filedata) { cb(null, tmpl(filedata, {yield:content})); }); }); }; // [TASKS] // a. re-bundle the app. var bundleApplication = function(f, callback) { return function() { browserify(__dirname + '/script/app.js') .bundle({ standalone: 'app' }) .pipe(fs.createWriteStream(path.resolve(outdir + '/script/app.js'))) .on('close', function() { console.log('changed app.js...'); if(callback) { callback(); } }); }; }; // b. template testrunner with app partial. var templateTestRunner = function(callback) { fs.createReadStream(__dirname + '/template/app-main.us') .pipe(wrap(__dirname + '/template/testrunner-wrapper.us')) .pipe(fs.createWriteStream(path.resolve(tempdir + '/testrunner.html'))) .on('close', function() { if(callback) { callback(); } }); }; // c. rerun cucumberjs-browser tool. var cuke = function(f, callback) { return function() { var filename = S(path.basename(f, '.js').split('.').join('-')).camelize().s; // templateTestRunner(function() { browserCukes = child_process.spawn('cucumberjs-browser', options) .on('exit', function() { console.log('changed ' + filename + '...'); rimraf(tempdir, function() { if(callback) { callback(); } }); }); // }); }; }; // 1. Recursive mkdir /test/script if not exist. mkdirp.sync(outdir + '/script'); mkdirp.sync(tempdir); // 2. Create tiny-livereload server. var lr = tinylr(); lr.listen(livereloadPort, function() { console.log('livereload listening on ' + livereloadPort + '...'); }); // 3. Start server on localhost. var app = connect().use(connect.static(__dirname + '/test')); var server = http.createServer(app).listen(connectPort, function() { console.log('local server started on ' + connectPort + '...'); console.log('Note: Remember to start the livereload browser extension!'); console.log('http://feedback.livereload.com/knowledgebase/articles/86242-how-do-i-install-and-use-the-browser-extensions-'); cuke('./features/support/world', function() { bundleApplication('./script/app.js', function() { open('http://localhost:' + connectPort + '/cucumber-testrunner.html'); })(); })(); }); // 4. Watch source and generate bundles. watch(['./features', './script'], {recursive:true}, function(filename) { // Used to resolve when running operation(s) are complete. var resolver; var running = false; var resolveWatch = function(limit) { var count = 0; running = true; return function() { if(++count === limit) { count = 0; running = false; } else { running = true; } }; }; if(!running && filename.match(JS_EXT)) { var bundleAppInvoke = bundleApplication(filename, function() { lr.changed({ body: { files: ['script/app'] } }); resolver(); }); if(/^script?/i.test(filename)) { resolver = resolveWatch(1); bundleAppInvoke(); } else if(/^features?/i.test(filename)) { resolver = resolveWatch(2); cuke(filename, function() { lr.changed({ body: { files: [filename] } }); resolver(); bundleAppInvoke(); })(); } } });
update to allow wrapping templates from real app partial used in build.
cuke-browser-watcher.js
update to allow wrapping templates from real app partial used in build.
<ide><path>uke-browser-watcher.js <ide> return map(function(file, cb) { <ide> var content = file.toString(); <ide> fs.readFile(path.resolve(wrapperTemplate), 'utf8', function(err, filedata) { <del> cb(null, tmpl(filedata, {yield:content})); <add> cb(null, filedata.replace(/[^]<%= yield %>/i, content)); <ide> }); <ide> }); <ide> }; <ide> var cuke = function(f, callback) { <ide> return function() { <ide> var filename = S(path.basename(f, '.js').split('.').join('-')).camelize().s; <del> // templateTestRunner(function() { <add> templateTestRunner(function() { <ide> browserCukes = child_process.spawn('cucumberjs-browser', options) <ide> .on('exit', function() { <ide> console.log('changed ' + filename + '...'); <ide> } <ide> }); <ide> }); <del> // }); <add> }); <ide> }; <ide> }; <ide>
JavaScript
apache-2.0
38d6402ac5114cc55bc84277391c21c954eb9f2e
0
edlerd/scrabble,edlerd/scrabble,edlerd/scrabble
/** Copyright 2014-2018 David Edler 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. **/ var BOARD = null; // future pointer to dom element var BOARD_LETTERS = []; var TO_BE_PLAYED_BOARD_LETTER_INDEXES = []; var LETTERS_PLAYED_BY_KI_INDEXES = []; var IS_GAME_FINISHED; var LETTER_STASH; var POINTS_PER_LETTER; var LANGUAGE_CONFIG; const LANG_ENGLISH = 'english'; const LANG_GERMAN = 'german'; const ENGLISH_CONFIG_URL = 'config/english.jsonp'; const GERMAN_CONFIG_URL = 'config/german.jsonp'; loadLanguageConfig(); function getUrlParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } function getConfigUrl() { var lang = getUrlParameterByName('lang'); switch (lang) { case LANG_ENGLISH: return ENGLISH_CONFIG_URL; case LANG_GERMAN: default: return GERMAN_CONFIG_URL; } } function i18n(text) { var lang = getUrlParameterByName('lang') || LANG_GERMAN; if (TRANSLATION_MAP[text] && TRANSLATION_MAP[text][lang]) { return TRANSLATION_MAP[text][lang]; } return text; } function loadLanguageConfig() { var request = new XMLHttpRequest(); var configUrl = getConfigUrl(); request.open("GET", configUrl, true); request.onreadystatechange = function() { if (request.readyState === 4) { LANGUAGE_CONFIG = JSON.parse(request.responseText); LETTER_STASH = LANGUAGE_CONFIG.LETTER_STASH; POINTS_PER_LETTER = LANGUAGE_CONFIG.POINTS_PER_LETTER; loadDictionary(); } }; request.send(null); } var PLAYER_1_LETTERS = []; var PLAYER_1_POINTS = 0; var PLAYER_2_LETTERS = []; var PLAYER_2_POINTS = 0; var KI_INTELLIGENCE = 1; var KI_MAX_INTELLIGENCE = 0.2; var MAX_POINTS = 0; var MAX_RESULT = {}; var BOTH_PLAYERS_PASS_COUNT = 0; var DICTIONARY = []; function loadDictionary() { var request = new XMLHttpRequest(); request.open("GET", LANGUAGE_CONFIG.DICTIONARY_URL, true); request.onreadystatechange = function() { if (request.readyState === 4) { DICTIONARY = request.responseText.replace("OE","Ö").replace("UE",'Ü').replace('AE','Ä').toUpperCase(); startGame(); } }; request.send(null); } function showLetterInput(elem) { // get current field var targetPosition = elem.srcElement.id.substring(1,elem.srcElement.id.length).split("_"); var x = parseInt(targetPosition[0]) - 1; var y = parseInt(targetPosition[1]) - 1; // if there is already a active tile, remove it. if (elem.target.classList.contains('player_set_tile')) { var returnedIndex = x * 15 + y; var letter = BOARD_LETTERS[returnedIndex]; BOARD_LETTERS[x*15+y] = ""; TO_BE_PLAYED_BOARD_LETTER_INDEXES.splice(TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(returnedIndex), 1); PLAYER_1_LETTERS.push(letter); elem.target.classList.remove('player_set_tile'); printPlayersLetters(); printBoard(); updatePlayButton(); return; } // there is already a letter if (elem.target.innerHTML !== '') { return; } // mark target cell elem.srcElement.classList.add("input_here"); // show the input layer var input_container = document.getElementById("input_container"); input_container.style.padding= (elem.srcElement.offsetTop + 10) + " 0 0 " + (elem.srcElement.offsetLeft + 55); input_container.style.display= "block"; input_container.innerHTML = i18n('Welchen Buchstaben möchtest du hier setzen?') + "<br><div class='input_letter'>" + PLAYER_1_LETTERS.join("</div><div class='input_letter'>") + "</div>"; // append event listeners to input buttons var buttons=document.getElementsByClassName("input_letter"); for (var i=0; i<buttons.length; i++) { buttons[i].onclick = letterClicked; } } function letterClicked(elem) { // hide input layer document.getElementById("input_container").style.display="none"; // get target field var targetRect = document.getElementsByClassName("input_here")[0]; targetRect.classList.remove("input_here"); // get clicked letter var letter = elem.srcElement.innerHTML; // get target position var targetPosition = targetRect.id.substring(1,targetRect.id.length).split("_"); var x = parseInt(targetPosition[0]) - 1; var y = parseInt(targetPosition[1]) - 1; var letter_position = PLAYER_1_LETTERS.indexOf(letter); if (letter_position === -1) { alert("Den Buchstaben hast du nicht auf der Hand!"); return; } // set the letter BOARD_LETTERS[x*15 + y] = letter; PLAYER_1_LETTERS.splice(letter_position,1); TO_BE_PLAYED_BOARD_LETTER_INDEXES.push(x*15 + y); LETTERS_PLAYED_BY_KI_INDEXES = []; printPlayersLetters(); printBoard(); updatePlayButton(); } function updatePlayButton() { var points = checkValidStateAndCalculatePoints(); if (points) { document.getElementById("move").innerHTML = i18n("spielen") + " (" + i18n("für") + " " + points + " " + i18n("punkte") + ")"; document.getElementById("move").disabled = false; } else { document.getElementById("move").innerHTML = i18n("spielen"); document.getElementById("move").disabled = true; } } var SEED = Date.now(); seededRandom = function(max, min) { SEED = (SEED * 9301 + 49297) % 233280; var rnd = SEED / 233280; return Math.floor(min + rnd * (max - min)); } function drawTiles(player_var) { while (player_var.length < 7 && LETTER_STASH.length > 0) { var i = seededRandom(0, LETTER_STASH.length); player_var.push(LETTER_STASH[i]); LETTER_STASH.splice(i,1); } if (player_var.length === 0) { endGame(); } } function printPlayersLetters() { var out = ""; for (var i=0; i<PLAYER_1_LETTERS.length; i++) { out += '<div class="hand_letter">' + PLAYER_1_LETTERS[i] + '<div class="hand_letter_points">' + POINTS_PER_LETTER[PLAYER_1_LETTERS[i]] + '</div></div>'; } document.getElementById("player_1_letters").innerHTML = out; } function printBoard() { for (var i=0; i<15; i++) { for (var j=0; j<15; j++) { var field = BOARD.rows[i].cells[j]; field.innerHTML=BOARD_LETTERS[i * 15 + j]; if (BOARD_LETTERS[i * 15 + j] === '') { field.style.cursor = "pointer"; } else { field.style.cursor = "auto"; } if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(i * 15 + j) !== -1) { if (!field.classList.contains('player_set_tile')) { field.classList.add('player_set_tile'); } field.style.cursor = "no-drop"; } else { field.classList.remove('player_set_tile'); } if (LETTERS_PLAYED_BY_KI_INDEXES.indexOf(i * 15 + j) !== -1) { if (!field.classList.contains('ki_set_tile')) { field.classList.add('ki_set_tile'); } } else { field.classList.remove('ki_set_tile'); } } } // score document.getElementById("player_1_points").innerHTML = PLAYER_1_POINTS.toString(); document.getElementById("player_2_points").innerHTML = PLAYER_2_POINTS.toString(); // remaining tiles document.getElementById("letters_left").innerHTML = LETTER_STASH.length.toString(); } function takeBackCurrentTiles() { for (var i=0; i<TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { var pos = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; PLAYER_1_LETTERS.push(BOARD_LETTERS[pos]); BOARD_LETTERS[pos] = ''; } TO_BE_PLAYED_BOARD_LETTER_INDEXES.length=0; printPlayersLetters(); printBoard(); updatePlayButton(); } function isWordInDictionary(word) { if (Math.random() > KI_INTELLIGENCE) { return false; } return DICTIONARY.match("\n" + word + "\n") !== null; } function isWordStartInDictionary(word) { return DICTIONARY.match("\n" + word) !== null; } function findWordsAndPointsByActiveLetters() { var words = []; var pointSum = 0; for (var i=0; i < TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { var cur = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; /* * horizontal words */ // find leftest letter var h=cur; while (BOARD_LETTERS[h-1] !== "" && (h % 15) > 0) { h -=1; } //construct word var word_multiplier = 1; var letter_multiplier = 1; var word = BOARD_LETTERS[h]; if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(h) !== -1) { if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dl")) { letter_multiplier = 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tl")) { letter_multiplier = 3; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dw")) { word_multiplier *= 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tw")) { word_multiplier *= 3; } } var points = letter_multiplier * POINTS_PER_LETTER[BOARD_LETTERS[h]]; h++; while (BOARD_LETTERS[h] !== "" && (h % 15) !== 0) { letter_multiplier = 1; if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(h) !== -1) { if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dl")) { letter_multiplier = 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tl")) { letter_multiplier = 3; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dw")) { word_multiplier *= 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tw")) { word_multiplier *= 3; } } word = word.concat(BOARD_LETTERS[h]); points += letter_multiplier * POINTS_PER_LETTER[BOARD_LETTERS[h]]; h+=1; } if (word.length > 1 && words.indexOf(word) === -1) { words.push(word); pointSum += points * word_multiplier; } /* * vertical words */ // find highest letter var v=cur; while (BOARD_LETTERS[v-15] !== "" && v > 14) { v -= 15; } //construct word word = ''; points = 0; word_multiplier = 1; while (BOARD_LETTERS[v] !== "" && v < 225) { letter_multiplier = 1; if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(v) !== -1) { if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("dl")) { letter_multiplier = 2; } if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("tl")) { letter_multiplier = 3; } if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("dw")) { word_multiplier *= 2; } if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("tw")) { word_multiplier *= 3; } } word = word.concat(BOARD_LETTERS[v]); points += letter_multiplier * POINTS_PER_LETTER[BOARD_LETTERS[v]]; v += 15; } if (word.length > 1 && words.indexOf(word) === -1) { words.push(word); pointSum += points * word_multiplier; } } return [words, pointSum]; } /** * is the current position of new letters valid? * * one new word set and no letters on random points of the board * new word is connected to old letters * or opening of the game and center field used **/ function isLetterPositionValid() { var start = 225; var end = 0; for (i=0; i < TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { if (TO_BE_PLAYED_BOARD_LETTER_INDEXES[i] < start) { start = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; } if (TO_BE_PLAYED_BOARD_LETTER_INDEXES[i] > end) { end = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; } } var lineEnd = Math.abs(14 - (start % 15)) + start; var isHorizontal = lineEnd >= end; var increment = isHorizontal ? 1 : 15; for (i=start; i<end; i+=increment) { if (BOARD_LETTERS[i] === "") { return false; } } // do the tiles connect to letters on the board? for (var i=0; i < TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { var left = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]-1; if (left%15 < 14 && isFieldWithLetter(left)) { return true; } var right = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]+1; if (right%15 > 0 && isFieldWithLetter(right)) { return true; } var top = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]-15; if (top > 0 && isFieldWithLetter(top)) { return true; } var down = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]+15; if (down < 225 && isFieldWithLetter(down)) { return true; } } return wasBoardEmpty() && isCenterFieldUsed(); } function wasBoardEmpty() { for (var i = 0; i < 225; i++) { if (BOARD_LETTERS[i] !== '' && TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(i) === -1) { return false; } } return true; } function isCenterFieldUsed() { return TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(112) !== -1; } function isFieldWithLetter(index) { return TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(index) === -1 && BOARD_LETTERS[index] !== ''; } function checkValidStateAndCalculatePoints() { if (!isLetterPositionValid()) { return false; } var t = findWordsAndPointsByActiveLetters(); var words = t[0]; var points = t[1]; if (words.length < 1) { return false; } for (var i=0; i<words.length; i++) { if (!isWordInDictionary(words[i])) { return false; } } if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.length === 7) { points += 50; } return points; } function onFinishMoveClick() { PLAYER_1_POINTS += checkValidStateAndCalculatePoints(); BOTH_PLAYERS_PASS_COUNT = 0; TO_BE_PLAYED_BOARD_LETTER_INDEXES = []; drawTiles(PLAYER_1_LETTERS); printPlayersLetters(); printBoard(); startKiMove(); } function setKiMaxStrength(src) { KI_MAX_INTELLIGENCE = src.value; } function startKiMove() { if (IS_GAME_FINISHED) { return; } updatePlayButton(); document.getElementById("input_container").innerHTML='waiting for ki'; document.getElementById("input_container").style.display= "block"; setTimeout( function() { // ki_intelligence: the closer to 1 the more clever the ki KI_INTELLIGENCE = KI_MAX_INTELLIGENCE; computerMove(); if (!IS_GAME_FINISHED) { document.getElementById("input_container").style.display= "none"; KI_INTELLIGENCE = 1; } }, 100 ); return true; } function onLetterToSwapClicked(elem) { if (elem.srcElement.style.background !== 'yellow') { elem.srcElement.style.background = 'yellow'; elem.srcElement.classList.add('selected_to_switch'); } else { elem.srcElement.style.background = ''; elem.srcElement.classList.remove('selected_to_switch'); } } function onSelectSwapTilesClicked() { takeBackCurrentTiles(); if (LETTER_STASH.length === 0) { onPerformSwapTiles(); return; } var buttons=document.getElementsByClassName('hand_letter'); for (var i=0; i<buttons.length; i++) { buttons[i].onclick = onLetterToSwapClicked; } var button = document.getElementById('pass'); button.innerHTML = i18n('Wähle die Buchstaben aus, welche Du tauschen möchtest, dann klicke hier'); button.onclick = onPerformSwapTiles; } function onPerformSwapTiles() { var letterElements = document.getElementsByClassName('selected_to_switch'); var droppedLetters = []; for (var i = 0; i < letterElements.length; i++) { var letter = letterElements[i].innerHTML.charAt(0); var letter_position = PLAYER_1_LETTERS.indexOf(letter); PLAYER_1_LETTERS.splice(letter_position,1); droppedLetters.push(letter); } drawTiles(PLAYER_1_LETTERS); LETTER_STASH.concat(droppedLetters); printPlayersLetters(); var button = document.getElementById('pass'); button.innerHTML = i18n('Buchstaben tauschen (passen)'); button.onclick = onSelectSwapTilesClicked; incrementAndCheckPassCount(); startKiMove(); } Array.prototype.insert = function (index, item) { this.splice(index, 0, item); }; function incrementAndCheckPassCount() { BOTH_PLAYERS_PASS_COUNT += 1; if (BOTH_PLAYERS_PASS_COUNT >= 4) { endGame(); } } function endGame() { IS_GAME_FINISHED = true; for (var i = 0; i < PLAYER_1_LETTERS.length; i++) { var letter = PLAYER_1_LETTERS[i]; PLAYER_1_POINTS -= POINTS_PER_LETTER[letter]; } for (i = 0; i < PLAYER_2_LETTERS.length; i++) { letter = PLAYER_2_LETTERS[i]; PLAYER_2_POINTS -= POINTS_PER_LETTER[letter]; } document.getElementById("input_container").innerHTML='game over <a href="./" style="color:#ff9900">start new game</a>'; document.getElementById("input_container").style.display= "block"; document.getElementById("move").disabled = true; document.getElementById('pass').disabled = true; var winText = i18n('Du gewinnst.'); var looseText = i18n('Du verlierst.'); var resultText = PLAYER_1_POINTS > PLAYER_2_POINTS ? winText : looseText; alert( i18n('Das Spiel ist aus.') + '\n' + resultText + '\n' + i18n("DU") + ": " + PLAYER_1_POINTS + ' ' + i18n("punkte") + '\n' + i18n("KI") + ": " + PLAYER_2_POINTS + ' ' + i18n("punkte") ); } /** * pos: array of positions in game array to be filled with available letters * letters: array of available letters * result: object of indexes in game array and the letters to be set */ function tryFreePositions(pos,letters,result) { var tryPos = pos.pop(); TO_BE_PLAYED_BOARD_LETTER_INDEXES.push(tryPos); // try all letters available on current position for (var k = 0; k < letters.length; k++) { var tempLetter = letters.splice(k, 1)[0]; BOARD_LETTERS[tryPos] = tempLetter; result[tryPos] = tempLetter; // more positions to fill, recurse if (pos.length > 0) { // recurse only if we have laid valid starts of words yet var recurse = true; var words = findWordsAndPointsByActiveLetters()[0]; for (var i = 0; i < words.length; i++) { if (!isWordStartInDictionary(words[i])) { recurse = false; break; } } if (recurse) { tryFreePositions(pos, letters, result); } } else { var points = checkValidStateAndCalculatePoints(); // store points // store position and letters in result if (points > MAX_POINTS) { MAX_POINTS = points; //copy by value MAX_RESULT = JSON.parse(JSON.stringify(result)); } } BOARD_LETTERS[tryPos] = ''; result[tryPos] = ''; letters.insert(k, tempLetter); } pos.push(tryPos); TO_BE_PLAYED_BOARD_LETTER_INDEXES.splice(TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(tryPos), 1); } //fancy ki comes here function computerMove() { MAX_POINTS = 0; MAX_RESULT = {}; // try all rows for (var row=0; row<15; row++) { // try all starting positions within a row for (var rowStart=0; rowStart < 14; rowStart++) { // beginning field of our word startPos = row*15 + rowStart; // the field left of our current word is not empty if (rowStart !== 0 && BOARD_LETTERS[rowStart-1] !== '') { continue; } // try all possible word lengths for (var wordLength=2; wordLength < 15 - rowStart; wordLength++) { // end field of our word var endPos = row*15 + rowStart + wordLength; // the field right of our current word is not empty if (endPos !== 15 && BOARD_LETTERS[endPos+1] !== '') { continue; } var free_letter_positions=[]; var free_letter_count=0; var set_letter_count=0; for (i=startPos; i < endPos; i++) { if (BOARD_LETTERS[i] === '') { free_letter_positions[free_letter_count] = i; free_letter_count++; } else { set_letter_count++; } } // no letter set or // no free space to set a letter or // too many free spaces (should be up to number of tiles on player hand) if (set_letter_count === 0 || free_letter_count === 0 || free_letter_count > 3) { continue; } best_try = tryFreePositions(free_letter_positions, PLAYER_2_LETTERS, {}); } } } // try all columns var best_try; for (var column = 0; column < 15; column++) { // the starting position inside the column for (var columnStart = 0; columnStart < 14; columnStart++) { // beginning field of our word var startPos = column + 15 * columnStart; // the field on top of our current word is not empty if (startPos > 14 && BOARD_LETTERS[startPos - 15] !== '') { continue; } // try all possible word lengths for (wordLength = 2; wordLength < 15 - columnStart; wordLength++) { // end field of our word endPos = startPos + (15 * wordLength); // the field below our current word is not empty if (endPos + 15 < 225 && BOARD_LETTERS[endPos + 15] !== '') { continue; } free_letter_positions = []; free_letter_count = 0; set_letter_count = 0; for (i = startPos; i < endPos; i += 15) { if (BOARD_LETTERS[i] === '') { free_letter_positions[free_letter_count] = i; free_letter_count++; } else { set_letter_count++; } } // no letter set or // no free space to set a letter or // too many free spaces (should be up to number of tiles on player hand) if (set_letter_count === 0 || free_letter_count === 0 || free_letter_count > 3) { continue; } best_try = tryFreePositions(free_letter_positions, PLAYER_2_LETTERS, {}); } } } PLAYER_2_POINTS += MAX_POINTS; LETTERS_PLAYED_BY_KI_INDEXES = []; for (var i in MAX_RESULT) { LETTERS_PLAYED_BY_KI_INDEXES.push(parseInt(i)); var letter_pos = PLAYER_2_LETTERS.indexOf(MAX_RESULT[i]); PLAYER_2_LETTERS.splice(letter_pos,1); BOARD_LETTERS[i] = MAX_RESULT[i]; } TO_BE_PLAYED_BOARD_LETTER_INDEXES.length=0; drawTiles(PLAYER_2_LETTERS); if (MAX_POINTS === 0) { incrementAndCheckPassCount(); } else { BOTH_PLAYERS_PASS_COUNT = 0; } printBoard(); } function startGame() { BOARD = document.getElementById("board"); // event handlers on board for (var i=0; i<15; i++) { for (var j=0; j<15; j++) { BOARD_LETTERS[i * 15 + j]=''; BOARD.rows[i].cells[j].onclick=showLetterInput; } } document.getElementById("move").disabled = true; drawTiles(PLAYER_1_LETTERS); drawTiles(PLAYER_2_LETTERS); printPlayersLetters(); printBoard(); }
game.js
/** Copyright 2014-2018 David Edler 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. **/ var BOARD = null; // future pointer to dom element var BOARD_LETTERS = []; var TO_BE_PLAYED_BOARD_LETTER_INDEXES = []; var LETTERS_PLAYED_BY_KI_INDEXES = []; var IS_GAME_FINISHED; var LETTER_STASH; var POINTS_PER_LETTER; var LANGUAGE_CONFIG; const LANG_ENGLISH = 'english'; const LANG_GERMAN = 'german'; const ENGLISH_CONFIG_URL = 'config/english.jsonp'; const GERMAN_CONFIG_URL = 'config/german.jsonp'; loadLanguageConfig(); function getUrlParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); } function getConfigUrl() { var lang = getUrlParameterByName('lang'); switch (lang) { case LANG_ENGLISH: return ENGLISH_CONFIG_URL; case LANG_GERMAN: default: return GERMAN_CONFIG_URL; } } function i18n(text) { var lang = getUrlParameterByName('lang') || LANG_GERMAN; if (TRANSLATION_MAP[text] && TRANSLATION_MAP[text][lang]) { return TRANSLATION_MAP[text][lang]; } return text; } function loadLanguageConfig() { var request = new XMLHttpRequest(); var configUrl = getConfigUrl(); request.open("GET", configUrl, true); request.onreadystatechange = function() { if (request.readyState === 4) { LANGUAGE_CONFIG = JSON.parse(request.responseText); LETTER_STASH = LANGUAGE_CONFIG.LETTER_STASH; POINTS_PER_LETTER = LANGUAGE_CONFIG.POINTS_PER_LETTER; loadDictionary(); } }; request.send(null); } var PLAYER_1_LETTERS = []; var PLAYER_1_POINTS = 0; var PLAYER_2_LETTERS = []; var PLAYER_2_POINTS = 0; var KI_INTELLIGENCE = 1; var KI_MAX_INTELLIGENCE = 0.2; var MAX_POINTS = 0; var MAX_RESULT = {}; var BOTH_PLAYERS_PASS_COUNT = 0; var DICTIONARY = []; function loadDictionary() { var request = new XMLHttpRequest(); request.open("GET", LANGUAGE_CONFIG.DICTIONARY_URL, true); request.onreadystatechange = function() { if (request.readyState === 4) { DICTIONARY = request.responseText.replace("OE","Ö").replace("UE",'Ü').replace('AE','Ä').toUpperCase(); startGame(); } }; request.send(null); } function showLetterInput(elem) { // get current field var targetPosition = elem.srcElement.id.substring(1,elem.srcElement.id.length).split("_"); var x = parseInt(targetPosition[0]) - 1; var y = parseInt(targetPosition[1]) - 1; // if there is already a active tile, remove it. if (elem.target.classList.contains('player_set_tile')) { var returnedIndex = x * 15 + y; var letter = BOARD_LETTERS[returnedIndex]; BOARD_LETTERS[x*15+y] = ""; TO_BE_PLAYED_BOARD_LETTER_INDEXES.splice(TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(returnedIndex), 1); PLAYER_1_LETTERS.push(letter); elem.target.classList.remove('player_set_tile'); printPlayersLetters(); printBoard(); updatePlayButton(); return; } // there is already a letter if (elem.target.innerHTML !== '') { return; } // mark target cell elem.srcElement.classList.add("input_here"); // show the input layer var input_container = document.getElementById("input_container"); input_container.style.padding= (elem.srcElement.offsetTop + 10) + " 0 0 " + (elem.srcElement.offsetLeft + 55); input_container.style.display= "block"; input_container.innerHTML = i18n('Welchen Buchstaben möchtest du hier setzen?') + "<br><div class='input_letter'>" + PLAYER_1_LETTERS.join("</div><div class='input_letter'>") + "</div>"; // append event listeners to input buttons var buttons=document.getElementsByClassName("input_letter"); for (var i=0; i<buttons.length; i++) { buttons[i].onclick = letterClicked; } } function letterClicked(elem) { // hide input layer document.getElementById("input_container").style.display="none"; // get target field var targetRect = document.getElementsByClassName("input_here")[0]; targetRect.classList.remove("input_here"); // get clicked letter var letter = elem.srcElement.innerHTML; // get target position var targetPosition = targetRect.id.substring(1,targetRect.id.length).split("_"); var x = parseInt(targetPosition[0]) - 1; var y = parseInt(targetPosition[1]) - 1; var letter_position = PLAYER_1_LETTERS.indexOf(letter); if (letter_position === -1) { alert("Den Buchstaben hast du nicht auf der Hand!"); return; } // set the letter BOARD_LETTERS[x*15 + y] = letter; PLAYER_1_LETTERS.splice(letter_position,1); TO_BE_PLAYED_BOARD_LETTER_INDEXES.push(x*15 + y); LETTERS_PLAYED_BY_KI_INDEXES = []; printPlayersLetters(); printBoard(); updatePlayButton(); } function updatePlayButton() { var points = checkValidStateAndCalculatePoints(); if (points) { document.getElementById("move").innerHTML = i18n("spielen") + " (" + i18n("für") + " " + points + " " + i18n("punkte") + ")"; document.getElementById("move").disabled = false; } else { document.getElementById("move").innerHTML = i18n("spielen"); document.getElementById("move").disabled = true; } } function drawTiles(player_var) { while (player_var.length < 7 && LETTER_STASH.length > 0) { var i = Math.floor(Math.random() * LETTER_STASH.length); player_var.push(LETTER_STASH[i]); LETTER_STASH.splice(i,1); } if (player_var.length === 0) { endGame(); } } function printPlayersLetters() { var out = ""; for (var i=0; i<PLAYER_1_LETTERS.length; i++) { out += '<div class="hand_letter">' + PLAYER_1_LETTERS[i] + '<div class="hand_letter_points">' + POINTS_PER_LETTER[PLAYER_1_LETTERS[i]] + '</div></div>'; } document.getElementById("player_1_letters").innerHTML = out; } function printBoard() { for (var i=0; i<15; i++) { for (var j=0; j<15; j++) { var field = BOARD.rows[i].cells[j]; field.innerHTML=BOARD_LETTERS[i * 15 + j]; if (BOARD_LETTERS[i * 15 + j] === '') { field.style.cursor = "pointer"; } else { field.style.cursor = "auto"; } if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(i * 15 + j) !== -1) { if (!field.classList.contains('player_set_tile')) { field.classList.add('player_set_tile'); } field.style.cursor = "no-drop"; } else { field.classList.remove('player_set_tile'); } if (LETTERS_PLAYED_BY_KI_INDEXES.indexOf(i * 15 + j) !== -1) { if (!field.classList.contains('ki_set_tile')) { field.classList.add('ki_set_tile'); } } else { field.classList.remove('ki_set_tile'); } } } // score document.getElementById("player_1_points").innerHTML = PLAYER_1_POINTS.toString(); document.getElementById("player_2_points").innerHTML = PLAYER_2_POINTS.toString(); // remaining tiles document.getElementById("letters_left").innerHTML = LETTER_STASH.length.toString(); } function takeBackCurrentTiles() { for (var i=0; i<TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { var pos = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; PLAYER_1_LETTERS.push(BOARD_LETTERS[pos]); BOARD_LETTERS[pos] = ''; } TO_BE_PLAYED_BOARD_LETTER_INDEXES.length=0; printPlayersLetters(); printBoard(); updatePlayButton(); } function isWordInDictionary(word) { if (Math.random() > KI_INTELLIGENCE) { return false; } return DICTIONARY.match("\n" + word + "\n") !== null; } function isWordStartInDictionary(word) { return DICTIONARY.match("\n" + word) !== null; } function findWordsAndPointsByActiveLetters() { var words = []; var pointSum = 0; for (var i=0; i < TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { var cur = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; /* * horizontal words */ // find leftest letter var h=cur; while (BOARD_LETTERS[h-1] !== "" && (h % 15) > 0) { h -=1; } //construct word var word_multiplier = 1; var letter_multiplier = 1; var word = BOARD_LETTERS[h]; if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(h) !== -1) { if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dl")) { letter_multiplier = 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tl")) { letter_multiplier = 3; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dw")) { word_multiplier *= 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tw")) { word_multiplier *= 3; } } var points = letter_multiplier * POINTS_PER_LETTER[BOARD_LETTERS[h]]; h++; while (BOARD_LETTERS[h] !== "" && (h % 15) !== 0) { letter_multiplier = 1; if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(h) !== -1) { if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dl")) { letter_multiplier = 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tl")) { letter_multiplier = 3; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("dw")) { word_multiplier *= 2; } if (document.getElementById("s"+ Math.floor(h/15+1) + "_" + Math.floor(h%15+1)).classList.contains("tw")) { word_multiplier *= 3; } } word = word.concat(BOARD_LETTERS[h]); points += letter_multiplier * POINTS_PER_LETTER[BOARD_LETTERS[h]]; h+=1; } if (word.length > 1 && words.indexOf(word) === -1) { words.push(word); pointSum += points * word_multiplier; } /* * vertical words */ // find highest letter var v=cur; while (BOARD_LETTERS[v-15] !== "" && v > 14) { v -= 15; } //construct word word = ''; points = 0; word_multiplier = 1; while (BOARD_LETTERS[v] !== "" && v < 225) { letter_multiplier = 1; if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(v) !== -1) { if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("dl")) { letter_multiplier = 2; } if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("tl")) { letter_multiplier = 3; } if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("dw")) { word_multiplier *= 2; } if (document.getElementById("s"+ Math.floor(v/15+1) + "_" + Math.floor(v%15+1)).classList.contains("tw")) { word_multiplier *= 3; } } word = word.concat(BOARD_LETTERS[v]); points += letter_multiplier * POINTS_PER_LETTER[BOARD_LETTERS[v]]; v += 15; } if (word.length > 1 && words.indexOf(word) === -1) { words.push(word); pointSum += points * word_multiplier; } } return [words, pointSum]; } /** * is the current position of new letters valid? * * one new word set and no letters on random points of the board * new word is connected to old letters * or opening of the game and center field used **/ function isLetterPositionValid() { var start = 225; var end = 0; for (i=0; i < TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { if (TO_BE_PLAYED_BOARD_LETTER_INDEXES[i] < start) { start = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; } if (TO_BE_PLAYED_BOARD_LETTER_INDEXES[i] > end) { end = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]; } } var lineEnd = Math.abs(14 - (start % 15)) + start; var isHorizontal = lineEnd >= end; var increment = isHorizontal ? 1 : 15; for (i=start; i<end; i+=increment) { if (BOARD_LETTERS[i] === "") { return false; } } // do the tiles connect to letters on the board? for (var i=0; i < TO_BE_PLAYED_BOARD_LETTER_INDEXES.length; i++) { var left = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]-1; if (left%15 < 14 && isFieldWithLetter(left)) { return true; } var right = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]+1; if (right%15 > 0 && isFieldWithLetter(right)) { return true; } var top = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]-15; if (top > 0 && isFieldWithLetter(top)) { return true; } var down = TO_BE_PLAYED_BOARD_LETTER_INDEXES[i]+15; if (down < 225 && isFieldWithLetter(down)) { return true; } } return wasBoardEmpty() && isCenterFieldUsed(); } function wasBoardEmpty() { for (var i = 0; i < 225; i++) { if (BOARD_LETTERS[i] !== '' && TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(i) === -1) { return false; } } return true; } function isCenterFieldUsed() { return TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(112) !== -1; } function isFieldWithLetter(index) { return TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(index) === -1 && BOARD_LETTERS[index] !== ''; } function checkValidStateAndCalculatePoints() { if (!isLetterPositionValid()) { return false; } var t = findWordsAndPointsByActiveLetters(); var words = t[0]; var points = t[1]; if (words.length < 1) { return false; } for (var i=0; i<words.length; i++) { if (!isWordInDictionary(words[i])) { return false; } } if (TO_BE_PLAYED_BOARD_LETTER_INDEXES.length === 7) { points += 50; } return points; } function onFinishMoveClick() { PLAYER_1_POINTS += checkValidStateAndCalculatePoints(); BOTH_PLAYERS_PASS_COUNT = 0; TO_BE_PLAYED_BOARD_LETTER_INDEXES = []; drawTiles(PLAYER_1_LETTERS); printPlayersLetters(); printBoard(); startKiMove(); } function setKiMaxStrength(src) { KI_MAX_INTELLIGENCE = src.value; } function startKiMove() { if (IS_GAME_FINISHED) { return; } updatePlayButton(); document.getElementById("input_container").innerHTML='waiting for ki'; document.getElementById("input_container").style.display= "block"; setTimeout( function() { // ki_intelligence: the closer to 1 the more clever the ki KI_INTELLIGENCE = KI_MAX_INTELLIGENCE; computerMove(); if (!IS_GAME_FINISHED) { document.getElementById("input_container").style.display= "none"; KI_INTELLIGENCE = 1; } }, 100 ); return true; } function onLetterToSwapClicked(elem) { if (elem.srcElement.style.background !== 'yellow') { elem.srcElement.style.background = 'yellow'; elem.srcElement.classList.add('selected_to_switch'); } else { elem.srcElement.style.background = ''; elem.srcElement.classList.remove('selected_to_switch'); } } function onSelectSwapTilesClicked() { takeBackCurrentTiles(); if (LETTER_STASH.length === 0) { onPerformSwapTiles(); return; } var buttons=document.getElementsByClassName('hand_letter'); for (var i=0; i<buttons.length; i++) { buttons[i].onclick = onLetterToSwapClicked; } var button = document.getElementById('pass'); button.innerHTML = i18n('Wähle die Buchstaben aus, welche Du tauschen möchtest, dann klicke hier'); button.onclick = onPerformSwapTiles; } function onPerformSwapTiles() { var letterElements = document.getElementsByClassName('selected_to_switch'); var droppedLetters = []; for (var i = 0; i < letterElements.length; i++) { var letter = letterElements[i].innerHTML.charAt(0); var letter_position = PLAYER_1_LETTERS.indexOf(letter); PLAYER_1_LETTERS.splice(letter_position,1); droppedLetters.push(letter); } drawTiles(PLAYER_1_LETTERS); LETTER_STASH.concat(droppedLetters); printPlayersLetters(); var button = document.getElementById('pass'); button.innerHTML = i18n('Buchstaben tauschen (passen)'); button.onclick = onSelectSwapTilesClicked; incrementAndCheckPassCount(); startKiMove(); } Array.prototype.insert = function (index, item) { this.splice(index, 0, item); }; function incrementAndCheckPassCount() { BOTH_PLAYERS_PASS_COUNT += 1; if (BOTH_PLAYERS_PASS_COUNT >= 4) { endGame(); } } function endGame() { IS_GAME_FINISHED = true; for (var i = 0; i < PLAYER_1_LETTERS.length; i++) { var letter = PLAYER_1_LETTERS[i]; PLAYER_1_POINTS -= POINTS_PER_LETTER[letter]; } for (i = 0; i < PLAYER_2_LETTERS.length; i++) { letter = PLAYER_2_LETTERS[i]; PLAYER_2_POINTS -= POINTS_PER_LETTER[letter]; } document.getElementById("input_container").innerHTML='game over <a href="./" style="color:#ff9900">start new game</a>'; document.getElementById("input_container").style.display= "block"; document.getElementById("move").disabled = true; document.getElementById('pass').disabled = true; var winText = i18n('Du gewinnst.'); var looseText = i18n('Du verlierst.'); var resultText = PLAYER_1_POINTS > PLAYER_2_POINTS ? winText : looseText; alert( i18n('Das Spiel ist aus.') + '\n' + resultText + '\n' + i18n("DU") + ": " + PLAYER_1_POINTS + ' ' + i18n("punkte") + '\n' + i18n("KI") + ": " + PLAYER_2_POINTS + ' ' + i18n("punkte") ); } /** * pos: array of positions in game array to be filled with available letters * letters: array of available letters * result: object of indexes in game array and the letters to be set */ function tryFreePositions(pos,letters,result) { var tryPos = pos.pop(); TO_BE_PLAYED_BOARD_LETTER_INDEXES.push(tryPos); // try all letters available on current position for (var k = 0; k < letters.length; k++) { var tempLetter = letters.splice(k, 1)[0]; BOARD_LETTERS[tryPos] = tempLetter; result[tryPos] = tempLetter; // more positions to fill, recurse if (pos.length > 0) { // recurse only if we have laid valid starts of words yet var recurse = true; var words = findWordsAndPointsByActiveLetters()[0]; for (var i = 0; i < words.length; i++) { if (!isWordStartInDictionary(words[i])) { recurse = false; break; } } if (recurse) { tryFreePositions(pos, letters, result); } } else { var points = checkValidStateAndCalculatePoints(); // store points // store position and letters in result if (points > MAX_POINTS) { MAX_POINTS = points; //copy by value MAX_RESULT = JSON.parse(JSON.stringify(result)); } } BOARD_LETTERS[tryPos] = ''; result[tryPos] = ''; letters.insert(k, tempLetter); } pos.push(tryPos); TO_BE_PLAYED_BOARD_LETTER_INDEXES.splice(TO_BE_PLAYED_BOARD_LETTER_INDEXES.indexOf(tryPos), 1); } //fancy ki comes here function computerMove() { MAX_POINTS = 0; MAX_RESULT = {}; // try all rows for (var row=0; row<15; row++) { // try all starting positions within a row for (var rowStart=0; rowStart < 14; rowStart++) { // beginning field of our word startPos = row*15 + rowStart; // the field left of our current word is not empty if (rowStart !== 0 && BOARD_LETTERS[rowStart-1] !== '') { continue; } // try all possible word lengths for (var wordLength=2; wordLength < 15 - rowStart; wordLength++) { // end field of our word var endPos = row*15 + rowStart + wordLength; // the field right of our current word is not empty if (endPos !== 15 && BOARD_LETTERS[endPos+1] !== '') { continue; } var free_letter_positions=[]; var free_letter_count=0; var set_letter_count=0; for (i=startPos; i < endPos; i++) { if (BOARD_LETTERS[i] === '') { free_letter_positions[free_letter_count] = i; free_letter_count++; } else { set_letter_count++; } } // no letter set or // no free space to set a letter or // too many free spaces (should be up to number of tiles on player hand) if (set_letter_count === 0 || free_letter_count === 0 || free_letter_count > 3) { continue; } best_try = tryFreePositions(free_letter_positions, PLAYER_2_LETTERS, {}); } } } // try all columns var best_try; for (var column = 0; column < 15; column++) { // the starting position inside the column for (var columnStart = 0; columnStart < 14; columnStart++) { // beginning field of our word var startPos = column + 15 * columnStart; // the field on top of our current word is not empty if (startPos > 14 && BOARD_LETTERS[startPos - 15] !== '') { continue; } // try all possible word lengths for (wordLength = 2; wordLength < 15 - columnStart; wordLength++) { // end field of our word endPos = startPos + (15 * wordLength); // the field below our current word is not empty if (endPos + 15 < 225 && BOARD_LETTERS[endPos + 15] !== '') { continue; } free_letter_positions = []; free_letter_count = 0; set_letter_count = 0; for (i = startPos; i < endPos; i += 15) { if (BOARD_LETTERS[i] === '') { free_letter_positions[free_letter_count] = i; free_letter_count++; } else { set_letter_count++; } } // no letter set or // no free space to set a letter or // too many free spaces (should be up to number of tiles on player hand) if (set_letter_count === 0 || free_letter_count === 0 || free_letter_count > 3) { continue; } best_try = tryFreePositions(free_letter_positions, PLAYER_2_LETTERS, {}); } } } PLAYER_2_POINTS += MAX_POINTS; LETTERS_PLAYED_BY_KI_INDEXES = []; for (var i in MAX_RESULT) { LETTERS_PLAYED_BY_KI_INDEXES.push(parseInt(i)); var letter_pos = PLAYER_2_LETTERS.indexOf(MAX_RESULT[i]); PLAYER_2_LETTERS.splice(letter_pos,1); BOARD_LETTERS[i] = MAX_RESULT[i]; } TO_BE_PLAYED_BOARD_LETTER_INDEXES.length=0; drawTiles(PLAYER_2_LETTERS); if (MAX_POINTS === 0) { incrementAndCheckPassCount(); } else { BOTH_PLAYERS_PASS_COUNT = 0; } printBoard(); } function startGame() { BOARD = document.getElementById("board"); // event handlers on board for (var i=0; i<15; i++) { for (var j=0; j<15; j++) { BOARD_LETTERS[i * 15 + j]=''; BOARD.rows[i].cells[j].onclick=showLetterInput; } } document.getElementById("move").disabled = true; drawTiles(PLAYER_1_LETTERS); drawTiles(PLAYER_2_LETTERS); printPlayersLetters(); printBoard(); }
use custom random number generator
game.js
use custom random number generator
<ide><path>ame.js <ide> } <ide> } <ide> <add>var SEED = Date.now(); <add>seededRandom = function(max, min) { <add> SEED = (SEED * 9301 + 49297) % 233280; <add> var rnd = SEED / 233280; <add> <add> return Math.floor(min + rnd * (max - min)); <add>} <add> <ide> function drawTiles(player_var) { <ide> while (player_var.length < 7 && LETTER_STASH.length > 0) { <del> var i = Math.floor(Math.random() * LETTER_STASH.length); <add> var i = seededRandom(0, LETTER_STASH.length); <ide> player_var.push(LETTER_STASH[i]); <ide> LETTER_STASH.splice(i,1); <ide> }
Java
apache-2.0
2cc645987cd95a63fa0c9e8a74654d845c3b4ba9
0
vector-im/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android
/* * Copyright 2017 Vector Creations Ltd * * 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 im.vector.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.User; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import im.vector.Matrix; import im.vector.R; import im.vector.util.VectorUtils; public class ContactAdapter extends AbsListAdapter<ParticipantAdapterItem, ContactAdapter.ContactViewHolder> { private final Context mContext; private final MXSession mSession; private final Comparator<ParticipantAdapterItem> mComparator; /* * ********************************************************************************************* * Constructor * ********************************************************************************************* */ public ContactAdapter(final Context context, final Comparator<ParticipantAdapterItem> comparator, final OnSelectItemListener<ParticipantAdapterItem> listener) { super(R.layout.adapter_item_contact_view, listener); mContext = context; mSession = Matrix.getInstance(context).getDefaultSession(); mComparator = comparator; } /* * ********************************************************************************************* * Public methods * ********************************************************************************************* */ @Override public void setItems(final List<ParticipantAdapterItem> items, final Filter.FilterListener listener) { Collections.sort(items, mComparator); super.setItems(items, listener); } /** * Update the adapter item corresponding to the given user id * * @param user */ public void updateItemWithUser(final User user) { for (int i = 0; i < mItems.size(); i++) { ParticipantAdapterItem item = mItems.get(i); if (TextUtils.equals(user.user_id, item.mUserId)) { notifyItemChanged(i); } } } /* * ********************************************************************************************* * Abstract methods implementation * ********************************************************************************************* */ @Override protected ContactViewHolder createViewHolder(View itemView) { return new ContactViewHolder(itemView); } @Override protected void populateViewHolder(ContactViewHolder viewHolder, ParticipantAdapterItem item) { viewHolder.populateViews(item); } @Override protected List<ParticipantAdapterItem> getFilterItems(List<ParticipantAdapterItem> items, String pattern) { List<ParticipantAdapterItem> filteredContacts = new ArrayList<>(); final String formattedPattern = pattern != null ? pattern.toLowerCase().trim().toLowerCase() : ""; for (final ParticipantAdapterItem item : items) { if (item.startsWith(formattedPattern)) { filteredContacts.add(item); } } return filteredContacts; } /* * ********************************************************************************************* * View holder * ********************************************************************************************* */ class ContactViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.contact_avatar) ImageView vContactAvatar; @BindView(R.id.contact_badge) ImageView vContactBadge; @BindView(R.id.contact_name) TextView vContactName; @BindView(R.id.contact_desc) TextView vContactDesc; private ContactViewHolder(final View itemView) { super(itemView); ButterKnife.bind(this, itemView); } private void populateViews(final ParticipantAdapterItem participant) { participant.displayAvatar(mSession, vContactAvatar); vContactName.setText(participant.getUniqueDisplayName(null)); /* * Get the description to be displayed below the name * For local contact, it is the medium (email, phone number) * For other contacts, it is the presence */ if (participant.mContact != null) { boolean isMatrixUserId = MXSession.PATTERN_CONTAIN_MATRIX_USER_IDENTIFIER.matcher(participant.mUserId).matches(); vContactBadge.setVisibility(isMatrixUserId ? View.VISIBLE : View.GONE); if (participant.mContact.getEmails().size() > 0) { vContactDesc.setText(participant.mContact.getEmails().get(0)); } else { vContactDesc.setText(participant.mContact.getPhonenumbers().get(0).mRawPhoneNumber); } } else { loadContactPresence(vContactDesc, participant); vContactBadge.setVisibility(View.GONE); } } /** * Get the presence for the given contact * * @param textView * @param item */ private void loadContactPresence(final TextView textView, final ParticipantAdapterItem item) { User user = null; MXSession matchedSession = null; // retrieve the linked user ArrayList<MXSession> sessions = Matrix.getMXSessions(mContext); for (MXSession session : sessions) { if (null == user) { matchedSession = session; user = session.getDataHandler().getUser(item.mUserId); } } if (null != user) { final MXSession finalMatchedSession = matchedSession; final String presence = VectorUtils.getUserOnlineStatus(mContext, matchedSession, item.mUserId, new SimpleApiCallback<Void>() { @Override public void onSuccess(Void info) { if (textView != null) { textView.setText(VectorUtils.getUserOnlineStatus(mContext, finalMatchedSession, item.mUserId, null)); setItems(mItems, null); } } }); textView.setText(presence); } } } }
vector/src/main/java/im/vector/adapters/ContactAdapter.java
/* * Copyright 2017 Vector Creations Ltd * * 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 im.vector.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.User; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import im.vector.Matrix; import im.vector.R; import im.vector.util.VectorUtils; public class ContactAdapter extends AbsListAdapter<ParticipantAdapterItem, ContactAdapter.ContactViewHolder> { private final Context mContext; private final MXSession mSession; private final Comparator<ParticipantAdapterItem> mComparator; /* * ********************************************************************************************* * Constructor * ********************************************************************************************* */ public ContactAdapter(final Context context, final Comparator<ParticipantAdapterItem> comparator, final OnSelectItemListener<ParticipantAdapterItem> listener) { super(R.layout.adapter_item_contact_view, listener); mContext = context; mSession = Matrix.getInstance(context).getDefaultSession(); mComparator = comparator; } /* * ********************************************************************************************* * Public methods * ********************************************************************************************* */ @Override public void setItems(final List<ParticipantAdapterItem> items, final Filter.FilterListener listener) { Collections.sort(items, mComparator); super.setItems(items, listener); } /** * Update the adapter item corresponding to the given user id * * @param user */ public void updateItemWithUser(final User user) { for (int i = 0; i < mItems.size(); i++) { ParticipantAdapterItem item = mItems.get(i); if (TextUtils.equals(user.user_id, item.mUserId)) { notifyItemChanged(i); } } } /* * ********************************************************************************************* * Abstract methods implementation * ********************************************************************************************* */ @Override protected ContactViewHolder createViewHolder(View itemView) { return new ContactViewHolder(itemView); } @Override protected void populateViewHolder(ContactViewHolder viewHolder, ParticipantAdapterItem item) { viewHolder.populateViews(item); } @Override protected List<ParticipantAdapterItem> getFilterItems(List<ParticipantAdapterItem> items, String pattern) { List<ParticipantAdapterItem> filteredContacts = new ArrayList<>(); final String formattedPattern = pattern != null ? pattern.toLowerCase().trim().toLowerCase() : ""; for (final ParticipantAdapterItem item : items) { if (item.startsWith(formattedPattern)) { filteredContacts.add(item); } } return filteredContacts; } /* * ********************************************************************************************* * View holder * ********************************************************************************************* */ class ContactViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.contact_avatar) ImageView vContactAvatar; @BindView(R.id.contact_badge) ImageView vContactBadge; @BindView(R.id.contact_name) TextView vContactName; @BindView(R.id.contact_desc) TextView vContactDesc; private ContactViewHolder(final View itemView) { super(itemView); ButterKnife.bind(this, itemView); } private void populateViews(final ParticipantAdapterItem participant) { participant.displayAvatar(mSession, vContactAvatar); vContactName.setText(participant.getUniqueDisplayName(null)); /* * Get the description to be displayed below the name * For local contact, it is the medium (email, phone number) * For other contacts, it is the presence */ if (participant.mContact != null) { boolean isMatrixUserId = MXSession.PATTERN_CONTAIN_MATRIX_USER_IDENTIFIER.matcher(participant.mUserId).matches(); vContactBadge.setVisibility(isMatrixUserId ? View.VISIBLE : View.GONE); if (participant.mContact.getEmails().size() > 0) { vContactDesc.setText(participant.mContact.getEmails().get(0)); } else { vContactDesc.setText(participant.mContact.getPhonenumbers().get(0).mRawPhoneNumber); } } else { loadContactPresence(vContactDesc, participant); vContactBadge.setVisibility(View.GONE); } } /** * Get the presence for the given contact * * @param textView * @param item */ private void loadContactPresence(final TextView textView, final ParticipantAdapterItem item) { User user = null; MXSession matchedSession = null; // retrieve the linked user ArrayList<MXSession> sessions = Matrix.getMXSessions(mContext); for (MXSession session : sessions) { if (null == user) { matchedSession = session; user = session.getDataHandler().getUser(item.mUserId); } } if (null != user) { final MXSession finalMatchedSession = matchedSession; final String presence = VectorUtils.getUserOnlineStatus(mContext, matchedSession, item.mUserId, new SimpleApiCallback<Void>() { @Override public void onSuccess(Void info) { if (textView != null) { textView.setText(VectorUtils.getUserOnlineStatus(mContext, finalMatchedSession, item.mUserId, null)); // TODO // Collections.sort(mItems, mComparator); // setItems(mItems, null); // notifyDataSetChanged(); } } }); textView.setText(presence); } } } }
Update contact adapter
vector/src/main/java/im/vector/adapters/ContactAdapter.java
Update contact adapter
<ide><path>ector/src/main/java/im/vector/adapters/ContactAdapter.java <ide> public void onSuccess(Void info) { <ide> if (textView != null) { <ide> textView.setText(VectorUtils.getUserOnlineStatus(mContext, finalMatchedSession, item.mUserId, null)); <del> // TODO <del>// Collections.sort(mItems, mComparator); <del>// setItems(mItems, null); <del>// notifyDataSetChanged(); <add> setItems(mItems, null); <ide> } <ide> } <ide> });
Java
apache-2.0
54e39ea3d1654b3ab4219fc69bc44d4125898f72
0
mksmbrtsh/TrackJoystickView
package maximsblog.blogspot.com.trackjoystickview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class TrackJoystickView extends View implements Runnable { // Constants public final static long DEFAULT_LOOP_INTERVAL = 100; // 100 ms // Variables private OnTrackJoystickViewMoveListener onTrackJoystickViewMoveListener; // Listener private Thread thread = new Thread(this); private long loopInterval = DEFAULT_LOOP_INTERVAL; private int xPosition1 = 0; // Touch x1 track position private int xPosition2 = 0; // Touch x2 track position private int yPosition1 = 0; // Touch y1 track position private int yPosition2 = 0; // Touch y2 track position private double centerX1 = 0; // Center view x1 position private double centerY1 = 0; // Center view y1 position private double centerX2 = 0; // Center view x2 position private double centerY2 = 0; // Center view y2 position private Paint mButton; private Paint mLine; private int joystickRadius; private int buttonRadius; private int leftTrackTouch; private int rightTrackTouch; public TrackJoystickView(Context context) { super(context); } public TrackJoystickView(Context context, AttributeSet attrs) { super(context, attrs); initJoystickView(); } public TrackJoystickView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); initJoystickView(); } protected void initJoystickView() { mLine = new Paint(); mLine.setStrokeWidth(10); mLine.setColor(Color.DKGRAY); mButton = new Paint(Paint.ANTI_ALIAS_FLAG); mButton.setColor(Color.DKGRAY); mButton.setStyle(Paint.Style.FILL); } @Override protected void onFinishInflate() { } @Override protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) { super.onSizeChanged(xNew, yNew, xOld, yOld); buttonRadius = (int) (yNew / 2 * 0.25); joystickRadius = yNew - 2 * buttonRadius; // (int) (yNew / 2 * 0.75); // before measure, get the center of view xPosition1 = xNew - 2 * buttonRadius; xPosition2 = xNew * buttonRadius; yPosition1 = (int) yNew / 2; yPosition2 = (int) yNew / 2; centerX1 = getWidth() - 1 * buttonRadius; centerY1 = (getHeight()) / 2; centerX2 = 1 * buttonRadius; centerY2 = (getHeight()) / 2; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // setting the measured values to resize the view to a certain width and // height int d = Math.min(measure(widthMeasureSpec), measure(heightMeasureSpec)); setMeasuredDimension(d, d); } private int measure(int measureSpec) { int result = 0; // Decode the measurement specifications. int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.UNSPECIFIED) { // Return a default size of 200 if no bounds are specified. result = 200; } else { // As you want to fill the available space // always return the full available bounds. result = specSize; } return result; } @Override protected void onDraw(Canvas canvas) { Paint p = new Paint(); p.setColor(Color.CYAN); canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), p); // buttons canvas.drawCircle((float) centerX1, yPosition1, buttonRadius, mButton); canvas.drawCircle((float) centerX2, yPosition2, buttonRadius, mButton); // vertical lines canvas.drawLine((float) centerX1, (float) centerY1 + joystickRadius / 2, (float) centerX1, (float) (centerY1 - joystickRadius / 2), mLine); canvas.drawLine((float) centerX2, (float) centerY2 + joystickRadius / 2, (float) centerX2, (float) (centerY2 - joystickRadius / 2), mLine); // main horisontal lines // neuntral canvas.drawLine((float) (centerX1 - buttonRadius * 0.75), (float) centerY1, (float) (centerX1 + buttonRadius * 0.75), (float) centerY1, mLine); canvas.drawLine((float) (centerX2 - buttonRadius * 0.75), (float) centerY2, (float) (centerX2 + buttonRadius * 0.75), (float) centerY2, mLine); // low canvas.drawLine((float) (centerX1 - buttonRadius * 0.6), (float) centerY1 + joystickRadius / 2, (float) (centerX1 + buttonRadius * 0.6), (float) centerY1 + joystickRadius / 2, mLine); canvas.drawLine((float) (centerX2 - buttonRadius * 0.6), (float) centerY2 + joystickRadius / 2, (float) (centerX2 + buttonRadius * 0.6), (float) centerY2 + joystickRadius / 2, mLine); // high canvas.drawLine((float) (centerX1 - buttonRadius * 0.6), (float) centerY1 - joystickRadius / 2, (float) (centerX1 + buttonRadius * 0.6), (float) centerY1 - joystickRadius / 2, mLine); canvas.drawLine((float) (centerX2 - buttonRadius * 0.6), (float) centerY2 - joystickRadius / 2, (float) (centerX2 + buttonRadius * 0.6), (float) centerY2 - joystickRadius / 2, mLine); // second horisontal lines canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 4), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 4), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 4), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 4), mLine); canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 4), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 4), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 4), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 4), mLine); // canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 - 3 * (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 - 3 * (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 - 3 * (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 - 3 * (joystickRadius) / 8), mLine); // canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 + 3 * (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 + 3 * (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 + 3 * (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 + 3 * (joystickRadius) / 8), mLine); } @Override public boolean onTouchEvent(MotionEvent event) { // int actionMask = event.getActionMasked(); switch (actionMask) { case MotionEvent.ACTION_DOWN: { // first down int i1 = event.getActionIndex(); int y = (int) event.getY(i1); int x = (int) event.getX(i1); double abs1 = Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1)); double abs2 = Math.sqrt((x - centerX2) * (x - centerX2) + (y - centerY2) * (y - centerY2)); if (abs1 < abs2) { yPosition1 = y; leftTrackTouch = event.getPointerId(i1); if (abs1 > joystickRadius / 2) { yPosition1 = (int) ((yPosition1 - centerY1) * joystickRadius / 2 / abs1 + centerY1); } } else { yPosition2 = y; rightTrackTouch = event.getPointerId(i1); if (abs2 > joystickRadius / 2) { yPosition2 = (int) ((yPosition2 - centerY2) * joystickRadius / 2 / abs2 + centerY2); } } invalidate(); if (thread != null && thread.isAlive()) { thread.interrupt(); } thread = new Thread(this); thread.start(); } break; case MotionEvent.ACTION_POINTER_DOWN: { // next downs for (int i1 = 0; i1 < event.getPointerCount(); i1++) { // int i1 = event.getActionIndex(); int y = (int) event.getY(i1); int x = (int) event.getX(i1); if (leftTrackTouch == -1 && rightTrackTouch != event.getPointerId(i1)) { leftTrackTouch = event.getPointerId(i1); } else if (rightTrackTouch == -1 && leftTrackTouch != event.getPointerId(i1)) { rightTrackTouch = event.getPointerId(i1); } if (leftTrackTouch == event.getPointerId(i1)) { double abs1 = Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1)); yPosition1 = y; if (abs1 > joystickRadius / 2) { yPosition1 = (int) ((yPosition1 - centerY1) * joystickRadius / 2 / abs1 + centerY1); } } else if (rightTrackTouch == event.getPointerId(i1)) { double abs2 = Math.sqrt((x - centerX2) * (x - centerX2) + (y - centerY2) * (y - centerY2)); yPosition2 = y; if (abs2 > joystickRadius / 2) { yPosition2 = (int) ((yPosition2 - centerY2) * joystickRadius / 2 / abs2 + centerY2); } } } invalidate(); } break; case MotionEvent.ACTION_UP: { // last up yPosition1 = (int) centerY1; yPosition2 = (int) centerY2; rightTrackTouch = -1; leftTrackTouch = -1; invalidate(); thread.interrupt(); onTrackJoystickViewMoveListener.onValueChanged(getPower2(), getPower1()); } break; case MotionEvent.ACTION_POINTER_UP: { // next up //for (int i1 = 0; i1 < event.getPointerCount(); i1++) { int i = event.getPointerId(event.getActionIndex());// i1; if (leftTrackTouch == event.getPointerId(i)) { yPosition1 = (int) centerY1; leftTrackTouch = -1; } else if (rightTrackTouch == event.getPointerId(i)) { yPosition2 = (int) centerY2; rightTrackTouch = -1; } //} invalidate(); } break; case MotionEvent.ACTION_MOVE: { // moving for (int i1 = 0; i1 < event.getPointerCount(); i1++) { int y = (int) event.getY(i1); int x = (int) event.getX(i1); if (leftTrackTouch == event.getPointerId(i1)) { double abs1 = Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1)); yPosition1 = y; if (abs1 > joystickRadius / 2) { yPosition1 = (int) ((yPosition1 - centerY1) * joystickRadius / abs1 / 2 + centerY1); } } else if (rightTrackTouch == event.getPointerId(i1)) { double abs2 = Math.sqrt((x - centerX2) * (x - centerX2) + (y - centerY2) * (y - centerY2)); yPosition2 = y; if (abs2 > joystickRadius / 2) { yPosition2 = (int) ((yPosition2 - centerY2) * joystickRadius / abs2 / 2 + centerY2); } } } invalidate(); } break; } return true; } private int getPower1() { int y = yPosition1 - buttonRadius; return (int) Math.round(100.0 - y * 200.0 / (getHeight() - 2.0 * buttonRadius)); } private int getPower2() { int y = yPosition2 - buttonRadius; return (int) Math.round(100.0 - y * 200.0 / (getHeight() - 2.0 * buttonRadius)); } public void setOnTrackJoystickViewMoveListener( OnTrackJoystickViewMoveListener listener, long repeatInterval) { this.onTrackJoystickViewMoveListener = listener; this.loopInterval = repeatInterval; } public static interface OnTrackJoystickViewMoveListener { public void onValueChanged(int y1, int y2); } @Override public void run() { while (!Thread.interrupted()) { post(new Runnable() { public void run() { onTrackJoystickViewMoveListener.onValueChanged(getPower2(), getPower1()); } }); try { Thread.sleep(loopInterval); } catch (InterruptedException e) { break; } } } }
src/maximsblog/blogspot/com/trackjoystickview/TrackJoystickView.java
package maximsblog.blogspot.com.trackjoystickview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class TrackJoystickView extends View implements Runnable { // Constants public final static long DEFAULT_LOOP_INTERVAL = 100; // 100 ms // Variables private OnTrackJoystickViewMoveListener onTrackJoystickViewMoveListener; // Listener private Thread thread = new Thread(this); private long loopInterval = DEFAULT_LOOP_INTERVAL; private int xPosition1 = 0; // Touch x1 track position private int xPosition2 = 0; // Touch x2 track position private int yPosition1 = 0; // Touch y1 track position private int yPosition2 = 0; // Touch y2 track position private double centerX1 = 0; // Center view x1 position private double centerY1 = 0; // Center view y1 position private double centerX2 = 0; // Center view x2 position private double centerY2 = 0; // Center view y2 position private Paint mButton; private Paint mLine; private int joystickRadius; private int buttonRadius; private int leftTrackTouch; private int rightTrackTouch; public TrackJoystickView(Context context) { super(context); } public TrackJoystickView(Context context, AttributeSet attrs) { super(context, attrs); initJoystickView(); } public TrackJoystickView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); initJoystickView(); } protected void initJoystickView() { mLine = new Paint(); mLine.setStrokeWidth(10); mLine.setColor(Color.DKGRAY); mButton = new Paint(Paint.ANTI_ALIAS_FLAG); mButton.setColor(Color.DKGRAY); mButton.setStyle(Paint.Style.FILL); } @Override protected void onFinishInflate() { } @Override protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) { super.onSizeChanged(xNew, yNew, xOld, yOld); buttonRadius = (int) (yNew / 2 * 0.25); joystickRadius = yNew - 2 * buttonRadius; // (int) (yNew / 2 * 0.75); // before measure, get the center of view xPosition1 = xNew - 2 * buttonRadius; xPosition2 = xNew * buttonRadius; yPosition1 = (int) yNew / 2; yPosition2 = (int) yNew / 2; centerX1 = getWidth() - 1 * buttonRadius; centerY1 = (getHeight()) / 2; centerX2 = 1 * buttonRadius; centerY2 = (getHeight()) / 2; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // setting the measured values to resize the view to a certain width and // height int d = Math.min(measure(widthMeasureSpec), measure(heightMeasureSpec)); setMeasuredDimension(d, d); } private int measure(int measureSpec) { int result = 0; // Decode the measurement specifications. int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.UNSPECIFIED) { // Return a default size of 200 if no bounds are specified. result = 200; } else { // As you want to fill the available space // always return the full available bounds. result = specSize; } return result; } @Override protected void onDraw(Canvas canvas) { Paint p = new Paint(); p.setColor(Color.CYAN); canvas.drawRect(new Rect(0, 0, getWidth(), getHeight()), p); // buttons canvas.drawCircle((float) centerX1, yPosition1, buttonRadius, mButton); canvas.drawCircle((float) centerX2, yPosition2, buttonRadius, mButton); // vertical lines canvas.drawLine((float) centerX1, (float) centerY1 + joystickRadius / 2, (float) centerX1, (float) (centerY1 - joystickRadius / 2), mLine); canvas.drawLine((float) centerX2, (float) centerY2 + joystickRadius / 2, (float) centerX2, (float) (centerY2 - joystickRadius / 2), mLine); // main horisontal lines // neuntral canvas.drawLine((float) (centerX1 - buttonRadius * 0.75), (float) centerY1, (float) (centerX1 + buttonRadius * 0.75), (float) centerY1, mLine); canvas.drawLine((float) (centerX2 - buttonRadius * 0.75), (float) centerY2, (float) (centerX2 + buttonRadius * 0.75), (float) centerY2, mLine); // low canvas.drawLine((float) (centerX1 - buttonRadius * 0.6), (float) centerY1 + joystickRadius / 2, (float) (centerX1 + buttonRadius * 0.6), (float) centerY1 + joystickRadius / 2, mLine); canvas.drawLine((float) (centerX2 - buttonRadius * 0.6), (float) centerY2 + joystickRadius / 2, (float) (centerX2 + buttonRadius * 0.6), (float) centerY2 + joystickRadius / 2, mLine); // high canvas.drawLine((float) (centerX1 - buttonRadius * 0.6), (float) centerY1 - joystickRadius / 2, (float) (centerX1 + buttonRadius * 0.6), (float) centerY1 - joystickRadius / 2, mLine); canvas.drawLine((float) (centerX2 - buttonRadius * 0.6), (float) centerY2 - joystickRadius / 2, (float) (centerX2 + buttonRadius * 0.6), (float) centerY2 - joystickRadius / 2, mLine); // second horisontal lines canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 4), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 4), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 4), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 4), mLine); canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 4), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 4), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 4), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 4), mLine); // canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 - (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 - (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 - 3 * (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 - 3 * (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 - 3 * (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 - 3 * (joystickRadius) / 8), mLine); // canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 + (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 + (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX1 - 0.4 * buttonRadius), (float) (centerY1 + 3 * (joystickRadius) / 8), (float) (centerX1 + 0.4 * buttonRadius), (float) (centerY1 + 3 * (joystickRadius) / 8), mLine); canvas.drawLine((float) (centerX2 - 0.4 * buttonRadius), (float) (centerY2 + 3 * (joystickRadius) / 8), (float) (centerX2 + 0.4 * buttonRadius), (float) (centerY2 + 3 * (joystickRadius) / 8), mLine); } @Override public boolean onTouchEvent(MotionEvent event) { // int actionMask = event.getActionMasked(); switch (actionMask) { case MotionEvent.ACTION_DOWN: { // first down int i1 = event.getActionIndex(); int y = (int) event.getY(i1); int x = (int) event.getX(i1); double abs1 = Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1)); double abs2 = Math.sqrt((x - centerX2) * (x - centerX2) + (y - centerY2) * (y - centerY2)); if (abs1 < abs2) { yPosition1 = y; leftTrackTouch = event.getPointerId(i1); if (abs1 > joystickRadius / 2) { yPosition1 = (int) ((yPosition1 - centerY1) * joystickRadius / 2 / abs1 + centerY1); } } else { yPosition2 = y; rightTrackTouch = event.getPointerId(i1); if (abs2 > joystickRadius / 2) { yPosition2 = (int) ((yPosition2 - centerY2) * joystickRadius / 2 / abs2 + centerY2); } } invalidate(); if (thread != null && thread.isAlive()) { thread.interrupt(); } thread = new Thread(this); thread.start(); } break; case MotionEvent.ACTION_POINTER_DOWN: { // next downs for (int i1 = 0; i1 < event.getPointerCount(); i1++) { // int i1 = event.getActionIndex(); int y = (int) event.getY(i1); int x = (int) event.getX(i1); if (leftTrackTouch == -1 && rightTrackTouch != event.getPointerId(i1)) { leftTrackTouch = event.getPointerId(i1); } else if (rightTrackTouch == -1 && leftTrackTouch != event.getPointerId(i1)) { rightTrackTouch = event.getPointerId(i1); } if (leftTrackTouch == event.getPointerId(i1)) { double abs1 = Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1)); yPosition1 = y; if (abs1 > joystickRadius / 2) { yPosition1 = (int) ((yPosition1 - centerY1) * joystickRadius / 2 / abs1 + centerY1); } } else if (rightTrackTouch == event.getPointerId(i1)) { double abs2 = Math.sqrt((x - centerX2) * (x - centerX2) + (y - centerY2) * (y - centerY2)); yPosition2 = y; if (abs2 > joystickRadius / 2) { yPosition2 = (int) ((yPosition2 - centerY2) * joystickRadius / 2 / abs2 + centerY2); } } } invalidate(); } break; case MotionEvent.ACTION_UP: { // last up yPosition1 = (int) centerY1; yPosition2 = (int) centerY2; rightTrackTouch = -1; leftTrackTouch = -1; invalidate(); thread.interrupt(); onTrackJoystickViewMoveListener.onValueChanged(getPower2(), getPower1()); } break; case MotionEvent.ACTION_POINTER_UP: { // next up //for (int i1 = 0; i1 < event.getPointerCount(); i1++) { int i = event.getPointerId(event.getActionIndex());// i1; if (leftTrackTouch == event.getPointerId(i)) { yPosition1 = (int) centerY1; leftTrackTouch = -1; } else if (rightTrackTouch == event.getPointerId(i)) { yPosition2 = (int) centerY2; rightTrackTouch = -1; } //} invalidate(); } break; case MotionEvent.ACTION_MOVE: { // moving for (int i1 = 0; i1 < event.getPointerCount(); i1++) { int y = (int) event.getY(i1); int x = (int) event.getX(i1); if (leftTrackTouch == event.getPointerId(i1)) { double abs1 = Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1)); yPosition1 = y; if (abs1 > joystickRadius / 2) { yPosition1 = (int) ((yPosition1 - centerY1) * joystickRadius / abs1 / 2 + centerY1); } } else if (rightTrackTouch == event.getPointerId(i1)) { double abs2 = Math.sqrt((x - centerX2) * (x - centerX2) + (y - centerY2) * (y - centerY2)); yPosition2 = y; if (abs2 > joystickRadius / 2) { yPosition2 = (int) ((yPosition2 - centerY2) * joystickRadius / abs2 / 2 + centerY2); } } } invalidate(); } break; } return true; } private int getPower1() { int y = yPosition1 - buttonRadius; return 100 - y * 200 / (getHeight() - 2 * buttonRadius); } private int getPower2() { int y = yPosition2 - buttonRadius; return 100 - y * 200 / (getHeight() - 2 * buttonRadius); } public void setOnTrackJoystickViewMoveListener( OnTrackJoystickViewMoveListener listener, long repeatInterval) { this.onTrackJoystickViewMoveListener = listener; this.loopInterval = repeatInterval; } public static interface OnTrackJoystickViewMoveListener { public void onValueChanged(int y1, int y2); } @Override public void run() { while (!Thread.interrupted()) { post(new Runnable() { public void run() { onTrackJoystickViewMoveListener.onValueChanged(getPower2(), getPower1()); } }); try { Thread.sleep(loopInterval); } catch (InterruptedException e) { break; } } } }
fix round powers
src/maximsblog/blogspot/com/trackjoystickview/TrackJoystickView.java
fix round powers
<ide><path>rc/maximsblog/blogspot/com/trackjoystickview/TrackJoystickView.java <ide> private int getPower1() { <ide> int y = yPosition1 - buttonRadius; <ide> <del> return 100 - y * 200 / (getHeight() - 2 * buttonRadius); <add> return (int) Math.round(100.0 - y * 200.0 / (getHeight() - 2.0 * buttonRadius)); <ide> } <ide> <ide> private int getPower2() { <ide> int y = yPosition2 - buttonRadius; <ide> <del> return 100 - y * 200 / (getHeight() - 2 * buttonRadius); <add> return (int) Math.round(100.0 - y * 200.0 / (getHeight() - 2.0 * buttonRadius)); <ide> } <ide> <ide> public void setOnTrackJoystickViewMoveListener(
Java
bsd-3-clause
7d72bd9c82d05f81b2553c20c37c87e256e4e525
0
Tietoarkisto/metka,Tietoarkisto/metka,Tietoarkisto/metka,Tietoarkisto/metka
/************************************************************************************** * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere * * * * 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. Neither the name of the copyright holder 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 HOLDER 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 fi.uta.fsd.metka.ddi.builder; import codebook25.*; import fi.uta.fsd.Logger; import fi.uta.fsd.metka.enums.Language; import fi.uta.fsd.metka.model.access.calls.*; import fi.uta.fsd.metka.model.access.enums.StatusCode; import fi.uta.fsd.metka.model.configuration.*; import fi.uta.fsd.metka.model.data.RevisionData; import fi.uta.fsd.metka.model.data.container.*; import fi.uta.fsd.metka.mvc.services.ReferenceService; import fi.uta.fsd.metka.names.Fields; import fi.uta.fsd.metka.names.Lists; import fi.uta.fsd.metka.storage.repository.RevisionRepository; import fi.uta.fsd.metka.storage.repository.enums.ReturnResult; import fi.uta.fsd.metka.transfer.reference.ReferenceOption; import org.apache.commons.lang3.tuple.Pair; import org.springframework.util.StringUtils; import java.util.*; class DDIWriteStudyDescription extends DDIWriteSectionBase { DDIWriteStudyDescription(RevisionData revision, Language language, CodeBookType codeBook, Configuration configuration, RevisionRepository revisions, ReferenceService references) { super(revision, language, codeBook, configuration, revisions, references); } void write() { // Add study description to codebook StdyDscrType stdyDscrType = codeBook.addNewStdyDscr(); addCitationInfo(stdyDscrType); addStudyAuthorization(stdyDscrType); addStudyInfo(stdyDscrType); addMethod(stdyDscrType); addDataAccess(stdyDscrType); addOtherStudyMaterial(stdyDscrType); } private void addCitationInfo(StdyDscrType stdyDscrType) { // Add citation CitationType citationType = stdyDscrType.addNewCitation(); addCitationTitle(citationType); addCitationRspStatement(citationType); addCitationProdStatement(citationType); addCitationDistStatement(citationType); // Add SerStmt addCitationSerStatement(citationType); // Add VerStmt addCitationVerStatement(citationType); // Add biblcit Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.BIBLCIT)); if(hasValue(valueFieldPair, language)) { fillTextType(citationType.addNewBiblCit(), valueFieldPair, language); } } private void addCitationProdStatement(CitationType citationType) { ProdStmtType prodStmtType = citationType.addNewProdStmt(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.PRODUCERS)); String path = "producers."; if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = path+row.getRowId()+"."; String organisation = getReferenceTitle(rowRoot + Fields.PRODUCERORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.PRODUCERAGENCY); String section = getReferenceTitle(rowRoot + Fields.PRODUCERSECTION); ProducerType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(prodStmtType.addNewProducer(), organisation); } else { String producer = (StringUtils.hasText(agency)) ? agency : ""; producer += (StringUtils.hasText(producer) && StringUtils.hasText(section)) ? ". " : ""; producer += (StringUtils.hasText(section)) ? section : ""; if(!StringUtils.hasText(producer)) { continue; } d = fillTextType(prodStmtType.addNewProducer(), producer); } String abbr = getReferenceTitle(rowRoot + Fields.PRODUCERSECTIONABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERAGENCYABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERORGANISATIONABBR); d.setAbbr(abbr); if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } Pair<StatusCode, ValueDataField> fieldPair = row.dataField(ValueDataFieldCall.get(Fields.PRODUCERROLE)); if(hasValue(fieldPair, Language.DEFAULT)) { String role = fieldPair.getRight().getActualValueFor(Language.DEFAULT); SelectionList list = configuration.getRootSelectionList(configuration.getField(Fields.PRODUCERROLE).getSelectionList()); Option option = list.getOptionWithValue(role); if(option != null) { d.setRole(option.getTitleFor(language)); } } } } // Add copyright fillTextType(prodStmtType.addNewCopyright(), getDDIText(language, "COPYRIGHT_STDY")); } private void addCitationDistStatement(CitationType citationType) { DistStmtType distStmtType = citationType.addNewDistStmt(); DistrbtrType d = fillTextType(distStmtType.addNewDistrbtr(), getDDIText(language, "DISTRIBUTR")); d.setAbbr(getDDIText(language, "DISTRIBUTR_ABB")); d.setURI(getDDIText(language, "DISTRIBUTR_URI")); } private void addCitationRspStatement(CitationType citationType) { RspStmtType rsp = citationType.addNewRspStmt(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.AUTHORS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { String pathRoot = "authors."; for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if (row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHORTYPE)); if (!hasValue(pair, Language.DEFAULT)) { // We require a type for collector before we can move forward continue; } if(!pair.getRight().getActualValueFor(Language.DEFAULT).equals("1")) { continue; } // We have a person author pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHOR)); if (!hasValue(pair, Language.DEFAULT)) { // We must have a collector continue; } AuthEntyType d = fillTextType(rsp.addNewAuthEnty(), pair, Language.DEFAULT); String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); String affiliation = (StringUtils.hasText(organisation)) ? organisation : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(agency)) ? ". " : ""; affiliation += (StringUtils.hasText(agency)) ? agency : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(section)) ? ". " : ""; affiliation += (StringUtils.hasText(section)) ? section : ""; if (StringUtils.hasText(affiliation)) { d.setAffiliation(affiliation); } } } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.OTHERAUTHORS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { String pathRoot = "authors."; for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if (row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.OTHERAUTHORTYPE)); if(!hasValue(pair, Language.DEFAULT)) { // We require a type for collector before we can move forward continue; } String colltype = pair.getRight().getActualValueFor(Language.DEFAULT); // It's easier to dublicate some functionality and make a clean split from the top than to evaluate each value separately if(colltype.equals("1")) { // We have a person collector pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHOR)); if(!hasValue(pair, Language.DEFAULT)) { // We must have a collector continue; } OthIdType d = fillTextType(rsp.addNewOthId(), pair, Language.DEFAULT); String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); String affiliation = (StringUtils.hasText(organisation)) ? organisation : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(agency)) ? ". " : ""; affiliation += (StringUtils.hasText(agency)) ? agency : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(section)) ? ". " : ""; affiliation += (StringUtils.hasText(section)) ? section : ""; if(StringUtils.hasText(affiliation)) { d.setAffiliation(affiliation); } } else if(colltype.equals("2")) { // We have an organisation collector String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); OthIdType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(rsp.addNewOthId(), organisation); } else { String collector = (StringUtils.hasText(agency)) ? agency : ""; if(StringUtils.hasText(collector) && StringUtils.hasText(section)) { collector += ". "+section; } else if(StringUtils.hasText(section)) { collector = section; } else { continue; } d = fillTextType(rsp.addNewOthId(), collector); } if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } } else if(colltype.equals("3")) { pair = row.dataField(ValueDataFieldCall.get(Fields.OTHERAUTHORGROUP)); if(hasValue(pair, language)) { fillTextType(rsp.addNewOthId(), pair, language); } } } } } private void addCitationSerStatement(CitationType citationType) { // Add series statement, excel row #70 Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.SERIES)); if(hasValue(valueFieldPair, Language.DEFAULT)) { Pair<ReturnResult, RevisionData> revisionPair = revisions.getRevisionData(valueFieldPair.getRight().getActualValueFor(Language.DEFAULT)); if(revisionPair.getLeft() == ReturnResult.REVISION_FOUND) { RevisionData series = revisionPair.getRight(); valueFieldPair = series.dataField(ValueDataFieldCall.get(Fields.SERIESABBR)); String seriesAbbr = null; if(hasValue(valueFieldPair, Language.DEFAULT)) { seriesAbbr = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } if(seriesAbbr != null) { SerStmtType serStmtType = citationType.addNewSerStmt(); serStmtType.setURI(getDDIText(language, "SERIES_URI_PREFIX")+seriesAbbr); valueFieldPair = series.dataField(ValueDataFieldCall.get(Fields.SERIESNAME)); SerNameType serName; if(hasValue(valueFieldPair, language)) { serName = fillTextType(serStmtType.addNewSerName(), valueFieldPair, language); } else { serName = fillTextType(serStmtType.addNewSerName(), ""); } serName.setAbbr(seriesAbbr); valueFieldPair = series.dataField(ValueDataFieldCall.get(Fields.SERIESDESC)); if(hasValue(valueFieldPair, language)) { fillTextType(serStmtType.addNewSerInfo(), valueFieldPair, language); } } } else { Logger.error(getClass(), "Did not find referenced SERIES with id: "+valueFieldPair.getRight().getActualValueFor(Language.DEFAULT)); } } } private void addCitationVerStatement(CitationType citationType) { VerStmtType verStmtType = citationType.addNewVerStmt(); // Add version, repeatable Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.DATAVERSIONS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.DATAVERSION)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextAndDateType(verStmtType.addNewVersion(), valueFieldPair, Language.DEFAULT); } } } } private void addCitationTitle(CitationType citationType) { Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.TITLE)); TitlStmtType titlStmtType = citationType.addNewTitlStmt(); if(hasValue(valueFieldPair, language)) { // Add title of requested language fillTextType(titlStmtType.addNewTitl(), valueFieldPair, language); } addAltTitles(titlStmtType); addParTitles(titlStmtType); String agency = ""; valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.STUDYID)); if(hasValue(valueFieldPair, Language.DEFAULT)) { String id = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); // Get agency from study id SelectionList list = configuration.getRootSelectionList(Lists.ID_PREFIX_LIST); if(list != null) { for(Option option : list.getOptions()) { if(id.indexOf(option.getValue()) == 0) { agency = option.getValue(); break; } } } // Add study id as id no IDNoType idNoType = fillTextType(titlStmtType.addNewIDNo(), valueFieldPair, Language.DEFAULT); idNoType.setAgency(agency); } // Add DDI pid for the current language as idNO // TODO: Should this be the DDI package urn /*valueFieldPair = revisionData.dataField(ValueDataFieldCall.get(Fields.PIDDDI+getXmlLang(language))); if(hasValue(valueFieldPair, Language.DEFAULT)) { IDNoType idNoType = fillTextType(titlStmtType.addNewIDNo(), valueFieldPair, Language.DEFAULT); idNoType.setAgency(agency); }*/ } private void addParTitles(TitlStmtType titlStmtType) { Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.TITLE)); Set<String> usedLanguages = new HashSet<>(); usedLanguages.add(getXmlLang(language)); for(Language l : Language.values()) { if(l == language) { continue; } if(hasValue(valueFieldPair, l)) { SimpleTextType stt = fillTextType(titlStmtType.addNewParTitl(), valueFieldPair, l); stt.setXmlLang(getXmlLang(l)); usedLanguages.add(getXmlLang(l)); } } Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.PARTITLES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.PARTITLE)); String partitle = null; if(hasValue(valueFieldPair, Language.DEFAULT)) { partitle = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.PARTITLELANG)); String partitlelang = null; if(hasValue(valueFieldPair, Language.DEFAULT)) { partitlelang = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } if(partitle != null && partitlelang != null) { if(!usedLanguages.contains(partitlelang)) { SimpleTextType stt = fillTextType(titlStmtType.addNewParTitl(), partitle); stt.setXmlLang(partitlelang); usedLanguages.add(partitlelang); } } } } } private void addAltTitles(TitlStmtType titlStmtType) { Pair<StatusCode, ValueDataField> valueFieldPair;// Add alternative titles Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.ALTTITLES)); // TODO: Do we translate alternate titles or do the alternate titles have translations? if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.ALTTITLE)); if(hasValue(valueFieldPair, language)) { fillTextType(titlStmtType.addNewAltTitl(), valueFieldPair, language); } } } } private void addStudyAuthorization(StdyDscrType stdyDscrType) { Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.AUTHORS)); String path = "authors."; if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { StudyAuthorizationType sa = stdyDscrType.addNewStudyAuthorization(); for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHORTYPE)); if(!hasValue(pair, Language.DEFAULT)) { continue; } // If author type is person then it's not correct for this entity if(pair.getRight().getActualValueFor(Language.DEFAULT).equals("1")) { continue; } String rowRoot = path+row.getRowId()+"."; String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); AuthorizingAgencyType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(sa.addNewAuthorizingAgency(), organisation); } else { String authorizer = (StringUtils.hasText(agency)) ? agency : ""; authorizer += (StringUtils.hasText(authorizer) && StringUtils.hasText(section)) ? ". " : ""; authorizer += (StringUtils.hasText(section)) ? section : ""; if(!StringUtils.hasText(authorizer)) { continue; } d = fillTextType(sa.addNewAuthorizingAgency(), authorizer); } String abbr = getReferenceTitle(rowRoot + Fields.PRODUCERSECTIONABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERAGENCYABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERORGANISATIONABBR); d.setAbbr(abbr); if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } } } } private void addStudyInfo(StdyDscrType stdyDscrType) { StdyInfoType stdyInfo = stdyDscrType.addNewStdyInfo(); addStudyInfoSubject(stdyInfo); Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField( ValueDataFieldCall.get(Fields.ABSTRACT)); if(hasValue(valueFieldPair, language)) { fillTextType(stdyInfo.addNewAbstract(), valueFieldPair, language); } addStudyInfoSumDesc(stdyInfo); } private void addStudyInfoSubject(StdyInfoType stdyInfo) { SubjectType subject= stdyInfo.addNewSubject(); // Add subject Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.KEYWORDS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSubjectKeywords(subject, containerPair.getRight()); } // Add topic containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.TOPICS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSubjectTopics(subject, containerPair.getRight()); } } private void addStudyInfoSubjectKeywords(SubjectType subject, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "keywords."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String keyword = null; String keywordvocaburi = null; ReferenceOption keywordvocab = references.getCurrentFieldOption(language, revision, configuration, rowRoot + Fields.KEYWORDVOCAB, true); keywordvocaburi = getReferenceTitle(rowRoot + Fields.KEYWORDVOCABURI); SelectionList keywordvocab_list = configuration.getSelectionList(Lists.KEYWORDVOCAB_LIST); if(keywordvocab == null || keywordvocab_list.getFreeText().contains(keywordvocab.getValue())) { Pair<StatusCode, ValueDataField> keywordnovocabPair = row.dataField(ValueDataFieldCall.get(Fields.KEYWORDNOVOCAB)); if(hasValue(keywordnovocabPair, language)) { keyword = keywordnovocabPair.getRight().getActualValueFor(language); } } else { Pair<StatusCode, ValueDataField> keywordPair = row.dataField(ValueDataFieldCall.get(Fields.KEYWORD)); if(hasValue(keywordPair, language)) { keyword = keywordPair.getRight().getActualValueFor(language); } } if(!StringUtils.hasText(keyword)) { continue; } KeywordType kwt = fillTextType(subject.addNewKeyword(), keyword); if(keywordvocab != null) { kwt.setVocab(keywordvocab.getTitle().getValue()); } if(StringUtils.hasText(keywordvocaburi)) { kwt.setVocabURI(keywordvocaburi); } } } private void addStudyInfoSubjectTopics(SubjectType subject, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "topics."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String topic = null; String topictop = null; String topicvocab = null; String topicvocaburi = null; topicvocab = getReferenceTitle(rowRoot + Fields.TOPICVOCAB); if(!StringUtils.hasText(topicvocab)) { continue; } topictop = getReferenceTitle(rowRoot + Fields.TOPICTOP); if(!StringUtils.hasText(topictop)) { continue; } topic = getReferenceTitle(rowRoot + Fields.TOPIC); if(!StringUtils.hasText(topic)) { continue; } topicvocaburi = getReferenceTitle(rowRoot + Fields.TOPICVOCABURI); // Keyword should always be non null at this point TopcClasType tt = fillTextType(subject.addNewTopcClas(), topic); if(topicvocab != null) { tt.setVocab(topicvocab); } if(topicvocaburi != null) { tt.setVocabURI(topicvocaburi); } } } private void addStudyInfoSumDesc(StdyInfoType stdyInfo) { SumDscrType sumDscrType = stdyInfo.addNewSumDscr(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.TIMEPERIODS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescTimePrd(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COLLTIME)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescCollDate(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COUNTRIES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescNation(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.GEOGCOVERS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(language)) { for(DataRow row : containerPair.getRight().getRowsFor(language)) { if (row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> fieldPair = row.dataField(ValueDataFieldCall.get(Fields.GEOGCOVER)); if(hasValue(fieldPair, language)) { fillTextType(sumDscrType.addNewGeogCover(), fieldPair, language); } } } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.ANALYSIS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescAnlyUnit(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.UNIVERSES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescUniverse(sumDscrType, containerPair); } Pair<StatusCode, ValueDataField> fieldPair = revision.dataField(ValueDataFieldCall.get(Fields.DATAKIND)); if(hasValue(fieldPair, Language.DEFAULT)) { SelectionList list = configuration.getRootSelectionList(configuration.getField(Fields.DATAKIND).getSelectionList()); Option option = list.getOptionWithValue(fieldPair.getRight().getActualValueFor(Language.DEFAULT)); if(option != null) { fillTextType(sumDscrType.addNewDataKind(), option.getTitleFor(language)); } } } private void addStudyInfoSumDescAnlyUnit(SumDscrType sumDscr, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "analysis."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String analysisunit = null; String analysisunitvocab = null; String analysisunitvocaburi = null; analysisunitvocab = getReferenceTitle(rowRoot + Fields.ANALYSISUNITVOCAB); if(!StringUtils.hasText(analysisunitvocab)) { continue; } analysisunit = getReferenceTitle(rowRoot + Fields.ANALYSISUNIT); if(!StringUtils.hasText(analysisunit)) { continue; } analysisunitvocaburi = getReferenceTitle(rowRoot + Fields.ANALYSISUNITVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.ANALYSISUNITOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point AnlyUnitType t = sumDscr.addNewAnlyUnit(); ConceptType c = fillTextType(t.addNewConcept(), analysisunit); if(analysisunitvocab != null) { c.setVocab(analysisunitvocab); } if(analysisunitvocaburi != null) { c.setVocabURI(analysisunitvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addStudyInfoSumDescUniverse(SumDscrType sumDscrType, Pair<StatusCode, ContainerDataField> containerPair) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if (row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> fieldPair = row.dataField(ValueDataFieldCall.get(Fields.UNIVERSE)); if(hasValue(fieldPair, language)) { UniverseType t = fillTextType(sumDscrType.addNewUniverse(), fieldPair, language); fieldPair = row.dataField(ValueDataFieldCall.get(Fields.UNIVERSECLUSION)); if(hasValue(fieldPair, Language.DEFAULT)) { switch(fieldPair.getRight().getActualValueFor(Language.DEFAULT)) { case "I": t.setClusion(UniverseType.Clusion.I); break; case "E": t.setClusion(UniverseType.Clusion.E); break; } } } } } private void addStudyInfoSumDescTimePrd(SumDscrType sumDscr, ContainerDataField container) { for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> valuePair = row.dataField(ValueDataFieldCall.get(Fields.TIMEPERIODTEXT)); String timeperiodtext = hasValue(valuePair, language) ? valuePair.getRight().getActualValueFor(language) : null; valuePair = row.dataField(ValueDataFieldCall.get(Fields.TIMEPERIOD)); if(StringUtils.hasText(timeperiodtext) || hasValue(valuePair, Language.DEFAULT)) { TimePrdType t = sumDscr.addNewTimePrd(); if(StringUtils.hasText(timeperiodtext)) { fillTextType(t, timeperiodtext); } if(hasValue(valuePair, Language.DEFAULT)) { t.setDate(valuePair.getRight().getActualValueFor(Language.DEFAULT)); } valuePair = row.dataField(ValueDataFieldCall.get(Fields.TIMEPERIODEVENT)); if(hasValue(valuePair, Language.DEFAULT)) { switch(valuePair.getRight().getActualValueFor(Language.DEFAULT)) { case "start": t.setEvent(TimePrdType.Event.START); break; case "end": t.setEvent(TimePrdType.Event.END); break; case "single": t.setEvent(TimePrdType.Event.SINGLE); break; } } } } } private void addStudyInfoSumDescCollDate(SumDscrType sumDscr, ContainerDataField container) { for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> valuePair = row.dataField(ValueDataFieldCall.get(Fields.COLLDATETEXT)); String colldatetext = hasValue(valuePair, language) ? valuePair.getRight().getActualValueFor(language) : null; valuePair = row.dataField(ValueDataFieldCall.get(Fields.COLLDATE)); if(StringUtils.hasText(colldatetext) || hasValue(valuePair, Language.DEFAULT)) { CollDateType t = sumDscr.addNewCollDate(); if(StringUtils.hasText(colldatetext)) { fillTextType(t, colldatetext); } if(hasValue(valuePair, Language.DEFAULT)) { t.setDate(valuePair.getRight().getActualValueFor(Language.DEFAULT)); } valuePair = row.dataField(ValueDataFieldCall.get(Fields.COLLDATEEVENT)); if(hasValue(valuePair, Language.DEFAULT)) { switch(valuePair.getRight().getActualValueFor(Language.DEFAULT)) { case "start": t.setEvent(CollDateType.Event.START); break; case "end": t.setEvent(CollDateType.Event.END); break; case "single": t.setEvent(CollDateType.Event.SINGLE); break; } } } } } private void addStudyInfoSumDescNation(SumDscrType sumDscr, ContainerDataField container) { for (DataRow row : container.getRowsFor(language)) { if (row.getRemoved()) { continue; } Pair<StatusCode,ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.COUNTRY)); if (valueFieldPair.getLeft() != StatusCode.FIELD_FOUND && !valueFieldPair.getRight().hasValueFor(language)) return; NationType n = fillTextType(sumDscr.addNewNation(), valueFieldPair,language); valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.COUNTRYABBR)); if (valueFieldPair.getLeft() == StatusCode.FIELD_FOUND && valueFieldPair.getRight().hasValueFor(language)) { n.setAbbr(valueFieldPair.getValue().getActualValueFor(language)); } } } private void addMethod(StdyDscrType stdyDscrType) { MethodType methodType = stdyDscrType.addNewMethod(); addMethodDataColl(methodType); Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.DATAPROSESSING)); if(hasValue(valueFieldPair, language)) { fillTextType(methodType.addNewNotes(), valueFieldPair, language); } addMethodAnalyzeInfo(methodType); } private void addMethodDataColl(MethodType methodType) { // Add data column DataCollType dataCollType = methodType.addNewDataColl(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.TIMEMETHODS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollTimeMeth(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.SAMPPROCS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollSampProc(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COLLMODES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollCollMode(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.INSTRUMENTS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollResInstru(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COLLECTORS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollDataCollector(dataCollType, containerPair.getRight()); } addMethodDataCollSources(dataCollType); addMethodDataCollWeight(dataCollType); } private void addMethodDataCollTimeMeth(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "timemethods."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String timemethod = null; String timemethodvocab = null; String timemethodvocaburi = null; timemethodvocab = getReferenceTitle(rowRoot + Fields.TIMEMETHODVOCAB); if(!StringUtils.hasText(timemethodvocab)) { continue; } timemethod = getReferenceTitle(rowRoot + Fields.TIMEMETHOD); if(!StringUtils.hasText(timemethod)) { continue; } timemethodvocaburi = getReferenceTitle(rowRoot + Fields.TIMEMETHODVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.TIMEMETHODOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point TimeMethType t = dataColl.addNewTimeMeth(); ConceptType c = fillTextType(t.addNewConcept(), timemethod); if(timemethodvocab != null) { c.setVocab(timemethodvocab); } if(timemethodvocaburi != null) { c.setVocabURI(timemethodvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollDataCollector(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "collectors."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.COLLECTORTYPE)); if(!hasValue(pair, Language.DEFAULT)) { // We require a type for collector before we can move forward continue; } String colltype = pair.getRight().getActualValueFor(Language.DEFAULT); // It's easier to dublicate some functionality and make a clean split from the top than to evaluate each value separately if(colltype.equals("1")) { // We have a person collector pair = row.dataField(ValueDataFieldCall.get(Fields.COLLECTOR)); if(!hasValue(pair, Language.DEFAULT)) { // We must have a collector continue; } DataCollectorType d = fillTextType(dataColl.addNewDataCollector(), pair, Language.DEFAULT); String organisation = getReferenceTitle(rowRoot + Fields.COLLECTORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.COLLECTORAGENCY); String section = getReferenceTitle(rowRoot + Fields.COLLECTORSECTION); String affiliation = (StringUtils.hasText(organisation)) ? organisation : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(agency)) ? ". " : ""; affiliation += (StringUtils.hasText(agency)) ? agency : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(section)) ? ". " : ""; affiliation += (StringUtils.hasText(section)) ? section : ""; if(StringUtils.hasText(affiliation)) { d.setAffiliation(affiliation); } } else if(colltype.equals("2")) { // We have an organisation collector String organisation = getReferenceTitle(rowRoot + Fields.COLLECTORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.COLLECTORAGENCY); String section = getReferenceTitle(rowRoot + Fields.COLLECTORSECTION); DataCollectorType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(dataColl.addNewDataCollector(), organisation); } else { String collector = (StringUtils.hasText(agency)) ? agency : ""; if(StringUtils.hasText(collector) && StringUtils.hasText(section)) { collector += ". "+section; } else if(StringUtils.hasText(section)) { collector = section; } else { continue; } d = fillTextType(dataColl.addNewDataCollector(), collector); } String abbr = getReferenceTitle(rowRoot + Fields.COLLECTORSECTIONABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.COLLECTORAGENCYABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.COLLECTORORGANISATIONABBR); d.setAbbr(abbr); if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } } } } private void addMethodDataCollSampProc(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "sampprocs."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String sampproc = null; String sampprocvocab = null; String sampprocvocaburi = null; String sampproctext = null; sampprocvocab = getReferenceTitle(rowRoot + Fields.SAMPPROCVOCAB); if(!StringUtils.hasText(sampprocvocab)) { continue; } sampproc = getReferenceTitle(rowRoot + Fields.SAMPPROC); if(!StringUtils.hasText(sampproc)) { continue; } sampprocvocaburi = getReferenceTitle(rowRoot + Fields.SAMPPROCVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.SAMPPROCOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point ConceptualTextType t = dataColl.addNewSampProc(); // Add sampproctext if present valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.SAMPPROCTEXT)); sampproctext = valueFieldPair.getRight().getActualValueFor(language).replaceAll("<[^>]+>",""); ConceptType c = fillTextType(t.addNewConcept(), sampproc); if(sampprocvocab != null) { c.setVocab(sampprocvocab); } if(sampprocvocaburi != null) { c.setVocabURI(sampprocvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } if(sampproctext != null) { fillTextType(t.addNewP(), sampproctext); } } } private void addMethodDataCollCollMode(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "collmodes."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String collmode = null; String collmodevocab = null; String collmodevocaburi = null; collmodevocab = getReferenceTitle(rowRoot + Fields.COLLMODEVOCAB); if(!StringUtils.hasText(collmodevocab)) { continue; } collmode = getReferenceTitle(rowRoot + Fields.COLLMODE); if(!StringUtils.hasText(collmode)) { continue; } collmodevocaburi = getReferenceTitle(rowRoot + Fields.COLLMODEVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.COLLMODEOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point ConceptualTextType t = dataColl.addNewCollMode(); ConceptType c = fillTextType(t.addNewConcept(), collmode); if(collmodevocab != null) { c.setVocab(collmodevocab); } if(collmodevocaburi != null) { c.setVocabURI(collmodevocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollResInstru(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "instruments."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String instrument = null; String instrumentvocab = null; String instrumentvocaburi = null; instrumentvocab = getReferenceTitle(rowRoot + Fields.INSTRUMENTVOCAB); if(!StringUtils.hasText(instrumentvocab)) { continue; } instrument = getReferenceTitle(rowRoot + Fields.INSTRUMENT); if(!StringUtils.hasText(instrument)) { continue; } instrumentvocaburi = getReferenceTitle(rowRoot + Fields.INSTRUMENTVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.INSTRUMENTOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point ResInstruType t = dataColl.addNewResInstru(); ConceptType c = fillTextType(t.addNewConcept(), instrument); if(instrumentvocab != null) { c.setVocab(instrumentvocab); } if(instrumentvocaburi != null) { c.setVocabURI(instrumentvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollSources(DataCollType dataCollType) { List<ValueDataField> fields = gatherFields(revision, Fields.DATASOURCES, Fields.DATASOURCE, language, language); SourcesType sources = dataCollType.addNewSources(); for(ValueDataField field : fields) { fillTextType(sources.addNewDataSrc(), field, language); } } private void addMethodDataCollWeight(DataCollType dataCollType) { Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.WEIGHTYESNO)); if(hasValue(valueFieldPair, Language.DEFAULT) && valueFieldPair.getRight().getValueFor(Language.DEFAULT).valueAsBoolean()) { fillTextType(dataCollType.addNewWeight(), getDDIText(language, "WEIGHT_NO")); } else { valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.WEIGHT)); if(hasValue(valueFieldPair, language)) { fillTextType(dataCollType.addNewWeight(), valueFieldPair, language); } } } private void addMethodAnalyzeInfo(MethodType methodType) { AnlyInfoType anlyInfoType = methodType.addNewAnlyInfo(); // Add response rate Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.RESPRATE)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(anlyInfoType.addNewRespRate(), valueFieldPair, Language.DEFAULT); } // Add data appraisal, repeatable Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.APPRAISALS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(language)) { for (DataRow row : containerPair.getRight().getRowsFor(language)) { valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.APPRAISAL)); if(hasValue(valueFieldPair, language)) { fillTextType(anlyInfoType.addNewDataAppr(), valueFieldPair, language); } } } } private void addDataAccess(StdyDscrType stdyDscrType) { DataAccsType dataAccs = stdyDscrType.addNewDataAccs(); addDataAccessSetAvail(dataAccs); addDataAccessUseStatement(dataAccs); // Add notes Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.DATASETNOTES)); if(hasValue(valueFieldPair, language)) { fillTextType(dataAccs.addNewNotes(), valueFieldPair, language); } } private void addDataAccessSetAvail(DataAccsType dataAccs) { // Add set availability SetAvailType setAvail = dataAccs.addNewSetAvail(); // Add access place AccsPlacType acc = fillTextType(setAvail.addNewAccsPlac(), getDDIText(language, "ACCS_PLAC")); acc.setURI(getDDIText(language, "ACCS_PLAC_URI")); // Add original archive Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.ORIGINALLOCATION)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(setAvail.addNewOrigArch(), valueFieldPair, Language.DEFAULT); } // Add collection size valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.COLLSIZE)); if(hasValue(valueFieldPair, language)) { fillTextType(setAvail.addNewCollSize(), valueFieldPair, language); } // Add complete valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.COMPLETE)); if(hasValue(valueFieldPair, language)) { fillTextType(setAvail.addNewComplete(), valueFieldPair, language); } } private void addDataAccessUseStatement(DataAccsType dataAccs) { // Add use statement UseStmtType useStmt = dataAccs.addNewUseStmt(); // Add special permissions Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.SPECIALTERMSOFUSE)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(useStmt.addNewSpecPerm(), valueFieldPair, language); } // Add restrictions, excel row #164 valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.TERMSOFUSE)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(useStmt.addNewRestrctn(), getDDIRestriction(language, valueFieldPair.getRight().getActualValueFor(Language.DEFAULT))); } // Add citation required fillTextType(useStmt.addNewCitReq(), getDDIText(language, "CIT_REQ")); // Add deposition required fillTextType(useStmt.addNewDeposReq(), getDDIText(language, "DEPOS_REQ")); // Add disclaimer required fillTextType(useStmt.addNewDisclaimer(), getDDIText(language, "DISCLAIMER")); } private void addOtherStudyMaterial(StdyDscrType stdyDscrType) { OthrStdyMatType othr = stdyDscrType.addNewOthrStdyMat(); // Add related materials List<ValueDataField> fields = gatherFields(revision, Fields.RELATEDMATERIALS, Fields.RELATEDMATERIAL, language, language); for(ValueDataField field : fields) { fillTextType(othr.addNewRelMat(), field, language); } // Add related studies (studyID + study name) Pair<StatusCode, ReferenceContainerDataField> referenceContainerPair = revision.dataField(ReferenceContainerDataFieldCall.get(Fields.RELATEDSTUDIES)); if(referenceContainerPair.getLeft() == StatusCode.FIELD_FOUND && !referenceContainerPair.getRight().getReferences().isEmpty()) { for(ReferenceRow row : referenceContainerPair.getRight().getReferences()) { if(row.getRemoved() || !row.hasValue()) { continue; } Pair<ReturnResult, RevisionData> revisionPair = revisions.getRevisionData(row.getReference().getValue()); if(revisionPair.getLeft() != ReturnResult.REVISION_FOUND) { Logger.error(getClass(), "Could not find referenced study with ID: "+row.getReference().getValue()); continue; } String studyID = "-"; String title = "-"; RevisionData study = revisionPair.getRight(); Pair<StatusCode, ValueDataField> valueFieldPair = study.dataField(ValueDataFieldCall.get(Fields.STUDYID)); if(hasValue(valueFieldPair, Language.DEFAULT)) { studyID = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } valueFieldPair = study.dataField(ValueDataFieldCall.get(Fields.TITLE)); if(hasValue(valueFieldPair, language)) { title = valueFieldPair.getRight().getActualValueFor(language); } fillTextType(othr.addNewRelStdy(), studyID+" "+title); } } // Add related publications (publications -> publicationrelpubl) referenceContainerPair = revision.dataField(ReferenceContainerDataFieldCall.get(Fields.PUBLICATIONS)); if(referenceContainerPair.getLeft() == StatusCode.FIELD_FOUND && !referenceContainerPair.getRight().getReferences().isEmpty()) { for(ReferenceRow row : referenceContainerPair.getRight().getReferences()) { if (row.getRemoved() || !row.hasValue()) { continue; } Pair<ReturnResult, RevisionData> revisionPair = revisions.getRevisionData(row.getReference().getValue()); if (revisionPair.getLeft() != ReturnResult.REVISION_FOUND) { Logger.error(getClass(), "Could not find referenced publication with ID: " + row.getReference().getValue()); continue; } RevisionData publication = revisionPair.getRight(); Pair<StatusCode, ValueDataField> valueFieldPair = publication.dataField(ValueDataFieldCall.get(Fields.PUBLICATIONRELPUBL)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(othr.addNewRelPubl(), valueFieldPair, Language.DEFAULT); } } } // Add publication comments fields = gatherFields(revision, Fields.PUBLICATIONCOMMENTS, Fields.PUBLICATIONCOMMENT, language, language); for(ValueDataField field : fields) { fillTextType(othr.addNewOthRefs(), field, language); } } }
metka/src/main/java/fi/uta/fsd/metka/ddi/builder/DDIWriteStudyDescription.java
/************************************************************************************** * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere * * * * 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. Neither the name of the copyright holder 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 HOLDER 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 fi.uta.fsd.metka.ddi.builder; import codebook25.*; import fi.uta.fsd.Logger; import fi.uta.fsd.metka.enums.Language; import fi.uta.fsd.metka.model.access.calls.*; import fi.uta.fsd.metka.model.access.enums.StatusCode; import fi.uta.fsd.metka.model.configuration.*; import fi.uta.fsd.metka.model.data.RevisionData; import fi.uta.fsd.metka.model.data.container.*; import fi.uta.fsd.metka.mvc.services.ReferenceService; import fi.uta.fsd.metka.names.Fields; import fi.uta.fsd.metka.names.Lists; import fi.uta.fsd.metka.storage.repository.RevisionRepository; import fi.uta.fsd.metka.storage.repository.enums.ReturnResult; import fi.uta.fsd.metka.transfer.reference.ReferenceOption; import org.apache.commons.lang3.tuple.Pair; import org.springframework.util.StringUtils; import java.util.*; class DDIWriteStudyDescription extends DDIWriteSectionBase { DDIWriteStudyDescription(RevisionData revision, Language language, CodeBookType codeBook, Configuration configuration, RevisionRepository revisions, ReferenceService references) { super(revision, language, codeBook, configuration, revisions, references); } void write() { // Add study description to codebook StdyDscrType stdyDscrType = codeBook.addNewStdyDscr(); addCitationInfo(stdyDscrType); addStudyAuthorization(stdyDscrType); addStudyInfo(stdyDscrType); addMethod(stdyDscrType); addDataAccess(stdyDscrType); addOtherStudyMaterial(stdyDscrType); } private void addCitationInfo(StdyDscrType stdyDscrType) { // Add citation CitationType citationType = stdyDscrType.addNewCitation(); addCitationTitle(citationType); addCitationRspStatement(citationType); addCitationProdStatement(citationType); addCitationDistStatement(citationType); // Add SerStmt addCitationSerStatement(citationType); // Add VerStmt addCitationVerStatement(citationType); // Add biblcit Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.BIBLCIT)); if(hasValue(valueFieldPair, language)) { fillTextType(citationType.addNewBiblCit(), valueFieldPair, language); } } private void addCitationProdStatement(CitationType citationType) { ProdStmtType prodStmtType = citationType.addNewProdStmt(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.PRODUCERS)); String path = "producers."; if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = path+row.getRowId()+"."; String organisation = getReferenceTitle(rowRoot + Fields.PRODUCERORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.PRODUCERAGENCY); String section = getReferenceTitle(rowRoot + Fields.PRODUCERSECTION); ProducerType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(prodStmtType.addNewProducer(), organisation); } else { String producer = (StringUtils.hasText(agency)) ? agency : ""; producer += (StringUtils.hasText(producer) && StringUtils.hasText(section)) ? ". " : ""; producer += (StringUtils.hasText(section)) ? section : ""; if(!StringUtils.hasText(producer)) { continue; } d = fillTextType(prodStmtType.addNewProducer(), producer); } String abbr = getReferenceTitle(rowRoot + Fields.PRODUCERSECTIONABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERAGENCYABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERORGANISATIONABBR); d.setAbbr(abbr); if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } Pair<StatusCode, ValueDataField> fieldPair = row.dataField(ValueDataFieldCall.get(Fields.PRODUCERROLE)); if(hasValue(fieldPair, Language.DEFAULT)) { String role = fieldPair.getRight().getActualValueFor(Language.DEFAULT); SelectionList list = configuration.getRootSelectionList(configuration.getField(Fields.PRODUCERROLE).getSelectionList()); Option option = list.getOptionWithValue(role); if(option != null) { d.setRole(option.getTitleFor(language)); } } } } // Add copyright fillTextType(prodStmtType.addNewCopyright(), getDDIText(language, "COPYRIGHT_STDY")); } private void addCitationDistStatement(CitationType citationType) { DistStmtType distStmtType = citationType.addNewDistStmt(); DistrbtrType d = fillTextType(distStmtType.addNewDistrbtr(), getDDIText(language, "DISTRIBUTR")); d.setAbbr(getDDIText(language, "DISTRIBUTR_ABB")); d.setURI(getDDIText(language, "DISTRIBUTR_URI")); } private void addCitationRspStatement(CitationType citationType) { RspStmtType rsp = citationType.addNewRspStmt(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.AUTHORS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { String pathRoot = "authors."; for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if (row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHORTYPE)); if (!hasValue(pair, Language.DEFAULT)) { // We require a type for collector before we can move forward continue; } if(!pair.getRight().getActualValueFor(Language.DEFAULT).equals("1")) { continue; } // We have a person author pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHOR)); if (!hasValue(pair, Language.DEFAULT)) { // We must have a collector continue; } AuthEntyType d = fillTextType(rsp.addNewAuthEnty(), pair, Language.DEFAULT); String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); String affiliation = (StringUtils.hasText(organisation)) ? organisation : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(agency)) ? ". " : ""; affiliation += (StringUtils.hasText(agency)) ? agency : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(section)) ? ". " : ""; affiliation += (StringUtils.hasText(section)) ? section : ""; if (StringUtils.hasText(affiliation)) { d.setAffiliation(affiliation); } } } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.OTHERAUTHORS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { String pathRoot = "authors."; for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if (row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.OTHERAUTHORTYPE)); if(!hasValue(pair, Language.DEFAULT)) { // We require a type for collector before we can move forward continue; } String colltype = pair.getRight().getActualValueFor(Language.DEFAULT); // It's easier to dublicate some functionality and make a clean split from the top than to evaluate each value separately if(colltype.equals("1")) { // We have a person collector pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHOR)); if(!hasValue(pair, Language.DEFAULT)) { // We must have a collector continue; } OthIdType d = fillTextType(rsp.addNewOthId(), pair, Language.DEFAULT); String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); String affiliation = (StringUtils.hasText(organisation)) ? organisation : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(agency)) ? ". " : ""; affiliation += (StringUtils.hasText(agency)) ? agency : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(section)) ? ". " : ""; affiliation += (StringUtils.hasText(section)) ? section : ""; if(StringUtils.hasText(affiliation)) { d.setAffiliation(affiliation); } } else if(colltype.equals("2")) { // We have an organisation collector String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); OthIdType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(rsp.addNewOthId(), organisation); } else { String collector = (StringUtils.hasText(agency)) ? agency : ""; if(StringUtils.hasText(collector) && StringUtils.hasText(section)) { collector += ". "+section; } else if(StringUtils.hasText(section)) { collector = section; } else { continue; } d = fillTextType(rsp.addNewOthId(), collector); } if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } } else if(colltype.equals("3")) { pair = row.dataField(ValueDataFieldCall.get(Fields.OTHERAUTHORGROUP)); if(hasValue(pair, language)) { fillTextType(rsp.addNewOthId(), pair, language); } } } } } private void addCitationSerStatement(CitationType citationType) { // Add series statement, excel row #70 Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.SERIES)); if(hasValue(valueFieldPair, Language.DEFAULT)) { Pair<ReturnResult, RevisionData> revisionPair = revisions.getRevisionData(valueFieldPair.getRight().getActualValueFor(Language.DEFAULT)); if(revisionPair.getLeft() == ReturnResult.REVISION_FOUND) { RevisionData series = revisionPair.getRight(); valueFieldPair = series.dataField(ValueDataFieldCall.get(Fields.SERIESABBR)); String seriesAbbr = null; if(hasValue(valueFieldPair, Language.DEFAULT)) { seriesAbbr = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } if(seriesAbbr != null) { SerStmtType serStmtType = citationType.addNewSerStmt(); serStmtType.setURI(getDDIText(language, "SERIES_URI_PREFIX")+seriesAbbr); valueFieldPair = series.dataField(ValueDataFieldCall.get(Fields.SERIESNAME)); SerNameType serName; if(hasValue(valueFieldPair, language)) { serName = fillTextType(serStmtType.addNewSerName(), valueFieldPair, language); } else { serName = fillTextType(serStmtType.addNewSerName(), ""); } serName.setAbbr(seriesAbbr); valueFieldPair = series.dataField(ValueDataFieldCall.get(Fields.SERIESDESC)); if(hasValue(valueFieldPair, language)) { fillTextType(serStmtType.addNewSerInfo(), valueFieldPair, language); } } } else { Logger.error(getClass(), "Did not find referenced SERIES with id: "+valueFieldPair.getRight().getActualValueFor(Language.DEFAULT)); } } } private void addCitationVerStatement(CitationType citationType) { VerStmtType verStmtType = citationType.addNewVerStmt(); // Add version, repeatable Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.DATAVERSIONS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.DATAVERSION)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextAndDateType(verStmtType.addNewVersion(), valueFieldPair, Language.DEFAULT); } } } } private void addCitationTitle(CitationType citationType) { Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.TITLE)); TitlStmtType titlStmtType = citationType.addNewTitlStmt(); if(hasValue(valueFieldPair, language)) { // Add title of requested language fillTextType(titlStmtType.addNewTitl(), valueFieldPair, language); } addAltTitles(titlStmtType); addParTitles(titlStmtType); String agency = ""; valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.STUDYID)); if(hasValue(valueFieldPair, Language.DEFAULT)) { String id = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); // Get agency from study id SelectionList list = configuration.getRootSelectionList(Lists.ID_PREFIX_LIST); if(list != null) { for(Option option : list.getOptions()) { if(id.indexOf(option.getValue()) == 0) { agency = option.getValue(); break; } } } // Add study id as id no IDNoType idNoType = fillTextType(titlStmtType.addNewIDNo(), valueFieldPair, Language.DEFAULT); idNoType.setAgency(agency); } // Add DDI pid for the current language as idNO // TODO: Should this be the DDI package urn /*valueFieldPair = revisionData.dataField(ValueDataFieldCall.get(Fields.PIDDDI+getXmlLang(language))); if(hasValue(valueFieldPair, Language.DEFAULT)) { IDNoType idNoType = fillTextType(titlStmtType.addNewIDNo(), valueFieldPair, Language.DEFAULT); idNoType.setAgency(agency); }*/ } private void addParTitles(TitlStmtType titlStmtType) { Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.TITLE)); Set<String> usedLanguages = new HashSet<>(); usedLanguages.add(getXmlLang(language)); for(Language l : Language.values()) { if(l == language) { continue; } if(hasValue(valueFieldPair, l)) { SimpleTextType stt = fillTextType(titlStmtType.addNewParTitl(), valueFieldPair, l); stt.setXmlLang(getXmlLang(l)); usedLanguages.add(getXmlLang(l)); } } Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.PARTITLES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.PARTITLE)); String partitle = null; if(hasValue(valueFieldPair, Language.DEFAULT)) { partitle = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.PARTITLELANG)); String partitlelang = null; if(hasValue(valueFieldPair, Language.DEFAULT)) { partitlelang = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } if(partitle != null && partitlelang != null) { if(!usedLanguages.contains(partitlelang)) { SimpleTextType stt = fillTextType(titlStmtType.addNewParTitl(), partitle); stt.setXmlLang(partitlelang); usedLanguages.add(partitlelang); } } } } } private void addAltTitles(TitlStmtType titlStmtType) { Pair<StatusCode, ValueDataField> valueFieldPair;// Add alternative titles Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.ALTTITLES)); // TODO: Do we translate alternate titles or do the alternate titles have translations? if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.ALTTITLE)); if(hasValue(valueFieldPair, language)) { fillTextType(titlStmtType.addNewAltTitl(), valueFieldPair, language); } } } } private void addStudyAuthorization(StdyDscrType stdyDscrType) { Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.AUTHORS)); String path = "authors."; if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { StudyAuthorizationType sa = stdyDscrType.addNewStudyAuthorization(); for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.AUTHORTYPE)); if(!hasValue(pair, Language.DEFAULT)) { continue; } // If author type is person then it's not correct for this entity if(pair.getRight().getActualValueFor(Language.DEFAULT).equals("1")) { continue; } String rowRoot = path+row.getRowId()+"."; String organisation = getReferenceTitle(rowRoot + Fields.AUTHORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.AUTHORAGENCY); String section = getReferenceTitle(rowRoot + Fields.AUTHORSECTION); AuthorizingAgencyType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(sa.addNewAuthorizingAgency(), organisation); } else { String authorizer = (StringUtils.hasText(agency)) ? agency : ""; authorizer += (StringUtils.hasText(authorizer) && StringUtils.hasText(section)) ? ". " : ""; authorizer += (StringUtils.hasText(section)) ? section : ""; if(!StringUtils.hasText(authorizer)) { continue; } d = fillTextType(sa.addNewAuthorizingAgency(), authorizer); } String abbr = getReferenceTitle(rowRoot + Fields.PRODUCERSECTIONABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERAGENCYABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.PRODUCERORGANISATIONABBR); d.setAbbr(abbr); if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } } } } private void addStudyInfo(StdyDscrType stdyDscrType) { StdyInfoType stdyInfo = stdyDscrType.addNewStdyInfo(); addStudyInfoSubject(stdyInfo); Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField( ValueDataFieldCall.get(Fields.ABSTRACT)); if(hasValue(valueFieldPair, language)) { fillTextType(stdyInfo.addNewAbstract(), valueFieldPair, language); } addStudyInfoSumDesc(stdyInfo); } private void addStudyInfoSubject(StdyInfoType stdyInfo) { SubjectType subject= stdyInfo.addNewSubject(); // Add subject Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.KEYWORDS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSubjectKeywords(subject, containerPair.getRight()); } // Add topic containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.TOPICS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSubjectTopics(subject, containerPair.getRight()); } } private void addStudyInfoSubjectKeywords(SubjectType subject, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "keywords."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String keyword = null; String keywordvocaburi = null; ReferenceOption keywordvocab = references.getCurrentFieldOption(language, revision, configuration, rowRoot + Fields.KEYWORDVOCAB, true); keywordvocaburi = getReferenceTitle(rowRoot + Fields.KEYWORDVOCABURI); SelectionList keywordvocab_list = configuration.getSelectionList(Lists.KEYWORDVOCAB_LIST); if(keywordvocab == null || keywordvocab_list.getFreeText().contains(keywordvocab.getValue())) { Pair<StatusCode, ValueDataField> keywordnovocabPair = row.dataField(ValueDataFieldCall.get(Fields.KEYWORDNOVOCAB)); if(hasValue(keywordnovocabPair, language)) { keyword = keywordnovocabPair.getRight().getActualValueFor(language); } } else { Pair<StatusCode, ValueDataField> keywordPair = row.dataField(ValueDataFieldCall.get(Fields.KEYWORD)); if(hasValue(keywordPair, language)) { keyword = keywordPair.getRight().getActualValueFor(language); } } if(!StringUtils.hasText(keyword)) { continue; } KeywordType kwt = fillTextType(subject.addNewKeyword(), keyword); if(keywordvocab != null) { kwt.setVocab(keywordvocab.getTitle().getValue()); } if(StringUtils.hasText(keywordvocaburi)) { kwt.setVocabURI(keywordvocaburi); } } } private void addStudyInfoSubjectTopics(SubjectType subject, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "topics."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String topic = null; String topictop = null; String topicvocab = null; String topicvocaburi = null; topicvocab = getReferenceTitle(rowRoot + Fields.TOPICVOCAB); if(!StringUtils.hasText(topicvocab)) { continue; } topictop = getReferenceTitle(rowRoot + Fields.TOPICTOP); if(!StringUtils.hasText(topictop)) { continue; } topic = getReferenceTitle(rowRoot + Fields.TOPIC); if(!StringUtils.hasText(topic)) { continue; } topicvocaburi = getReferenceTitle(rowRoot + Fields.TOPICVOCABURI); // Keyword should always be non null at this point TopcClasType tt = fillTextType(subject.addNewTopcClas(), topic); if(topicvocab != null) { tt.setVocab(topicvocab); } if(topicvocaburi != null) { tt.setVocabURI(topicvocaburi); } } } private void addStudyInfoSumDesc(StdyInfoType stdyInfo) { SumDscrType sumDscrType = stdyInfo.addNewSumDscr(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.TIMEPERIODS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescTimePrd(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COLLTIME)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescCollDate(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COUNTRIES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescNation(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.GEOGCOVERS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(language)) { for(DataRow row : containerPair.getRight().getRowsFor(language)) { if (row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> fieldPair = row.dataField(ValueDataFieldCall.get(Fields.GEOGCOVER)); if(hasValue(fieldPair, language)) { fillTextType(sumDscrType.addNewGeogCover(), fieldPair, language); } } } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.ANALYSIS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescAnlyUnit(sumDscrType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.UNIVERSES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addStudyInfoSumDescUniverse(sumDscrType, containerPair); } Pair<StatusCode, ValueDataField> fieldPair = revision.dataField(ValueDataFieldCall.get(Fields.DATAKIND)); if(hasValue(fieldPair, Language.DEFAULT)) { SelectionList list = configuration.getRootSelectionList(configuration.getField(Fields.DATAKIND).getSelectionList()); Option option = list.getOptionWithValue(fieldPair.getRight().getActualValueFor(Language.DEFAULT)); if(option != null) { fillTextType(sumDscrType.addNewDataKind(), option.getTitleFor(language)); } } } private void addStudyInfoSumDescAnlyUnit(SumDscrType sumDscr, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "analysis."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String analysisunit = null; String analysisunitvocab = null; String analysisunitvocaburi = null; analysisunitvocab = getReferenceTitle(rowRoot + Fields.ANALYSISUNITVOCAB); if(!StringUtils.hasText(analysisunitvocab)) { continue; } analysisunit = getReferenceTitle(rowRoot + Fields.ANALYSISUNIT); if(!StringUtils.hasText(analysisunit)) { continue; } analysisunitvocaburi = getReferenceTitle(rowRoot + Fields.ANALYSISUNITVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.ANALYSISUNITOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point AnlyUnitType t = sumDscr.addNewAnlyUnit(); ConceptType c = fillTextType(t.addNewConcept(), analysisunit); if(analysisunitvocab != null) { c.setVocab(analysisunitvocab); } if(analysisunitvocaburi != null) { c.setVocabURI(analysisunitvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addStudyInfoSumDescUniverse(SumDscrType sumDscrType, Pair<StatusCode, ContainerDataField> containerPair) { for(DataRow row : containerPair.getRight().getRowsFor(Language.DEFAULT)) { if (row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> fieldPair = row.dataField(ValueDataFieldCall.get(Fields.UNIVERSE)); if(hasValue(fieldPair, language)) { UniverseType t = fillTextType(sumDscrType.addNewUniverse(), fieldPair, language); fieldPair = row.dataField(ValueDataFieldCall.get(Fields.UNIVERSECLUSION)); if(hasValue(fieldPair, Language.DEFAULT)) { switch(fieldPair.getRight().getActualValueFor(Language.DEFAULT)) { case "I": t.setClusion(UniverseType.Clusion.I); break; case "E": t.setClusion(UniverseType.Clusion.E); break; } } } } } private void addStudyInfoSumDescTimePrd(SumDscrType sumDscr, ContainerDataField container) { for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> valuePair = row.dataField(ValueDataFieldCall.get(Fields.TIMEPERIODTEXT)); String timeperiodtext = hasValue(valuePair, language) ? valuePair.getRight().getActualValueFor(language) : null; valuePair = row.dataField(ValueDataFieldCall.get(Fields.TIMEPERIOD)); if(StringUtils.hasText(timeperiodtext) || hasValue(valuePair, Language.DEFAULT)) { TimePrdType t = sumDscr.addNewTimePrd(); if(StringUtils.hasText(timeperiodtext)) { fillTextType(t, timeperiodtext); } if(hasValue(valuePair, Language.DEFAULT)) { t.setDate(valuePair.getRight().getActualValueFor(Language.DEFAULT)); } valuePair = row.dataField(ValueDataFieldCall.get(Fields.TIMEPERIODEVENT)); if(hasValue(valuePair, Language.DEFAULT)) { switch(valuePair.getRight().getActualValueFor(Language.DEFAULT)) { case "start": t.setEvent(TimePrdType.Event.START); break; case "end": t.setEvent(TimePrdType.Event.END); break; case "single": t.setEvent(TimePrdType.Event.SINGLE); break; } } } } } private void addStudyInfoSumDescCollDate(SumDscrType sumDscr, ContainerDataField container) { for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } Pair<StatusCode, ValueDataField> valuePair = row.dataField(ValueDataFieldCall.get(Fields.COLLDATETEXT)); String colldatetext = hasValue(valuePair, language) ? valuePair.getRight().getActualValueFor(language) : null; valuePair = row.dataField(ValueDataFieldCall.get(Fields.COLLDATE)); if(StringUtils.hasText(colldatetext) || hasValue(valuePair, Language.DEFAULT)) { CollDateType t = sumDscr.addNewCollDate(); if(StringUtils.hasText(colldatetext)) { fillTextType(t, colldatetext); } if(hasValue(valuePair, Language.DEFAULT)) { t.setDate(valuePair.getRight().getActualValueFor(Language.DEFAULT)); } valuePair = row.dataField(ValueDataFieldCall.get(Fields.COLLDATEEVENT)); if(hasValue(valuePair, Language.DEFAULT)) { switch(valuePair.getRight().getActualValueFor(Language.DEFAULT)) { case "start": t.setEvent(CollDateType.Event.START); break; case "end": t.setEvent(CollDateType.Event.END); break; case "single": t.setEvent(CollDateType.Event.SINGLE); break; } } } } } private void addStudyInfoSumDescNation(SumDscrType sumDscr, ContainerDataField container) { for (DataRow row : container.getRowsFor(language)) { if (row.getRemoved()) { continue; } Pair<StatusCode,ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.COUNTRY)); if (valueFieldPair.getLeft() != StatusCode.FIELD_FOUND && !valueFieldPair.getRight().hasValueFor(language)) return; NationType n = fillTextType(sumDscr.addNewNation(), valueFieldPair,language); valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.COUNTRYABBR)); if (valueFieldPair.getLeft() == StatusCode.FIELD_FOUND && valueFieldPair.getRight().hasValueFor(language)) { n.setAbbr(valueFieldPair.getValue().getActualValueFor(language)); } } } private void addMethod(StdyDscrType stdyDscrType) { MethodType methodType = stdyDscrType.addNewMethod(); addMethodDataColl(methodType); Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.DATAPROSESSING)); if(hasValue(valueFieldPair, language)) { fillTextType(methodType.addNewNotes(), valueFieldPair, language); } addMethodAnalyzeInfo(methodType); } private void addMethodDataColl(MethodType methodType) { // Add data column DataCollType dataCollType = methodType.addNewDataColl(); Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.TIMEMETHODS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollTimeMeth(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.SAMPPROCS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollSampProc(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COLLMODES)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollCollMode(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.INSTRUMENTS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollResInstru(dataCollType, containerPair.getRight()); } containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.COLLECTORS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(Language.DEFAULT)) { addMethodDataCollDataCollector(dataCollType, containerPair.getRight()); } addMethodDataCollSources(dataCollType); addMethodDataCollWeight(dataCollType); } private void addMethodDataCollTimeMeth(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "timemethods."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String timemethod = null; String timemethodvocab = null; String timemethodvocaburi = null; timemethodvocab = getReferenceTitle(rowRoot + Fields.TIMEMETHODVOCAB); if(!StringUtils.hasText(timemethodvocab)) { continue; } timemethod = getReferenceTitle(rowRoot + Fields.TIMEMETHOD); if(!StringUtils.hasText(timemethod)) { continue; } timemethodvocaburi = getReferenceTitle(rowRoot + Fields.TIMEMETHODVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.TIMEMETHODOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point TimeMethType t = dataColl.addNewTimeMeth(); ConceptType c = fillTextType(t.addNewConcept(), timemethod); if(timemethodvocab != null) { c.setVocab(timemethodvocab); } if(timemethodvocaburi != null) { c.setVocabURI(timemethodvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollDataCollector(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "collectors."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; Pair<StatusCode, ValueDataField> pair = row.dataField(ValueDataFieldCall.get(Fields.COLLECTORTYPE)); if(!hasValue(pair, Language.DEFAULT)) { // We require a type for collector before we can move forward continue; } String colltype = pair.getRight().getActualValueFor(Language.DEFAULT); // It's easier to dublicate some functionality and make a clean split from the top than to evaluate each value separately if(colltype.equals("1")) { // We have a person collector pair = row.dataField(ValueDataFieldCall.get(Fields.COLLECTOR)); if(!hasValue(pair, Language.DEFAULT)) { // We must have a collector continue; } DataCollectorType d = fillTextType(dataColl.addNewDataCollector(), pair, Language.DEFAULT); String organisation = getReferenceTitle(rowRoot + Fields.COLLECTORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.COLLECTORAGENCY); String section = getReferenceTitle(rowRoot + Fields.COLLECTORSECTION); String affiliation = (StringUtils.hasText(organisation)) ? organisation : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(agency)) ? ". " : ""; affiliation += (StringUtils.hasText(agency)) ? agency : ""; affiliation += (StringUtils.hasText(affiliation) && StringUtils.hasText(section)) ? ". " : ""; affiliation += (StringUtils.hasText(section)) ? section : ""; if(StringUtils.hasText(affiliation)) { d.setAffiliation(affiliation); } } else if(colltype.equals("2")) { // We have an organisation collector String organisation = getReferenceTitle(rowRoot + Fields.COLLECTORORGANISATION); String agency = getReferenceTitle(rowRoot + Fields.COLLECTORAGENCY); String section = getReferenceTitle(rowRoot + Fields.COLLECTORSECTION); DataCollectorType d; if(!StringUtils.hasText(agency) && !StringUtils.hasText(section)) { if(!StringUtils.hasText(organisation)) { continue; } d = fillTextType(dataColl.addNewDataCollector(), organisation); } else { String collector = (StringUtils.hasText(agency)) ? agency : ""; if(StringUtils.hasText(collector) && StringUtils.hasText(section)) { collector += ". "+section; } else if(StringUtils.hasText(section)) { collector = section; } else { continue; } d = fillTextType(dataColl.addNewDataCollector(), collector); } String abbr = getReferenceTitle(rowRoot + Fields.COLLECTORSECTIONABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.COLLECTORAGENCYABBR); abbr = (StringUtils.hasText(abbr)) ? abbr : getReferenceTitle(rowRoot + Fields.COLLECTORORGANISATIONABBR); d.setAbbr(abbr); if(StringUtils.hasText(agency) || StringUtils.hasText(section)) { if(StringUtils.hasText(organisation)) { d.setAffiliation(organisation); } } } } } private void addMethodDataCollSampProc(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "sampprocs."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String sampproc = null; String sampprocvocab = null; String sampprocvocaburi = null; sampprocvocab = getReferenceTitle(rowRoot + Fields.SAMPPROCVOCAB); if(!StringUtils.hasText(sampprocvocab)) { continue; } sampproc = getReferenceTitle(rowRoot + Fields.SAMPPROC); if(!StringUtils.hasText(sampproc)) { continue; } sampprocvocaburi = getReferenceTitle(rowRoot + Fields.SAMPPROCVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.SAMPPROCOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point ConceptualTextType t = dataColl.addNewSampProc(); // Add sampproctext if present valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.SAMPPROCTEXT)); if(hasValue(valueFieldPair, language)) { fillTextType(t, valueFieldPair, language); } ConceptType c = fillTextType(t.addNewConcept(), sampproc); if(sampprocvocab != null) { c.setVocab(sampprocvocab); } if(sampprocvocaburi != null) { c.setVocabURI(sampprocvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollCollMode(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "collmodes."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String collmode = null; String collmodevocab = null; String collmodevocaburi = null; collmodevocab = getReferenceTitle(rowRoot + Fields.COLLMODEVOCAB); if(!StringUtils.hasText(collmodevocab)) { continue; } collmode = getReferenceTitle(rowRoot + Fields.COLLMODE); if(!StringUtils.hasText(collmode)) { continue; } collmodevocaburi = getReferenceTitle(rowRoot + Fields.COLLMODEVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.COLLMODEOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point ConceptualTextType t = dataColl.addNewCollMode(); ConceptType c = fillTextType(t.addNewConcept(), collmode); if(collmodevocab != null) { c.setVocab(collmodevocab); } if(collmodevocaburi != null) { c.setVocabURI(collmodevocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollResInstru(DataCollType dataColl, ContainerDataField container) { // Let's hardcode the path since we know exactly what we are looking for. String pathRoot = "instruments."; for(DataRow row : container.getRowsFor(Language.DEFAULT)) { if(row.getRemoved()) { continue; } String rowRoot = pathRoot + row.getRowId() + "."; String txt = null; String instrument = null; String instrumentvocab = null; String instrumentvocaburi = null; instrumentvocab = getReferenceTitle(rowRoot + Fields.INSTRUMENTVOCAB); if(!StringUtils.hasText(instrumentvocab)) { continue; } instrument = getReferenceTitle(rowRoot + Fields.INSTRUMENT); if(!StringUtils.hasText(instrument)) { continue; } instrumentvocaburi = getReferenceTitle(rowRoot + Fields.INSTRUMENTVOCABURI); Pair<StatusCode, ValueDataField> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.INSTRUMENTOTHER)); if(hasValue(valueFieldPair, language)) { txt = valueFieldPair.getRight().getActualValueFor(language); } // Keyword should always be non null at this point ResInstruType t = dataColl.addNewResInstru(); ConceptType c = fillTextType(t.addNewConcept(), instrument); if(instrumentvocab != null) { c.setVocab(instrumentvocab); } if(instrumentvocaburi != null) { c.setVocabURI(instrumentvocaburi); } if(txt != null) { fillTextType(t.addNewTxt(), txt); } } } private void addMethodDataCollSources(DataCollType dataCollType) { List<ValueDataField> fields = gatherFields(revision, Fields.DATASOURCES, Fields.DATASOURCE, language, language); SourcesType sources = dataCollType.addNewSources(); for(ValueDataField field : fields) { fillTextType(sources.addNewDataSrc(), field, language); } } private void addMethodDataCollWeight(DataCollType dataCollType) { Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.WEIGHTYESNO)); if(hasValue(valueFieldPair, Language.DEFAULT) && valueFieldPair.getRight().getValueFor(Language.DEFAULT).valueAsBoolean()) { fillTextType(dataCollType.addNewWeight(), getDDIText(language, "WEIGHT_NO")); } else { valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.WEIGHT)); if(hasValue(valueFieldPair, language)) { fillTextType(dataCollType.addNewWeight(), valueFieldPair, language); } } } private void addMethodAnalyzeInfo(MethodType methodType) { AnlyInfoType anlyInfoType = methodType.addNewAnlyInfo(); // Add response rate Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.RESPRATE)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(anlyInfoType.addNewRespRate(), valueFieldPair, Language.DEFAULT); } // Add data appraisal, repeatable Pair<StatusCode, ContainerDataField> containerPair = revision.dataField(ContainerDataFieldCall.get(Fields.APPRAISALS)); if(containerPair.getLeft() == StatusCode.FIELD_FOUND && containerPair.getRight().hasRowsFor(language)) { for (DataRow row : containerPair.getRight().getRowsFor(language)) { valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.APPRAISAL)); if(hasValue(valueFieldPair, language)) { fillTextType(anlyInfoType.addNewDataAppr(), valueFieldPair, language); } } } } private void addDataAccess(StdyDscrType stdyDscrType) { DataAccsType dataAccs = stdyDscrType.addNewDataAccs(); addDataAccessSetAvail(dataAccs); addDataAccessUseStatement(dataAccs); // Add notes Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.DATASETNOTES)); if(hasValue(valueFieldPair, language)) { fillTextType(dataAccs.addNewNotes(), valueFieldPair, language); } } private void addDataAccessSetAvail(DataAccsType dataAccs) { // Add set availability SetAvailType setAvail = dataAccs.addNewSetAvail(); // Add access place AccsPlacType acc = fillTextType(setAvail.addNewAccsPlac(), getDDIText(language, "ACCS_PLAC")); acc.setURI(getDDIText(language, "ACCS_PLAC_URI")); // Add original archive Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.ORIGINALLOCATION)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(setAvail.addNewOrigArch(), valueFieldPair, Language.DEFAULT); } // Add collection size valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.COLLSIZE)); if(hasValue(valueFieldPair, language)) { fillTextType(setAvail.addNewCollSize(), valueFieldPair, language); } // Add complete valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.COMPLETE)); if(hasValue(valueFieldPair, language)) { fillTextType(setAvail.addNewComplete(), valueFieldPair, language); } } private void addDataAccessUseStatement(DataAccsType dataAccs) { // Add use statement UseStmtType useStmt = dataAccs.addNewUseStmt(); // Add special permissions Pair<StatusCode, ValueDataField> valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.SPECIALTERMSOFUSE)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(useStmt.addNewSpecPerm(), valueFieldPair, language); } // Add restrictions, excel row #164 valueFieldPair = revision.dataField(ValueDataFieldCall.get(Fields.TERMSOFUSE)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(useStmt.addNewRestrctn(), getDDIRestriction(language, valueFieldPair.getRight().getActualValueFor(Language.DEFAULT))); } // Add citation required fillTextType(useStmt.addNewCitReq(), getDDIText(language, "CIT_REQ")); // Add deposition required fillTextType(useStmt.addNewDeposReq(), getDDIText(language, "DEPOS_REQ")); // Add disclaimer required fillTextType(useStmt.addNewDisclaimer(), getDDIText(language, "DISCLAIMER")); } private void addOtherStudyMaterial(StdyDscrType stdyDscrType) { OthrStdyMatType othr = stdyDscrType.addNewOthrStdyMat(); // Add related materials List<ValueDataField> fields = gatherFields(revision, Fields.RELATEDMATERIALS, Fields.RELATEDMATERIAL, language, language); for(ValueDataField field : fields) { fillTextType(othr.addNewRelMat(), field, language); } // Add related studies (studyID + study name) Pair<StatusCode, ReferenceContainerDataField> referenceContainerPair = revision.dataField(ReferenceContainerDataFieldCall.get(Fields.RELATEDSTUDIES)); if(referenceContainerPair.getLeft() == StatusCode.FIELD_FOUND && !referenceContainerPair.getRight().getReferences().isEmpty()) { for(ReferenceRow row : referenceContainerPair.getRight().getReferences()) { if(row.getRemoved() || !row.hasValue()) { continue; } Pair<ReturnResult, RevisionData> revisionPair = revisions.getRevisionData(row.getReference().getValue()); if(revisionPair.getLeft() != ReturnResult.REVISION_FOUND) { Logger.error(getClass(), "Could not find referenced study with ID: "+row.getReference().getValue()); continue; } String studyID = "-"; String title = "-"; RevisionData study = revisionPair.getRight(); Pair<StatusCode, ValueDataField> valueFieldPair = study.dataField(ValueDataFieldCall.get(Fields.STUDYID)); if(hasValue(valueFieldPair, Language.DEFAULT)) { studyID = valueFieldPair.getRight().getActualValueFor(Language.DEFAULT); } valueFieldPair = study.dataField(ValueDataFieldCall.get(Fields.TITLE)); if(hasValue(valueFieldPair, language)) { title = valueFieldPair.getRight().getActualValueFor(language); } fillTextType(othr.addNewRelStdy(), studyID+" "+title); } } // Add related publications (publications -> publicationrelpubl) referenceContainerPair = revision.dataField(ReferenceContainerDataFieldCall.get(Fields.PUBLICATIONS)); if(referenceContainerPair.getLeft() == StatusCode.FIELD_FOUND && !referenceContainerPair.getRight().getReferences().isEmpty()) { for(ReferenceRow row : referenceContainerPair.getRight().getReferences()) { if (row.getRemoved() || !row.hasValue()) { continue; } Pair<ReturnResult, RevisionData> revisionPair = revisions.getRevisionData(row.getReference().getValue()); if (revisionPair.getLeft() != ReturnResult.REVISION_FOUND) { Logger.error(getClass(), "Could not find referenced publication with ID: " + row.getReference().getValue()); continue; } RevisionData publication = revisionPair.getRight(); Pair<StatusCode, ValueDataField> valueFieldPair = publication.dataField(ValueDataFieldCall.get(Fields.PUBLICATIONRELPUBL)); if(hasValue(valueFieldPair, Language.DEFAULT)) { fillTextType(othr.addNewRelPubl(), valueFieldPair, Language.DEFAULT); } } } // Add publication comments fields = gatherFields(revision, Fields.PUBLICATIONCOMMENTS, Fields.PUBLICATIONCOMMENT, language, language); for(ValueDataField field : fields) { fillTextType(othr.addNewOthRefs(), field, language); } } }
DDI-Export: Otantamenetelmän kuvauksen siirtäminen p-tagin sisään, concept-elementin perään #615
metka/src/main/java/fi/uta/fsd/metka/ddi/builder/DDIWriteStudyDescription.java
DDI-Export: Otantamenetelmän kuvauksen siirtäminen p-tagin sisään, concept-elementin perään #615
<ide><path>etka/src/main/java/fi/uta/fsd/metka/ddi/builder/DDIWriteStudyDescription.java <ide> String sampproc = null; <ide> String sampprocvocab = null; <ide> String sampprocvocaburi = null; <add> String sampproctext = null; <ide> <ide> sampprocvocab = getReferenceTitle(rowRoot + Fields.SAMPPROCVOCAB); <ide> if(!StringUtils.hasText(sampprocvocab)) { <ide> <ide> // Add sampproctext if present <ide> valueFieldPair = row.dataField(ValueDataFieldCall.get(Fields.SAMPPROCTEXT)); <del> if(hasValue(valueFieldPair, language)) { <del> fillTextType(t, valueFieldPair, language); <del> } <add> sampproctext = valueFieldPair.getRight().getActualValueFor(language).replaceAll("<[^>]+>",""); <ide> <ide> ConceptType c = fillTextType(t.addNewConcept(), sampproc); <ide> <ide> <ide> if(txt != null) { <ide> fillTextType(t.addNewTxt(), txt); <add> } <add> <add> if(sampproctext != null) { <add> fillTextType(t.addNewP(), sampproctext); <ide> } <ide> } <ide> }
Java
apache-2.0
36edbdee9151c8b6b9a4a56cb8ef49ca9973f6ef
0
nicolargo/intellij-community,clumsy/intellij-community,kdwink/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,allotria/intellij-community,gnuhub/intellij-community,allotria/intellij-community,holmes/intellij-community,Lekanich/intellij-community,izonder/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ryano144/intellij-community,slisson/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,da1z/intellij-community,semonte/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,supersven/intellij-community,holmes/intellij-community,petteyg/intellij-community,ryano144/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,signed/intellij-community,caot/intellij-community,robovm/robovm-studio,petteyg/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,da1z/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,fitermay/intellij-community,asedunov/intellij-community,jagguli/intellij-community,robovm/robovm-studio,kool79/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,kdwink/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,holmes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,samthor/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,da1z/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,apixandru/intellij-community,diorcety/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,adedayo/intellij-community,semonte/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,kool79/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,kdwink/intellij-community,diorcety/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,allotria/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,vladmm/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ryano144/intellij-community,FHannes/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,slisson/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,holmes/intellij-community,signed/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,caot/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,kool79/intellij-community,caot/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ibinti/intellij-community,blademainer/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,signed/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,hurricup/intellij-community,amith01994/intellij-community,asedunov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,allotria/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,slisson/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,slisson/intellij-community,semonte/intellij-community,hurricup/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,kool79/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,caot/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,blademainer/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,xfournet/intellij-community,clumsy/intellij-community,retomerz/intellij-community,signed/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,da1z/intellij-community,vladmm/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,dslomov/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,caot/intellij-community,signed/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,clumsy/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,blademainer/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,retomerz/intellij-community,holmes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,blademainer/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,jagguli/intellij-community,asedunov/intellij-community,kool79/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,clumsy/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,da1z/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,allotria/intellij-community,dslomov/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,semonte/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,semonte/intellij-community,retomerz/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,samthor/intellij-community,semonte/intellij-community,semonte/intellij-community,xfournet/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,retomerz/intellij-community,allotria/intellij-community,allotria/intellij-community,amith01994/intellij-community,blademainer/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,caot/intellij-community,kool79/intellij-community,da1z/intellij-community,asedunov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,blademainer/intellij-community,xfournet/intellij-community,da1z/intellij-community,robovm/robovm-studio,adedayo/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,allotria/intellij-community,allotria/intellij-community,wreckJ/intellij-community,da1z/intellij-community,da1z/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,izonder/intellij-community,samthor/intellij-community,da1z/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,jagguli/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,fnouama/intellij-community,amith01994/intellij-community,retomerz/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,dslomov/intellij-community,vladmm/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,supersven/intellij-community,vladmm/intellij-community,izonder/intellij-community,fnouama/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,diorcety/intellij-community,vvv1559/intellij-community,caot/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,kool79/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,izonder/intellij-community,dslomov/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,semonte/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,hurricup/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,slisson/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,adedayo/intellij-community,amith01994/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,signed/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,kdwink/intellij-community,holmes/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fitermay/intellij-community,kdwink/intellij-community,dslomov/intellij-community,holmes/intellij-community,samthor/intellij-community,tmpgit/intellij-community,holmes/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,supersven/intellij-community,caot/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,samthor/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,kool79/intellij-community,blademainer/intellij-community
/* * Copyright 2005 Pythonid 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 com.jetbrains.python.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Icons; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.stubs.PyClassStub; import com.jetbrains.python.validation.DocStringAnnotator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: yole * Date: 03.06.2005 * Time: 0:27:33 * To change this template use File | Settings | File Templates. */ public class PyClassImpl extends PyPresentableElementImpl<PyClassStub> implements PyClass { public PyClassImpl(ASTNode astNode) { super(astNode); } public PyClassImpl(final PyClassStub stub) { super(stub, PyElementTypes.CLASS_DECLARATION); } public PsiElement setName(@NotNull String name) throws IncorrectOperationException { final ASTNode nameElement = getLanguage().getElementGenerator().createNameIdentifier(getProject(), name); getNode().replaceChild(findNameIdentifier(), nameElement); return this; } @Nullable @Override public String getName() { final PyClassStub stub = getStub(); if (stub != null) { return stub.getName(); } else { ASTNode node = findNameIdentifier(); return node != null ? node.getText() : null; } } private ASTNode findNameIdentifier() { return getNode().findChildByType(PyTokenTypes.IDENTIFIER); } @Override public Icon getIcon(int flags) { return Icons.CLASS_ICON; } @Override protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyClass(this); } @NotNull public PyStatementList getStatementList() { return childToPsiNotNull(PyElementTypes.STATEMENT_LIST); } @Nullable public PyExpression[] getSuperClassExpressions() { final PyParenthesizedExpression superExpression = PsiTreeUtil.getChildOfType(this, PyParenthesizedExpression.class); if (superExpression != null) { PyExpression expr = superExpression.getContainedExpression(); if (expr instanceof PyTupleExpression) { return ((PyTupleExpression) expr).getElements(); } if (expr != null) { return new PyExpression[] { expr }; } } return null; } public PsiElement[] getSuperClassElements() { final PyExpression[] superExpressions = getSuperClassExpressions(); if (superExpressions != null) { List<PsiElement> superClasses = new ArrayList<PsiElement>(); for(PyExpression expr: superExpressions) { if (expr instanceof PyReferenceExpression && !"object".equals(expr.getText())) { PyReferenceExpression ref = (PyReferenceExpression) expr; final PsiElement result = ref.resolve(); if (result != null) { superClasses.add(result); } } } return superClasses.toArray(new PsiElement[superClasses.size()]); } return null; } public PyClass[] getSuperClasses() { PsiElement[] superClassElements = getSuperClassElements(); if (superClassElements != null) { List<PyClass> result = new ArrayList<PyClass>(); for(PsiElement element: superClassElements) { if (element instanceof PyClass) { result.add((PyClass) element); } } return result.toArray(new PyClass[result.size()]); } return null; } @NotNull public PyFunction[] getMethods() { List<PyFunction> result = new ArrayList<PyFunction>(); final PyStatementList statementList = getStatementList(); for (PsiElement element : statementList.getChildren()) { if (element instanceof PyFunction) { result.add((PyFunction) element); } } return result.toArray(new PyFunction[result.size()]); } public PyFunction findMethodByName(@NotNull final String name) { PyFunction[] methods = getMethods(); for(PyFunction method: methods) { if (name.equals(method.getName())) { return method; } } return null; } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState substitutor, PsiElement lastParent, @NotNull PsiElement place) { final PyStatementList statementList = getStatementList(); for(PyFunction func: getMethods()) { if (!processor.execute(func, substitutor)) return false; if ("__init__".equals(func.getName())) { if (!processFields(processor, func, substitutor)) return false; } } for (PsiElement psiElement : statementList.getChildren()) { if (psiElement instanceof PyAssignmentStatement) { final PyAssignmentStatement assignmentStatement = (PyAssignmentStatement)psiElement; final PyExpression[] targets = assignmentStatement.getTargets(); for (PyExpression target : targets) { if (target instanceof PyTargetExpression) { if (!processor.execute(target, substitutor)) return false; } } } } if (processor instanceof PyResolveUtil.VariantsProcessor) { return true; } return processor.execute(this, substitutor); } private static boolean processFields(final PsiScopeProcessor processor, final PyFunction function, final ResolveState substitutor) { final PyParameter[] params = function.getParameterList().getParameters(); if (params.length == 0) return true; final Ref<Boolean> result = new Ref<Boolean>(); function.getStatementList().accept(new PyRecursiveElementVisitor() { public void visitPyAssignmentStatement(final PyAssignmentStatement node) { if (!result.isNull()) return; super.visitPyAssignmentStatement(node); final PyExpression[] targets = node.getTargets(); for(PyExpression target: targets) { if (target instanceof PyTargetExpression) { PyExpression qualifier = ((PyTargetExpression) target).getQualifier(); if (qualifier != null && qualifier.getText().equals(params [0].getName())) { if (!processor.execute(target, substitutor)) { result.set(Boolean.FALSE); } } } } } }); return result.isNull(); } public int getTextOffset() { final ASTNode name = findNameIdentifier(); return name != null ? name.getStartOffset() : super.getTextOffset(); } public String getDocString() { return DocStringAnnotator.findDocString(getStatementList()); } }
python/src/com/jetbrains/python/psi/impl/PyClassImpl.java
/* * Copyright 2005 Pythonid 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 com.jetbrains.python.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Icons; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.stubs.PyClassStub; import com.jetbrains.python.validation.DocStringAnnotator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: yole * Date: 03.06.2005 * Time: 0:27:33 * To change this template use File | Settings | File Templates. */ public class PyClassImpl extends PyPresentableElementImpl<PyClassStub> implements PyClass { public PyClassImpl(ASTNode astNode) { super(astNode); } public PyClassImpl(final PyClassStub stub) { super(stub, PyElementTypes.CLASS_DECLARATION); } public PsiElement setName(@NotNull String name) throws IncorrectOperationException { final ASTNode nameElement = getLanguage().getElementGenerator().createNameIdentifier(getProject(), name); getNode().replaceChild(findNameIdentifier(), nameElement); return this; } @Nullable @Override public String getName() { final PyClassStub stub = getStub(); if (stub != null) { return stub.getName(); } else { ASTNode node = findNameIdentifier(); return node != null ? node.getText() : null; } } private ASTNode findNameIdentifier() { return getNode().findChildByType(PyTokenTypes.IDENTIFIER); } @Override public Icon getIcon(int flags) { return Icons.CLASS_ICON; } @Override protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyClass(this); } @NotNull public PyStatementList getStatementList() { return childToPsiNotNull(PyElementTypes.STATEMENT_LIST); } @Nullable public PyExpression[] getSuperClassExpressions() { final PyParenthesizedExpression superExpression = PsiTreeUtil.getChildOfType(this, PyParenthesizedExpression.class); if (superExpression != null) { PyExpression expr = superExpression.getContainedExpression(); if (expr instanceof PyTupleExpression) { return ((PyTupleExpression) expr).getElements(); } if (expr != null) { return new PyExpression[] { expr }; } } return null; } public PsiElement[] getSuperClassElements() { final PyExpression[] superExpressions = getSuperClassExpressions(); if (superExpressions != null) { List<PsiElement> superClasses = new ArrayList<PsiElement>(); for(PyExpression expr: superExpressions) { if (expr instanceof PyReferenceExpression && !"object".equals(expr.getText())) { PyReferenceExpression ref = (PyReferenceExpression) expr; final PsiElement result = ref.resolve(); if (result != null) { superClasses.add(result); } } } return superClasses.toArray(new PsiElement[superClasses.size()]); } return null; } public PyClass[] getSuperClasses() { PsiElement[] superClassElements = getSuperClassElements(); if (superClassElements != null) { List<PyClass> result = new ArrayList<PyClass>(); for(PsiElement element: superClassElements) { if (element instanceof PyClass) { result.add((PyClass) element); } } return result.toArray(new PyClass[result.size()]); } return null; } @NotNull public PyFunction[] getMethods() { List<PyFunction> result = new ArrayList<PyFunction>(); final PyStatementList statementList = getStatementList(); for (PsiElement element : statementList.getChildren()) { if (element instanceof PyFunction) { result.add((PyFunction) element); } } return result.toArray(new PyFunction[result.size()]); } public PyFunction findMethodByName(@NotNull final String name) { PyFunction[] methods = getMethods(); for(PyFunction method: methods) { if (name.equals(method.getName())) { return method; } } return null; } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState substitutor, PsiElement lastParent, @NotNull PsiElement place) { final PyStatementList statementList = getStatementList(); for (PsiElement element : statementList.getChildren()) { if (element instanceof PyFunction) { final PyFunction function = (PyFunction)element; final String name = function.getName(); if ("__init__".equals(name)) { if (!processFields(processor, function, substitutor)) return false; } else { if (!processor.execute(element, substitutor)) return false; } } } for (PsiElement psiElement : statementList.getChildren()) { if (psiElement instanceof PyAssignmentStatement) { final PyAssignmentStatement assignmentStatement = (PyAssignmentStatement)psiElement; final PyExpression[] targets = assignmentStatement.getTargets(); for (PyExpression target : targets) { if (target instanceof PyTargetExpression) { if (!processor.execute(target, substitutor)) return false; } } } } if (processor instanceof PyResolveUtil.VariantsProcessor) { return true; } return processor.execute(this, substitutor); } private static boolean processFields(final PsiScopeProcessor processor, final PyFunction function, final ResolveState substitutor) { final PyParameter[] params = function.getParameterList().getParameters(); if (params.length == 0) return true; final Ref<Boolean> result = new Ref<Boolean>(); function.getStatementList().accept(new PyRecursiveElementVisitor() { public void visitPyAssignmentStatement(final PyAssignmentStatement node) { if (!result.isNull()) return; super.visitPyAssignmentStatement(node); final PyExpression[] targets = node.getTargets(); for(PyExpression target: targets) { if (target instanceof PyTargetExpression) { PyExpression qualifier = ((PyTargetExpression) target).getQualifier(); if (qualifier != null && qualifier.getText().equals(params [0].getName())) { if (!processor.execute(target, substitutor)) { result.set(Boolean.FALSE); } } } } } }); return result.isNull(); } public int getTextOffset() { final ASTNode name = findNameIdentifier(); return name != null ? name.getStartOffset() : super.getTextOffset(); } public String getDocString() { return DocStringAnnotator.findDocString(getStatementList()); } }
do not skip __init__ method when resolving
python/src/com/jetbrains/python/psi/impl/PyClassImpl.java
do not skip __init__ method when resolving
<ide><path>ython/src/com/jetbrains/python/psi/impl/PyClassImpl.java <ide> PsiElement lastParent, <ide> @NotNull PsiElement place) { <ide> final PyStatementList statementList = getStatementList(); <del> for (PsiElement element : statementList.getChildren()) { <del> if (element instanceof PyFunction) { <del> final PyFunction function = (PyFunction)element; <del> final String name = function.getName(); <del> if ("__init__".equals(name)) { <del> if (!processFields(processor, function, substitutor)) return false; <del> } <del> else { <del> if (!processor.execute(element, substitutor)) return false; <del> } <add> for(PyFunction func: getMethods()) { <add> if (!processor.execute(func, substitutor)) return false; <add> if ("__init__".equals(func.getName())) { <add> if (!processFields(processor, func, substitutor)) return false; <ide> } <ide> } <ide> for (PsiElement psiElement : statementList.getChildren()) {
Java
apache-2.0
2da7957b6788114765396ffe9b403bf39a2d0b6c
0
Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([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 org.jkiss.dbeaver.ext.postgresql.model; import org.eclipse.core.runtime.IAdaptable; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.ext.postgresql.PostgreConstants; import org.jkiss.dbeaver.ext.postgresql.PostgreDataSourceProvider; import org.jkiss.dbeaver.ext.postgresql.PostgreServerType; import org.jkiss.dbeaver.ext.postgresql.PostgreUtils; import org.jkiss.dbeaver.ext.postgresql.model.jdbc.PostgreJdbcFactory; import org.jkiss.dbeaver.ext.postgresql.model.plan.PostgrePlanAnalyser; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.connection.DBPDriver; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.exec.jdbc.*; import org.jkiss.dbeaver.model.exec.plan.DBCPlan; import org.jkiss.dbeaver.model.exec.plan.DBCPlanStyle; import org.jkiss.dbeaver.model.exec.plan.DBCQueryPlanner; import org.jkiss.dbeaver.model.impl.AsyncServerOutputReader; import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource; import org.jkiss.dbeaver.model.impl.jdbc.JDBCExecutionContext; import org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCObjectLookupCache; import org.jkiss.dbeaver.model.impl.sql.QueryTransformerLimit; import org.jkiss.dbeaver.model.net.DBWHandlerConfiguration; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLState; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.runtime.net.DefaultCallbackHandler; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.BeanUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * PostgreDataSource */ public class PostgreDataSource extends JDBCDataSource implements DBSObjectSelector, DBSInstanceContainer, DBCQueryPlanner, IAdaptable { private static final Log log = Log.getLog(PostgreDataSource.class); private DatabaseCache databaseCache; private String activeDatabaseName; private PostgreServerType serverType; public PostgreDataSource(DBRProgressMonitor monitor, DBPDataSourceContainer container) throws DBException { super(monitor, container, new PostgreDialect()); } @Override protected void initializeRemoteInstance(DBRProgressMonitor monitor) throws DBException { activeDatabaseName = getContainer().getConnectionConfiguration().getDatabaseName(); databaseCache = new DatabaseCache(); DBPConnectionConfiguration configuration = getContainer().getActualConnectionConfiguration(); final boolean showNDD = CommonUtils.toBoolean(configuration.getProviderProperty(PostgreConstants.PROP_SHOW_NON_DEFAULT_DB)) && !CommonUtils.isEmpty(configuration.getDatabaseName()); List<PostgreDatabase> dbList = new ArrayList<>(); if (!showNDD) { if (CommonUtils.isEmpty(activeDatabaseName)) { activeDatabaseName = PostgreConstants.DEFAULT_DATABASE; } PostgreDatabase defDatabase = new PostgreDatabase(monitor, this, activeDatabaseName); dbList.add(defDatabase); } else { // Make initial connection to read database list final boolean showTemplates = CommonUtils.toBoolean(configuration.getProviderProperty(PostgreConstants.PROP_SHOW_TEMPLATES_DB)); StringBuilder catalogQuery = new StringBuilder( "SELECT db.oid,db.*" + "\nFROM pg_catalog.pg_database db WHERE datallowconn "); if (!showTemplates) { catalogQuery.append(" AND NOT datistemplate "); } DBSObjectFilter catalogFilters = getContainer().getObjectFilter(PostgreDatabase.class, null, false); if (catalogFilters != null) { JDBCUtils.appendFilterClause(catalogQuery, catalogFilters, "datname", false); } catalogQuery.append("\nORDER BY db.datname"); try (Connection bootstrapConnection = openConnection(monitor, null, "Read PostgreSQL database list")) { try (PreparedStatement dbStat = bootstrapConnection.prepareStatement(catalogQuery.toString())) { if (catalogFilters != null) { JDBCUtils.setFilterParameters(dbStat, 1, catalogFilters); } try (ResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { PostgreDatabase database = new PostgreDatabase(monitor, this, dbResult); dbList.add(database); } } } if (activeDatabaseName == null) { try (PreparedStatement stat = bootstrapConnection.prepareStatement("SELECT current_database()")) { try (ResultSet rs = stat.executeQuery()) { if (rs.next()) { activeDatabaseName = JDBCUtils.safeGetString(rs, 1); } } } } } catch (SQLException e) { throw new DBException("Can't connect ot remote PostgreSQL server", e); } } databaseCache.setCache(dbList); // Initiate default context getDefaultInstance().checkDatabaseConnection(monitor); } @Override protected Map<String, String> getInternalConnectionProperties(DBRProgressMonitor monitor, DBPDriver driver, String purpose, DBPConnectionConfiguration connectionInfo) throws DBCException { Map<String, String> props = new LinkedHashMap<>(PostgreDataSourceProvider.getConnectionsProps()); final DBWHandlerConfiguration sslConfig = getContainer().getActualConnectionConfiguration().getDeclaredHandler(PostgreConstants.HANDLER_SSL); if (sslConfig != null && sslConfig.isEnabled()) { try { initSSL(props, sslConfig); } catch (Exception e) { throw new DBCException("Error configuring SSL certificates", e); } } return props; } private void initSSL(Map<String, String> props, DBWHandlerConfiguration sslConfig) throws Exception { props.put("ssl", "true"); final String rootCertProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_ROOT_CERT); if (!CommonUtils.isEmpty(rootCertProp)) { props.put("sslrootcert", rootCertProp); } final String clientCertProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_CLIENT_CERT); if (!CommonUtils.isEmpty(clientCertProp)) { props.put("sslcert", clientCertProp); } final String keyCertProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_CLIENT_KEY); if (!CommonUtils.isEmpty(keyCertProp)) { props.put("sslkey", keyCertProp); } final String modeProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_MODE); if (!CommonUtils.isEmpty(modeProp)) { props.put("sslmode", modeProp); } final String factoryProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_FACTORY); if (!CommonUtils.isEmpty(factoryProp)) { props.put("sslfactory", factoryProp); } props.put("sslpasswordcallback", DefaultCallbackHandler.class.getName()); } @Override public Object getDataSourceFeature(String featureId) { if (DBConstants.FEATURE_LOB_REQUIRE_TRANSACTIONS.equals(featureId)) { return true; } return super.getDataSourceFeature(featureId); } protected void initializeContextState(@NotNull DBRProgressMonitor monitor, @NotNull JDBCExecutionContext context, boolean setActiveObject) throws DBCException { if (setActiveObject) { PostgreDatabase activeDatabase = getDefaultObject(); if (activeDatabase != null) { final PostgreSchema activeSchema = activeDatabase.getDefaultObject(); if (activeSchema != null) { // Check default active schema String curDefSchema; try (JDBCSession session = context.openSession(monitor, DBCExecutionPurpose.META, "Get context active schema")) { curDefSchema = JDBCUtils.queryString(session, "SELECT current_schema()"); } catch (SQLException e) { throw new DBCException(e, getDataSource()); } if (curDefSchema == null || !curDefSchema.equals(activeSchema.getName())) { activeDatabase.setSearchPath(monitor, activeSchema, context); } } } } } public DatabaseCache getDatabaseCache() { return databaseCache; } public Collection<PostgreDatabase> getDatabases() { return databaseCache.getCachedObjects(); } public PostgreDatabase getDatabase(String name) { return databaseCache.getCachedObject(name); } @Override public void initialize(@NotNull DBRProgressMonitor monitor) throws DBException { super.initialize(monitor); // Read databases getDefaultInstance().cacheDataTypes(monitor, true); } @Override public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException { super.refreshObject(monitor); shutdown(monitor); this.databaseCache.clearCache(); this.activeDatabaseName = null; this.initializeRemoteInstance(monitor); this.initialize(monitor); return this; } @Override public Collection<? extends PostgreDatabase> getChildren(@NotNull DBRProgressMonitor monitor) throws DBException { return getDatabases(); } @Override public PostgreDatabase getChild(@NotNull DBRProgressMonitor monitor, @NotNull String childName) throws DBException { return getDatabase(childName); } @Override public Class<? extends PostgreDatabase> getChildType(@NotNull DBRProgressMonitor monitor) throws DBException { return PostgreDatabase.class; } @Override public void cacheStructure(@NotNull DBRProgressMonitor monitor, int scope) throws DBException { databaseCache.getAllObjects(monitor, this); } @Override public boolean supportsDefaultChange() { return true; } //////////////////////////////////////////////////// // Default schema and search path @Override public PostgreDatabase getDefaultObject() { return getDefaultInstance(); } @Override public void setDefaultObject(@NotNull DBRProgressMonitor monitor, @NotNull DBSObject object) throws DBException { final PostgreDatabase oldDatabase = getDefaultObject(); if (!(object instanceof PostgreDatabase)) { throw new IllegalArgumentException("Invalid object type: " + object); } final PostgreDatabase newDatabase = (PostgreDatabase) object; if (oldDatabase == newDatabase) { // The same return; } activeDatabaseName = object.getName(); getDefaultInstance().initializeMetaContext(monitor); getDefaultInstance().cacheDataTypes(monitor, false); // Notify UI if (oldDatabase != null) { DBUtils.fireObjectSelect(oldDatabase, false); } DBUtils.fireObjectSelect(newDatabase, true); } @Override public boolean refreshDefaultObject(@NotNull DBCSession session) throws DBException { return true; } //////////////////////////////////////////// // Connections @Override protected Connection openConnection(@NotNull DBRProgressMonitor monitor, JDBCRemoteInstance remoteInstance, @NotNull String purpose) throws DBCException { final DBPConnectionConfiguration conConfig = getContainer().getActualConnectionConfiguration(); Connection pgConnection; if (remoteInstance != null) { log.debug("Initiate connection to " + getServerType().getName() + " database [" + remoteInstance.getName() + "@" + conConfig.getHostName() + "]"); } if (remoteInstance instanceof PostgreDatabase && remoteInstance.getName() != null && !CommonUtils.equalObjects(remoteInstance.getName(), conConfig.getDatabaseName())) { // If database was changed then use new name for connection final DBPConnectionConfiguration originalConfig = new DBPConnectionConfiguration(conConfig); try { // Patch URL with new database name conConfig.setDatabaseName(remoteInstance.getName()); conConfig.setUrl(getContainer().getDriver().getDataSourceProvider().getConnectionURL(getContainer().getDriver(), conConfig)); pgConnection = super.openConnection(monitor, remoteInstance, purpose); } finally { conConfig.setDatabaseName(originalConfig.getDatabaseName()); conConfig.setUrl(originalConfig.getUrl()); } } else { pgConnection = super.openConnection(monitor, remoteInstance, purpose); } if (getServerType() != PostgreServerType.REDSHIFT && !getContainer().getPreferenceStore().getBoolean(ModelPreferences.META_CLIENT_NAME_DISABLE)) { // Provide client info. Not supported by Redshift? try { pgConnection.setClientInfo("ApplicationName", DBUtils.getClientApplicationName(getContainer(), purpose)); } catch (Throwable e) { // just ignore log.debug(e); } } return pgConnection; } //////////////////////////////////////////// // Explain plan @NotNull @Override public DBCPlan planQueryExecution(@NotNull DBCSession session, @NotNull String query) throws DBCException { PostgrePlanAnalyser plan = new PostgrePlanAnalyser(getPlanStyle() == DBCPlanStyle.QUERY, query); if (getPlanStyle() == DBCPlanStyle.PLAN) { plan.explain(session); } return plan; } @NotNull @Override public DBCPlanStyle getPlanStyle() { return isServerVersionAtLeast(9, 0) ? DBCPlanStyle.PLAN : DBCPlanStyle.QUERY; } @Override public <T> T getAdapter(Class<T> adapter) { if (adapter == DBSStructureAssistant.class) { return adapter.cast(new PostgreStructureAssistant(this)); } else if (adapter == DBCServerOutputReader.class) { return adapter.cast(new AsyncServerOutputReader()); } return super.getAdapter(adapter); } @NotNull @Override public PostgreDataSource getDataSource() { return this; } @Override public Collection<PostgreDataType> getLocalDataTypes() { final PostgreSchema schema = getDefaultInstance().getCatalogSchema(); if (schema != null) { return schema.dataTypeCache.getCachedObjects(); } return null; } @Override public PostgreDataType getLocalDataType(String typeName) { return getDefaultInstance().getDataType(new VoidProgressMonitor(), typeName); } @Override public DBSDataType getLocalDataType(int typeID) { return getDefaultInstance().getDataType(new VoidProgressMonitor(), typeID); } @Override public String getDefaultDataTypeName(@NotNull DBPDataKind dataKind) { return PostgreUtils.getDefaultDataTypeName(dataKind); } @NotNull @Override public PostgreDatabase getDefaultInstance() { PostgreDatabase defDatabase = databaseCache.getCachedObject(activeDatabaseName); if (defDatabase == null) { defDatabase = databaseCache.getCachedObject(PostgreConstants.DEFAULT_DATABASE); } if (defDatabase == null) { final List<PostgreDatabase> allDatabases = databaseCache.getCachedObjects(); if (allDatabases.isEmpty()) { // Looks like we are not connected or in connection process right now - no instance then return null; } defDatabase = allDatabases.get(0); } return defDatabase; } @NotNull @Override public List<PostgreDatabase> getAvailableInstances() { return databaseCache.getCachedObjects(); } public List<String> getTemplateDatabases(DBRProgressMonitor monitor) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load template databases")) { try (PreparedStatement dbStat = session.prepareStatement("SELECT db.datname FROM pg_catalog.pg_database db WHERE datistemplate")) { try (ResultSet resultSet = dbStat.executeQuery()) { List<String> dbNames = new ArrayList<>(); while (resultSet.next()) { dbNames.add(resultSet.getString(1)); } return dbNames; } } } catch (Exception e) { throw new DBException("Error reading template databases", e); } } public PostgreServerType getServerType() { if (serverType == null) { serverType = PostgreUtils.getServerType(getContainer().getDriver()); } return serverType; } class DatabaseCache extends JDBCObjectLookupCache<PostgreDataSource, PostgreDatabase> { @Override protected PostgreDatabase fetchObject(@NotNull JDBCSession session, @NotNull PostgreDataSource owner, @NotNull JDBCResultSet resultSet) throws SQLException, DBException { return new PostgreDatabase(session.getProgressMonitor(), owner, resultSet); } @Override public JDBCStatement prepareLookupStatement(JDBCSession session, PostgreDataSource owner, PostgreDatabase object, String objectName) throws SQLException { final boolean showNDD = CommonUtils.toBoolean(getContainer().getActualConnectionConfiguration().getProviderProperty(PostgreConstants.PROP_SHOW_NON_DEFAULT_DB)); final boolean showTemplates = CommonUtils.toBoolean(getContainer().getActualConnectionConfiguration().getProviderProperty(PostgreConstants.PROP_SHOW_TEMPLATES_DB)); StringBuilder catalogQuery = new StringBuilder( "SELECT db.oid,db.*" + "\nFROM pg_catalog.pg_database db WHERE datallowconn "); if (!showTemplates) { catalogQuery.append(" AND NOT datistemplate "); } if (object != null) { catalogQuery.append("\nAND db.oid=?"); } else if (objectName != null || !showNDD) { catalogQuery.append("\nAND db.datname=?"); } DBSObjectFilter catalogFilters = owner.getContainer().getObjectFilter(PostgreDatabase.class, null, false); if (showNDD) { if (catalogFilters != null) { JDBCUtils.appendFilterClause(catalogQuery, catalogFilters, "datname", false); } catalogQuery.append("\nORDER BY db.datname"); } JDBCPreparedStatement dbStat = session.prepareStatement(catalogQuery.toString()); if (object != null) { dbStat.setLong(1, object.getObjectId()); } else if (objectName != null || !showNDD) { dbStat.setString(1, object != null ? object.getName() : (objectName != null ? objectName : activeDatabaseName)); } else if (catalogFilters != null) { JDBCUtils.setFilterParameters(dbStat, 1, catalogFilters); } return dbStat; } } private Pattern ERROR_POSITION_PATTERN = Pattern.compile("\\n\\s*\\p{L}+\\s*: ([0-9]+)"); @Nullable @Override public ErrorPosition[] getErrorPosition(@NotNull DBRProgressMonitor monitor, @NotNull DBCExecutionContext context, @NotNull String query, @NotNull Throwable error) { Throwable rootCause = GeneralUtils.getRootCause(error); if (rootCause != null && PostgreConstants.PSQL_EXCEPTION_CLASS_NAME.equals(rootCause.getClass().getName())) { try { Object serverErrorMessage = BeanUtils.readObjectProperty(rootCause, "serverErrorMessage"); if (serverErrorMessage != null) { Object position = BeanUtils.readObjectProperty(serverErrorMessage, "position"); if (position instanceof Number) { ErrorPosition pos = new ErrorPosition(); pos.position = ((Number) position).intValue(); return new ErrorPosition[] {pos}; } } } catch (Throwable e) { // Something went wrong. Doesn't matter, ignore it as we are already in error handling routine } } String message = error.getMessage(); if (!CommonUtils.isEmpty(message)) { Matcher matcher = ERROR_POSITION_PATTERN.matcher(message); if (matcher.find()) { DBPErrorAssistant.ErrorPosition pos = new DBPErrorAssistant.ErrorPosition(); pos.position = Integer.parseInt(matcher.group(1)) - 1; return new ErrorPosition[] {pos}; } } return null; } @NotNull @Override protected JDBCFactory createJdbcFactory() { return new PostgreJdbcFactory(); } @Override public ErrorType discoverErrorType(Throwable error) { String sqlState = SQLState.getStateFromException(error); if (sqlState != null) { if (PostgreConstants.ERROR_ADMIN_SHUTDOWN.equals(sqlState)) { return ErrorType.CONNECTION_LOST; } } return super.discoverErrorType(error); } @Override protected DBPDataSourceInfo createDataSourceInfo(@NotNull JDBCDatabaseMetaData metaData) { return new PostgreDataSourceInfo(metaData); } @Nullable @Override public DBCQueryTransformer createQueryTransformer(@NotNull DBCQueryTransformType type) { if (type == DBCQueryTransformType.RESULT_SET_LIMIT) { return new QueryTransformerLimit(false, true); } else if (type == DBCQueryTransformType.FETCH_ALL_TABLE) { return new QueryTransformerFetchAll(); } return null; } }
plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreDataSource.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([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 org.jkiss.dbeaver.ext.postgresql.model; import org.eclipse.core.runtime.IAdaptable; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.ext.postgresql.PostgreConstants; import org.jkiss.dbeaver.ext.postgresql.PostgreDataSourceProvider; import org.jkiss.dbeaver.ext.postgresql.PostgreServerType; import org.jkiss.dbeaver.ext.postgresql.PostgreUtils; import org.jkiss.dbeaver.ext.postgresql.model.jdbc.PostgreJdbcFactory; import org.jkiss.dbeaver.ext.postgresql.model.plan.PostgrePlanAnalyser; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration; import org.jkiss.dbeaver.model.connection.DBPDriver; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.exec.jdbc.*; import org.jkiss.dbeaver.model.exec.plan.DBCPlan; import org.jkiss.dbeaver.model.exec.plan.DBCPlanStyle; import org.jkiss.dbeaver.model.exec.plan.DBCQueryPlanner; import org.jkiss.dbeaver.model.impl.AsyncServerOutputReader; import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource; import org.jkiss.dbeaver.model.impl.jdbc.JDBCExecutionContext; import org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCObjectLookupCache; import org.jkiss.dbeaver.model.impl.sql.QueryTransformerLimit; import org.jkiss.dbeaver.model.net.DBWHandlerConfiguration; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLState; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.runtime.net.DefaultCallbackHandler; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.BeanUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * PostgreDataSource */ public class PostgreDataSource extends JDBCDataSource implements DBSObjectSelector, DBSInstanceContainer, DBCQueryPlanner, IAdaptable { private static final Log log = Log.getLog(PostgreDataSource.class); private DatabaseCache databaseCache; private String activeDatabaseName; private PostgreServerType serverType; public PostgreDataSource(DBRProgressMonitor monitor, DBPDataSourceContainer container) throws DBException { super(monitor, container, new PostgreDialect()); } @Override protected void initializeRemoteInstance(DBRProgressMonitor monitor) throws DBException { activeDatabaseName = getContainer().getConnectionConfiguration().getDatabaseName(); databaseCache = new DatabaseCache(); DBPConnectionConfiguration configuration = getContainer().getActualConnectionConfiguration(); final boolean showNDD = CommonUtils.toBoolean(configuration.getProviderProperty(PostgreConstants.PROP_SHOW_NON_DEFAULT_DB)) && !CommonUtils.isEmpty(configuration.getDatabaseName()); List<PostgreDatabase> dbList = new ArrayList<>(); if (!showNDD) { PostgreDatabase defDatabase = new PostgreDatabase(monitor, this, activeDatabaseName); dbList.add(defDatabase); } else { // Make initial connection to read database list final boolean showTemplates = CommonUtils.toBoolean(configuration.getProviderProperty(PostgreConstants.PROP_SHOW_TEMPLATES_DB)); StringBuilder catalogQuery = new StringBuilder( "SELECT db.oid,db.*" + "\nFROM pg_catalog.pg_database db WHERE datallowconn "); if (!showTemplates) { catalogQuery.append(" AND NOT datistemplate "); } DBSObjectFilter catalogFilters = getContainer().getObjectFilter(PostgreDatabase.class, null, false); if (catalogFilters != null) { JDBCUtils.appendFilterClause(catalogQuery, catalogFilters, "datname", false); } catalogQuery.append("\nORDER BY db.datname"); try (Connection bootstrapConnection = openConnection(monitor, null, "Read PostgreSQL database list")) { try (PreparedStatement dbStat = bootstrapConnection.prepareStatement(catalogQuery.toString())) { if (catalogFilters != null) { JDBCUtils.setFilterParameters(dbStat, 1, catalogFilters); } try (ResultSet dbResult = dbStat.executeQuery()) { while (dbResult.next()) { PostgreDatabase database = new PostgreDatabase(monitor, this, dbResult); dbList.add(database); } } } if (activeDatabaseName == null) { try (PreparedStatement stat = bootstrapConnection.prepareStatement("SELECT current_database()")) { try (ResultSet rs = stat.executeQuery()) { if (rs.next()) { activeDatabaseName = JDBCUtils.safeGetString(rs, 1); } } } } } catch (SQLException e) { throw new DBException("Can't connect ot remote PostgreSQL server", e); } } databaseCache.setCache(dbList); // Initiate default context getDefaultInstance().checkDatabaseConnection(monitor); } @Override protected Map<String, String> getInternalConnectionProperties(DBRProgressMonitor monitor, DBPDriver driver, String purpose, DBPConnectionConfiguration connectionInfo) throws DBCException { Map<String, String> props = new LinkedHashMap<>(PostgreDataSourceProvider.getConnectionsProps()); final DBWHandlerConfiguration sslConfig = getContainer().getActualConnectionConfiguration().getDeclaredHandler(PostgreConstants.HANDLER_SSL); if (sslConfig != null && sslConfig.isEnabled()) { try { initSSL(props, sslConfig); } catch (Exception e) { throw new DBCException("Error configuring SSL certificates", e); } } return props; } private void initSSL(Map<String, String> props, DBWHandlerConfiguration sslConfig) throws Exception { props.put("ssl", "true"); final String rootCertProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_ROOT_CERT); if (!CommonUtils.isEmpty(rootCertProp)) { props.put("sslrootcert", rootCertProp); } final String clientCertProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_CLIENT_CERT); if (!CommonUtils.isEmpty(clientCertProp)) { props.put("sslcert", clientCertProp); } final String keyCertProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_CLIENT_KEY); if (!CommonUtils.isEmpty(keyCertProp)) { props.put("sslkey", keyCertProp); } final String modeProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_MODE); if (!CommonUtils.isEmpty(modeProp)) { props.put("sslmode", modeProp); } final String factoryProp = sslConfig.getProperties().get(PostgreConstants.PROP_SSL_FACTORY); if (!CommonUtils.isEmpty(factoryProp)) { props.put("sslfactory", factoryProp); } props.put("sslpasswordcallback", DefaultCallbackHandler.class.getName()); } @Override public Object getDataSourceFeature(String featureId) { if (DBConstants.FEATURE_LOB_REQUIRE_TRANSACTIONS.equals(featureId)) { return true; } return super.getDataSourceFeature(featureId); } protected void initializeContextState(@NotNull DBRProgressMonitor monitor, @NotNull JDBCExecutionContext context, boolean setActiveObject) throws DBCException { if (setActiveObject) { PostgreDatabase activeDatabase = getDefaultObject(); if (activeDatabase != null) { final PostgreSchema activeSchema = activeDatabase.getDefaultObject(); if (activeSchema != null) { // Check default active schema String curDefSchema; try (JDBCSession session = context.openSession(monitor, DBCExecutionPurpose.META, "Get context active schema")) { curDefSchema = JDBCUtils.queryString(session, "SELECT current_schema()"); } catch (SQLException e) { throw new DBCException(e, getDataSource()); } if (curDefSchema == null || !curDefSchema.equals(activeSchema.getName())) { activeDatabase.setSearchPath(monitor, activeSchema, context); } } } } } public DatabaseCache getDatabaseCache() { return databaseCache; } public Collection<PostgreDatabase> getDatabases() { return databaseCache.getCachedObjects(); } public PostgreDatabase getDatabase(String name) { return databaseCache.getCachedObject(name); } @Override public void initialize(@NotNull DBRProgressMonitor monitor) throws DBException { super.initialize(monitor); // Read databases getDefaultInstance().cacheDataTypes(monitor, true); } @Override public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException { super.refreshObject(monitor); shutdown(monitor); this.databaseCache.clearCache(); this.activeDatabaseName = null; this.initializeRemoteInstance(monitor); this.initialize(monitor); return this; } @Override public Collection<? extends PostgreDatabase> getChildren(@NotNull DBRProgressMonitor monitor) throws DBException { return getDatabases(); } @Override public PostgreDatabase getChild(@NotNull DBRProgressMonitor monitor, @NotNull String childName) throws DBException { return getDatabase(childName); } @Override public Class<? extends PostgreDatabase> getChildType(@NotNull DBRProgressMonitor monitor) throws DBException { return PostgreDatabase.class; } @Override public void cacheStructure(@NotNull DBRProgressMonitor monitor, int scope) throws DBException { databaseCache.getAllObjects(monitor, this); } @Override public boolean supportsDefaultChange() { return true; } //////////////////////////////////////////////////// // Default schema and search path @Override public PostgreDatabase getDefaultObject() { return getDefaultInstance(); } @Override public void setDefaultObject(@NotNull DBRProgressMonitor monitor, @NotNull DBSObject object) throws DBException { final PostgreDatabase oldDatabase = getDefaultObject(); if (!(object instanceof PostgreDatabase)) { throw new IllegalArgumentException("Invalid object type: " + object); } final PostgreDatabase newDatabase = (PostgreDatabase) object; if (oldDatabase == newDatabase) { // The same return; } activeDatabaseName = object.getName(); getDefaultInstance().initializeMetaContext(monitor); getDefaultInstance().cacheDataTypes(monitor, false); // Notify UI if (oldDatabase != null) { DBUtils.fireObjectSelect(oldDatabase, false); } DBUtils.fireObjectSelect(newDatabase, true); } @Override public boolean refreshDefaultObject(@NotNull DBCSession session) throws DBException { return true; } //////////////////////////////////////////// // Connections @Override protected Connection openConnection(@NotNull DBRProgressMonitor monitor, JDBCRemoteInstance remoteInstance, @NotNull String purpose) throws DBCException { final DBPConnectionConfiguration conConfig = getContainer().getActualConnectionConfiguration(); Connection pgConnection; if (remoteInstance != null) { log.debug("Initiate connection to " + getServerType().getName() + " database [" + remoteInstance.getName() + "@" + conConfig.getHostName() + "]"); } if (remoteInstance instanceof PostgreDatabase && remoteInstance.getName() != null && !CommonUtils.equalObjects(remoteInstance.getName(), conConfig.getDatabaseName())) { // If database was changed then use new name for connection final DBPConnectionConfiguration originalConfig = new DBPConnectionConfiguration(conConfig); try { // Patch URL with new database name conConfig.setDatabaseName(remoteInstance.getName()); conConfig.setUrl(getContainer().getDriver().getDataSourceProvider().getConnectionURL(getContainer().getDriver(), conConfig)); pgConnection = super.openConnection(monitor, remoteInstance, purpose); } finally { conConfig.setDatabaseName(originalConfig.getDatabaseName()); conConfig.setUrl(originalConfig.getUrl()); } } else { pgConnection = super.openConnection(monitor, remoteInstance, purpose); } if (getServerType() != PostgreServerType.REDSHIFT && !getContainer().getPreferenceStore().getBoolean(ModelPreferences.META_CLIENT_NAME_DISABLE)) { // Provide client info. Not supported by Redshift? try { pgConnection.setClientInfo("ApplicationName", DBUtils.getClientApplicationName(getContainer(), purpose)); } catch (Throwable e) { // just ignore log.debug(e); } } return pgConnection; } //////////////////////////////////////////// // Explain plan @NotNull @Override public DBCPlan planQueryExecution(@NotNull DBCSession session, @NotNull String query) throws DBCException { PostgrePlanAnalyser plan = new PostgrePlanAnalyser(getPlanStyle() == DBCPlanStyle.QUERY, query); if (getPlanStyle() == DBCPlanStyle.PLAN) { plan.explain(session); } return plan; } @NotNull @Override public DBCPlanStyle getPlanStyle() { return isServerVersionAtLeast(9, 0) ? DBCPlanStyle.PLAN : DBCPlanStyle.QUERY; } @Override public <T> T getAdapter(Class<T> adapter) { if (adapter == DBSStructureAssistant.class) { return adapter.cast(new PostgreStructureAssistant(this)); } else if (adapter == DBCServerOutputReader.class) { return adapter.cast(new AsyncServerOutputReader()); } return super.getAdapter(adapter); } @NotNull @Override public PostgreDataSource getDataSource() { return this; } @Override public Collection<PostgreDataType> getLocalDataTypes() { final PostgreSchema schema = getDefaultInstance().getCatalogSchema(); if (schema != null) { return schema.dataTypeCache.getCachedObjects(); } return null; } @Override public PostgreDataType getLocalDataType(String typeName) { return getDefaultInstance().getDataType(new VoidProgressMonitor(), typeName); } @Override public DBSDataType getLocalDataType(int typeID) { return getDefaultInstance().getDataType(new VoidProgressMonitor(), typeID); } @Override public String getDefaultDataTypeName(@NotNull DBPDataKind dataKind) { return PostgreUtils.getDefaultDataTypeName(dataKind); } @NotNull @Override public PostgreDatabase getDefaultInstance() { PostgreDatabase defDatabase = databaseCache.getCachedObject(activeDatabaseName); if (defDatabase == null) { defDatabase = databaseCache.getCachedObject(PostgreConstants.DEFAULT_DATABASE); } if (defDatabase == null) { final List<PostgreDatabase> allDatabases = databaseCache.getCachedObjects(); if (allDatabases.isEmpty()) { // Looks like we are not connected or in connection process right now - no instance then return null; } defDatabase = allDatabases.get(0); } return defDatabase; } @NotNull @Override public List<PostgreDatabase> getAvailableInstances() { return databaseCache.getCachedObjects(); } public List<String> getTemplateDatabases(DBRProgressMonitor monitor) throws DBException { try (JDBCSession session = DBUtils.openMetaSession(monitor, this, "Load template databases")) { try (PreparedStatement dbStat = session.prepareStatement("SELECT db.datname FROM pg_catalog.pg_database db WHERE datistemplate")) { try (ResultSet resultSet = dbStat.executeQuery()) { List<String> dbNames = new ArrayList<>(); while (resultSet.next()) { dbNames.add(resultSet.getString(1)); } return dbNames; } } } catch (Exception e) { throw new DBException("Error reading template databases", e); } } public PostgreServerType getServerType() { if (serverType == null) { serverType = PostgreUtils.getServerType(getContainer().getDriver()); } return serverType; } class DatabaseCache extends JDBCObjectLookupCache<PostgreDataSource, PostgreDatabase> { @Override protected PostgreDatabase fetchObject(@NotNull JDBCSession session, @NotNull PostgreDataSource owner, @NotNull JDBCResultSet resultSet) throws SQLException, DBException { return new PostgreDatabase(session.getProgressMonitor(), owner, resultSet); } @Override public JDBCStatement prepareLookupStatement(JDBCSession session, PostgreDataSource owner, PostgreDatabase object, String objectName) throws SQLException { final boolean showNDD = CommonUtils.toBoolean(getContainer().getActualConnectionConfiguration().getProviderProperty(PostgreConstants.PROP_SHOW_NON_DEFAULT_DB)); final boolean showTemplates = CommonUtils.toBoolean(getContainer().getActualConnectionConfiguration().getProviderProperty(PostgreConstants.PROP_SHOW_TEMPLATES_DB)); StringBuilder catalogQuery = new StringBuilder( "SELECT db.oid,db.*" + "\nFROM pg_catalog.pg_database db WHERE datallowconn "); if (!showTemplates) { catalogQuery.append(" AND NOT datistemplate "); } if (object != null) { catalogQuery.append("\nAND db.oid=?"); } else if (objectName != null || !showNDD) { catalogQuery.append("\nAND db.datname=?"); } DBSObjectFilter catalogFilters = owner.getContainer().getObjectFilter(PostgreDatabase.class, null, false); if (showNDD) { if (catalogFilters != null) { JDBCUtils.appendFilterClause(catalogQuery, catalogFilters, "datname", false); } catalogQuery.append("\nORDER BY db.datname"); } JDBCPreparedStatement dbStat = session.prepareStatement(catalogQuery.toString()); if (object != null) { dbStat.setLong(1, object.getObjectId()); } else if (objectName != null || !showNDD) { dbStat.setString(1, object != null ? object.getName() : (objectName != null ? objectName : activeDatabaseName)); } else if (catalogFilters != null) { JDBCUtils.setFilterParameters(dbStat, 1, catalogFilters); } return dbStat; } } private Pattern ERROR_POSITION_PATTERN = Pattern.compile("\\n\\s*\\p{L}+\\s*: ([0-9]+)"); @Nullable @Override public ErrorPosition[] getErrorPosition(@NotNull DBRProgressMonitor monitor, @NotNull DBCExecutionContext context, @NotNull String query, @NotNull Throwable error) { Throwable rootCause = GeneralUtils.getRootCause(error); if (rootCause != null && PostgreConstants.PSQL_EXCEPTION_CLASS_NAME.equals(rootCause.getClass().getName())) { try { Object serverErrorMessage = BeanUtils.readObjectProperty(rootCause, "serverErrorMessage"); if (serverErrorMessage != null) { Object position = BeanUtils.readObjectProperty(serverErrorMessage, "position"); if (position instanceof Number) { ErrorPosition pos = new ErrorPosition(); pos.position = ((Number) position).intValue(); return new ErrorPosition[] {pos}; } } } catch (Throwable e) { // Something went wrong. Doesn't matter, ignore it as we are already in error handling routine } } String message = error.getMessage(); if (!CommonUtils.isEmpty(message)) { Matcher matcher = ERROR_POSITION_PATTERN.matcher(message); if (matcher.find()) { DBPErrorAssistant.ErrorPosition pos = new DBPErrorAssistant.ErrorPosition(); pos.position = Integer.parseInt(matcher.group(1)) - 1; return new ErrorPosition[] {pos}; } } return null; } @NotNull @Override protected JDBCFactory createJdbcFactory() { return new PostgreJdbcFactory(); } @Override public ErrorType discoverErrorType(Throwable error) { String sqlState = SQLState.getStateFromException(error); if (sqlState != null) { if (PostgreConstants.ERROR_ADMIN_SHUTDOWN.equals(sqlState)) { return ErrorType.CONNECTION_LOST; } } return super.discoverErrorType(error); } @Override protected DBPDataSourceInfo createDataSourceInfo(@NotNull JDBCDatabaseMetaData metaData) { return new PostgreDataSourceInfo(metaData); } @Nullable @Override public DBCQueryTransformer createQueryTransformer(@NotNull DBCQueryTransformType type) { if (type == DBCQueryTransformType.RESULT_SET_LIMIT) { return new QueryTransformerLimit(false, true); } else if (type == DBCQueryTransformType.FETCH_ALL_TABLE) { return new QueryTransformerFetchAll(); } return null; } }
PG: use default database name if no database specified in connection props Former-commit-id: 7f93035ed2cd4f799267fbd939aaa950edf350bd
plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreDataSource.java
PG: use default database name if no database specified in connection props
<ide><path>lugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreDataSource.java <ide> final boolean showNDD = CommonUtils.toBoolean(configuration.getProviderProperty(PostgreConstants.PROP_SHOW_NON_DEFAULT_DB)) && !CommonUtils.isEmpty(configuration.getDatabaseName()); <ide> List<PostgreDatabase> dbList = new ArrayList<>(); <ide> if (!showNDD) { <add> if (CommonUtils.isEmpty(activeDatabaseName)) { <add> activeDatabaseName = PostgreConstants.DEFAULT_DATABASE; <add> } <ide> PostgreDatabase defDatabase = new PostgreDatabase(monitor, this, activeDatabaseName); <ide> dbList.add(defDatabase); <ide> } else {
Java
apache-2.0
a845b658aa54c4049dde0887be0469422ad69104
0
incodehq/ecpcrm,incodehq/ecpcrm,incodehq/ecpcrm,incodehq/ecpcrm
package org.incode.eurocommercial.ecpcrm.module.api.service.vm.websiteusercarddisable; import com.google.common.base.Strings; import com.google.gson.annotations.SerializedName; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import org.incode.eurocommercial.ecpcrm.module.api.dom.authentication.AuthenticationDevice; import org.incode.eurocommercial.ecpcrm.module.api.service.ApiService; import org.incode.eurocommercial.ecpcrm.module.api.service.Result; import org.incode.eurocommercial.ecpcrm.module.api.service.vm.AbstractRequestViewModel; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.Card; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.CardRepository; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.CardStatus; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.request.CardRequest; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.User; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.UserRepository; import javax.inject.Inject; @NoArgsConstructor(force = true) @AllArgsConstructor public class WebsiteUserCardDisableRequestViewModel extends AbstractRequestViewModel { @Getter @SerializedName("check_code") private final String checkCode; @Getter private final String email; @Override public Result isValid(AuthenticationDevice device, User user){ if (Strings.isNullOrEmpty(getCheckCode()) || Strings.isNullOrEmpty(getEmail())) { return Result.error(Result.STATUS_INVALID_PARAMETER, "Invalid parameter"); } user = userRepository.findByExactEmailAndCenter(getEmail(), device.getCenter()); if(user == null){ return Result.error(Result.STATUS_INVALID_USER, "Invalid user"); } if (!getCheckCode().equals(ApiService.computeCheckCode(getEmail()))) { return Result.error(Result.STATUS_INCORRECT_CHECK_CODE, "Incorrect check code"); } for (Card card : user.getCards()){ card.setStatus(CardStatus.DISABLED); } CardRequest cardRequestForUser = user.getOpenCardRequest(); if(cardRequestForUser != null){ cardRequestForUser.deny(); } return Result.ok(); } @Inject UserRepository userRepository; @Inject CardRepository cardRepository; }
application/src/main/java/org/incode/eurocommercial/ecpcrm/module/api/service/vm/websiteusercarddisable/WebsiteUserCardDisableRequestViewModel.java
package org.incode.eurocommercial.ecpcrm.module.api.service.vm.websiteusercarddisable; import com.google.common.base.Strings; import com.google.gson.annotations.SerializedName; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import org.incode.eurocommercial.ecpcrm.module.api.dom.authentication.AuthenticationDevice; import org.incode.eurocommercial.ecpcrm.module.api.service.ApiService; import org.incode.eurocommercial.ecpcrm.module.api.service.Result; import org.incode.eurocommercial.ecpcrm.module.api.service.vm.AbstractRequestViewModel; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.Card; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.CardRepository; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.CardStatus; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.User; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.UserRepository; import javax.inject.Inject; @NoArgsConstructor(force = true) @AllArgsConstructor public class WebsiteUserCardDisableRequestViewModel extends AbstractRequestViewModel { @Getter @SerializedName("check_code") private final String checkCode; @Getter private final String email; @Override public Result isValid(AuthenticationDevice device, User user){ if (Strings.isNullOrEmpty(getCheckCode()) || Strings.isNullOrEmpty(getEmail())) { return Result.error(Result.STATUS_INVALID_PARAMETER, "Invalid parameter"); } user = userRepository.findByExactEmailAndCenter(getEmail(), device.getCenter()); if(user == null){ return Result.error(Result.STATUS_INVALID_USER, "Invalid user"); } if (!getCheckCode().equals(ApiService.computeCheckCode(getEmail()))) { return Result.error(Result.STATUS_INCORRECT_CHECK_CODE, "Incorrect check code"); } for (Card card : user.getCards()){ card.setStatus(CardStatus.DISABLED); } return Result.ok(); } @Inject UserRepository userRepository; @Inject CardRepository cardRepository; }
ECPCRM-202: also closes any requests when a user disabled their account.
application/src/main/java/org/incode/eurocommercial/ecpcrm/module/api/service/vm/websiteusercarddisable/WebsiteUserCardDisableRequestViewModel.java
ECPCRM-202: also closes any requests when a user disabled their account.
<ide><path>pplication/src/main/java/org/incode/eurocommercial/ecpcrm/module/api/service/vm/websiteusercarddisable/WebsiteUserCardDisableRequestViewModel.java <ide> import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.Card; <ide> import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.CardRepository; <ide> import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.CardStatus; <add>import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.card.request.CardRequest; <ide> import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.User; <ide> import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.UserRepository; <ide> <ide> card.setStatus(CardStatus.DISABLED); <ide> } <ide> <add> CardRequest cardRequestForUser = user.getOpenCardRequest(); <add> if(cardRequestForUser != null){ <add> cardRequestForUser.deny(); <add> } <add> <ide> return Result.ok(); <ide> } <ide>
JavaScript
mit
34ba14d4c80be60eafd5fb0068f21c889730e403
0
jeffrey-hearn/poisson-disk-sample
// Constants var CANVAS_WIDTH = 700 , CANVAS_HEIGHT = 500; // Add canvas to page var canvasElement = $("<canvas width='" + CANVAS_WIDTH + "' height='" + CANVAS_HEIGHT + "'></canvas>"); var canvas = canvasElement.get(0).getContext("2d"); canvasElement.appendTo('body'); function PoissonDiskSampler( width, height, minDistance, sampleFrequency ){ this.grid = new Grid( width, height, minDistance ); this.outputList = new Array(); this.processingQueue = new RandomQueue(); // Generate first point this.queueToAll( this.grid.randomPoint() ); } PoissonDiskSampler.prototype.queueToAll = function ( point ){ this.processingQueue.push( point ); this.outputList.push( point ); this.grid.addPointToGrid( point, this.grid.pixelsToGridCoords( point ) ); } PoissonDiskSampler.prototype.drawOutputList = function( canvas ){ for ( var i = 0; i < this.outputList.length; i++ ){ this.grid.drawPoint( this.outputList[ i ], "#aaa", canvas ); } } function Grid( width, height, minDistance ){ this.width = width; this.height = height; this.minDistance = minDistance; this.cellSize = this.minDistance / Math.SQRT2; console.log( this.cellSize ); this.cellsWide = Math.ceil( this.width / this.cellSize ); this.cellsHigh = Math.ceil( this.height / this.cellSize ); // Initialize grid this.grid = []; for ( var x = 0; x < this.cellsWide; x++ ){ this.grid[x] = []; for ( var y = 0; y < this.cellsHigh; y++ ){ this.grid[x][y] = null; } } } Grid.prototype.pixelsToGridCoords = function( point ){ var gridX = Math.floor( point.x / this.cellSize ); var gridY = Math.floor( point.y / this.cellSize ); return { x: gridX, y: gridY }; } Grid.prototype.addPointToGrid = function( pointCoords, gridCoords ){ this.grid[ gridCoords.x ][ gridCoords.y ] = pointCoords; } Grid.prototype.randomPoint = function(){ return { x: getRandomArbitrary(0,this.width), y: getRandomArbitrary(0,this.height) }; } Grid.prototype.randomPointAround = function( point ){ var r1 = Math.random(); var r2 = Math.random(); // get a random radius between the min distance and 2 X mindist var radius = this.minDistance * (r1 + 1); // get random angle around the circle var angle = 2 * Math.PI * r2; // get x and y coords based on angle and radius var x = point.x + radius * Math.cos( angle ); var y = point.y + radius * Math.sin( angle ); return { x: x, y: y }; } Grid.prototype.inNeighborhood = function( point ){ var gridPoint = this.pixelsToGridCoords( point ); // TODO cells around point for ( var i = 0; i < cellsAroundPoint.length; i++ ){ if ( cellsAroundPoint[i] != null ){ if ( this.calcDistance( cellsAroundPoint[i], point ) < this.minDistance ){ return true; } } } return false; /* //get the neighbourhood if the point in the grid cellsAroundPoint = squareAroundPoint(grid, gridPoint, 5) for every cell in cellsAroundPoint if (cell != null) if distance(cell, point) < mindist return true return false */ } Grid.prototype.calcDistnce = function( pointInCell, point ){ return (point.x - pointInCell.x)*(point.x - pointInCell.x) + (point.y - pointInCell.y)*(point.y - pointInCell.y) } Grid.prototype.drawPoint = function( point, color, canvas ){ // Default color color = color || '#aaa'; // Draw a circle canvas.beginPath(); canvas.arc( point.x, point.y, 3, 0, 2 * Math.PI, false); canvas.fillStyle = color; canvas.fill(); } Grid.prototype.drawGrid = function( canvas ){ canvas.lineWidth = 0.2; canvas.strokeStyle = 'black'; // Borders canvas.beginPath(); canvas.moveTo( 0, 0 ); canvas.lineTo( this.width, 0 ); canvas.lineTo( this.width, this.height ); canvas.lineTo( 0, this.height ); canvas.lineTo( 0, 0 ); canvas.stroke(); // Vertical lines for ( var x = 1; x < this.cellsWide; x++ ){ canvas.beginPath(); canvas.moveTo( x * this.cellSize, 0 ); canvas.lineTo( x * this.cellSize, this.height ); canvas.stroke(); } // Horizontal lines for ( var y = 1; y < this.cellsHigh; y++ ){ canvas.beginPath(); canvas.moveTo( 0, y * this.cellSize ); canvas.lineTo( this.width, y * this.cellSize ); canvas.stroke(); } } function RandomQueue( a ){ this.queue = a || new Array(); } RandomQueue.prototype.push = function( element ){ this.queue.push( element ); } RandomQueue.prototype.pop = function(){ randomIndex = getRandomInt( 0, this.queue.length ); while( this.queue[randomIndex] === undefined ){ randomIndex = getRandomInt( 0, this.queue.length ); } element = this.queue[ randomIndex ]; this.queue.remove( randomIndex ); return element; } // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; // MDN Random Number Functions // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /* for( var i = 0; i < 30; i++ ){ point = demo.randomPoint(); demo.drawPoint( point, null, canvas ); } */ var sampler = new PoissonDiskSampler( CANVAS_WIDTH, CANVAS_HEIGHT, 40, 30 ); sampler.grid.drawGrid( canvas ); for ( var i = 0; i < 30; i++ ){ sampler.outputList.push( sampler.grid.randomPointAround(sampler.outputList[0]) ); } sampler.drawOutputList( canvas ); console.log( sampler );
poisson-disk.js
// Constants var CANVAS_WIDTH = 700 , CANVAS_HEIGHT = 500; // Add canvas to page var canvasElement = $("<canvas width='" + CANVAS_WIDTH + "' height='" + CANVAS_HEIGHT + "'></canvas>"); var canvas = canvasElement.get(0).getContext("2d"); canvasElement.appendTo('body'); function Grid( width, height, minDistance ){ this.width = width; this.height = height; this.minDistance = minDistance; this.cellSize = this.minDistance / Math.SQRT2; console.log( this.cellSize ); this.cellsWide = Math.ceil( this.width / this.cellSize ); this.cellsHigh = Math.ceil( this.height / this.cellSize ); // Initialize grid this.grid = []; for ( var x = 0; x < this.cellsWide; x++ ){ this.grid[x] = []; for ( var y = 0; y < this.cellsHigh; y++ ){ this.grid[x][y] = null; } } } Grid.prototype.pixelsToGridCoords = function( point ){ var gridX = Math.floor( point.x / this.cellSize ); var gridY = Math.floor( point.y / this.cellSize ); return [ gridX, gridY ]; } Grid.prototype.randomPoint = function(){ return { x: getRandomArbitrary(0,this.width), y: getRandomArbitrary(0,this.height) }; } Grid.prototype.drawPoint = function( point, color, canvas ){ // Default color color = color || '#aaa'; // Draw a circle canvas.beginPath(); canvas.arc( point.x, point.y, this.minDistance, 0, 2 * Math.PI, false); canvas.fillStyle = color; canvas.fill(); } Grid.prototype.drawGrid = function( canvas ){ canvas.lineWidth = 0.2; canvas.strokeStyle = 'black'; // Borders canvas.beginPath(); canvas.moveTo( 0, 0 ); canvas.lineTo( this.width, 0 ); canvas.lineTo( this.width, this.height ); canvas.lineTo( 0, this.height ); canvas.lineTo( 0, 0 ); canvas.stroke(); // Vertical lines for ( var x = 1; x < this.cellsWide; x++ ){ canvas.beginPath(); canvas.moveTo( x * this.cellSize, 0 ); canvas.lineTo( x * this.cellSize, this.height ); canvas.stroke(); } // Horizontal lines for ( var y = 1; y < this.cellsHigh; y++ ){ canvas.beginPath(); canvas.moveTo( 0, y * this.cellSize ); canvas.lineTo( this.width, y * this.cellSize ); canvas.stroke(); } } function RandomQueue( a ){ this.queue = a || new Array(); } RandomQueue.prototype.push = function( element ){ this.queue.push( element ); } RandomQueue.prototype.pop = function(){ randomIndex = getRandomInt( 0, this.queue.length ); while( this.queue[randomIndex] === undefined ){ randomIndex = getRandomInt( 0, this.queue.length ); } element = this.queue[ randomIndex ]; this.queue.remove( randomIndex ); return element; } // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; // MDN Random Number Functions // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var demo = new Grid( CANVAS_WIDTH, CANVAS_HEIGHT, 40 ); demo.drawGrid( canvas ); var rq = new RandomQueue( [1,2,3,4,5,6,7,8,9] ); console.log( rq.pop() ); console.log( rq.pop() ); console.log( rq.pop() ); console.log( rq.queue ); for( var i = 0; i < 30; i++ ){ point = demo.randomPoint(); demo.drawPoint( point, null, canvas ); }
Added get points around, sampler class
poisson-disk.js
Added get points around, sampler class
<ide><path>oisson-disk.js <ide> var canvasElement = $("<canvas width='" + CANVAS_WIDTH + "' height='" + CANVAS_HEIGHT + "'></canvas>"); <ide> var canvas = canvasElement.get(0).getContext("2d"); <ide> canvasElement.appendTo('body'); <add> <add> <add>function PoissonDiskSampler( width, height, minDistance, sampleFrequency ){ <add> this.grid = new Grid( width, height, minDistance ); <add> this.outputList = new Array(); <add> this.processingQueue = new RandomQueue(); <add> <add> // Generate first point <add> this.queueToAll( this.grid.randomPoint() ); <add> <add>} <add> <add>PoissonDiskSampler.prototype.queueToAll = function ( point ){ <add> this.processingQueue.push( point ); <add> this.outputList.push( point ); <add> this.grid.addPointToGrid( point, this.grid.pixelsToGridCoords( point ) ); <add>} <add> <add>PoissonDiskSampler.prototype.drawOutputList = function( canvas ){ <add> for ( var i = 0; i < this.outputList.length; i++ ){ <add> this.grid.drawPoint( this.outputList[ i ], "#aaa", canvas ); <add> } <add>} <add> <ide> <ide> <ide> function Grid( width, height, minDistance ){ <ide> Grid.prototype.pixelsToGridCoords = function( point ){ <ide> var gridX = Math.floor( point.x / this.cellSize ); <ide> var gridY = Math.floor( point.y / this.cellSize ); <del> return [ gridX, gridY ]; <add> return { x: gridX, y: gridY }; <add>} <add> <add>Grid.prototype.addPointToGrid = function( pointCoords, gridCoords ){ <add> this.grid[ gridCoords.x ][ gridCoords.y ] = pointCoords; <ide> } <ide> <ide> Grid.prototype.randomPoint = function(){ <ide> return { x: getRandomArbitrary(0,this.width), y: getRandomArbitrary(0,this.height) }; <add>} <add> <add>Grid.prototype.randomPointAround = function( point ){ <add> var r1 = Math.random(); <add> var r2 = Math.random(); <add> // get a random radius between the min distance and 2 X mindist <add> var radius = this.minDistance * (r1 + 1); <add> // get random angle around the circle <add> var angle = 2 * Math.PI * r2; <add> // get x and y coords based on angle and radius <add> var x = point.x + radius * Math.cos( angle ); <add> var y = point.y + radius * Math.sin( angle ); <add> return { x: x, y: y }; <add>} <add> <add>Grid.prototype.inNeighborhood = function( point ){ <add> var gridPoint = this.pixelsToGridCoords( point ); <add> <add> // TODO cells around point <add> <add> for ( var i = 0; i < cellsAroundPoint.length; i++ ){ <add> if ( cellsAroundPoint[i] != null ){ <add> if ( this.calcDistance( cellsAroundPoint[i], point ) < this.minDistance ){ <add> return true; <add> } <add> } <add> } <add> return false; <add> <add>/* <add> //get the neighbourhood if the point in the grid <add> cellsAroundPoint = squareAroundPoint(grid, gridPoint, 5) <add> for every cell in cellsAroundPoint <add> if (cell != null) <add> if distance(cell, point) < mindist <add> return true <add> return false <add>*/ <add> <add>} <add> <add>Grid.prototype.calcDistnce = function( pointInCell, point ){ <add> return (point.x - pointInCell.x)*(point.x - pointInCell.x) <add> + (point.y - pointInCell.y)*(point.y - pointInCell.y) <ide> } <ide> <ide> <ide> color = color || '#aaa'; <ide> // Draw a circle <ide> canvas.beginPath(); <del> canvas.arc( point.x, point.y, this.minDistance, 0, 2 * Math.PI, false); <add> canvas.arc( point.x, point.y, 3, 0, 2 * Math.PI, false); <ide> canvas.fillStyle = color; <ide> canvas.fill(); <ide> } <ide> } <ide> <ide> <del>var demo = new Grid( CANVAS_WIDTH, CANVAS_HEIGHT, 40 ); <del>demo.drawGrid( canvas ); <del> <del>var rq = new RandomQueue( [1,2,3,4,5,6,7,8,9] ); <del>console.log( rq.pop() ); <del>console.log( rq.pop() ); <del>console.log( rq.pop() ); <del>console.log( rq.queue ); <del> <del> <add>/* <ide> for( var i = 0; i < 30; i++ ){ <ide> point = demo.randomPoint(); <ide> demo.drawPoint( point, null, canvas ); <ide> } <del> <del> <del> <del> <del> <del> <del> <add>*/ <add> <add>var sampler = new PoissonDiskSampler( CANVAS_WIDTH, CANVAS_HEIGHT, 40, 30 ); <add>sampler.grid.drawGrid( canvas ); <add> <add>for ( var i = 0; i < 30; i++ ){ <add> sampler.outputList.push( sampler.grid.randomPointAround(sampler.outputList[0]) ); <add>} <add>sampler.drawOutputList( canvas ); <add> <add> <add>console.log( sampler ); <add> <add> <add>
JavaScript
mpl-2.0
cd1acfcd9716350e602b257931661d3eb8787405
0
mozilla-services/tecken,mozilla-services/tecken,mozilla-services/tecken,mozilla-services/tecken
import React, { Component } from 'react' import { NavLink, Link } from 'react-router-dom' import { observer } from 'mobx-react' import './Nav.css' import store from './Store' const Nav = observer( class Nav extends Component { constructor(props) { super(props) this.state = { menuToggled: true } } shouldComponentUpdate(nextProps, nextState) { // We do this so that this component is always re-rendered. // The reason is that the NavLink component in react-router-dom // might get a different idea of what's active and what's not // if the location has changed but none of the "local" props // and state has changed. return true } toggleMenu = event => { event.preventDefault() this.setState({ menuToggled: !this.state.menuToggled }) } render() { return ( <nav className="navbar has-shadow" id="top"> <div className="navbar-brand"> <Link className="navbar-item" to="/"> Mozilla Symbol Server </Link> <div data-target="navMenubd-example" className={ this.state.menuToggled ? 'navbar-burger' : 'navbar-burger is-active' } onClick={this.toggleMenu} > <span /> <span /> <span /> </div> </div> <div id="navMenubd-example" className={ this.state.menuToggled ? 'navbar-menu' : 'navbar-menu is-active' } > <div className="navbar-end"> <NavLink to="/" exact className="navbar-item" activeClassName="is-active" > Home </NavLink> {store.currentUser && store.currentUser.is_superuser ? <NavLink to="/users" className="navbar-item" activeClassName="is-active" > User Management </NavLink> : null} {store.currentUser && store.hasPermission('tokens.manage_tokens') && <NavLink to="/tokens" className="navbar-item" activeClassName="is-active" > API Tokens </NavLink>} {store.currentUser && store.hasPermission('upload.upload_symbols') && <NavLink to="/uploads" className="navbar-item" activeClassName="is-active" > Uploads </NavLink>} <NavLink to="/help" className="navbar-item" activeClassName="is-active" > Help </NavLink> <span className="navbar-item"> {store.currentUser && <button onClick={this.props.signOut} className="button is-info" title={`Signed in as ${store.currentUser.email}`} > Sign Out </button>} {!store.currentUser && store.signInUrl && <button onClick={this.props.signIn} className="button is-info" > Sign In </button>} </span> </div> </div> </nav> ) } } ) export default Nav
frontend/src/Nav.js
import React, { Component } from 'react' import { NavLink, Link } from 'react-router-dom' import { observer } from 'mobx-react' import './Nav.css' import store from './Store' const Nav = observer( class Nav extends Component { constructor(props) { super(props) this.state = { menuToggled: true } } toggleMenu = event => { event.preventDefault() this.setState({ menuToggled: !this.state.menuToggled }) } render() { return ( <nav className="navbar has-shadow" id="top"> <div className="navbar-brand"> <Link className="navbar-item" to="/"> Mozilla Symbol Server </Link> <div data-target="navMenubd-example" className={ this.state.menuToggled ? 'navbar-burger' : 'navbar-burger is-active' } onClick={this.toggleMenu} > <span /> <span /> <span /> </div> </div> <div id="navMenubd-example" className={ this.state.menuToggled ? 'navbar-menu' : 'navbar-menu is-active' } > <div className="navbar-end"> <NavLink to="/" exact className="navbar-item" activeClassName="is-active" > Home </NavLink> {store.currentUser && store.currentUser.is_superuser ? <NavLink to="/users" className="navbar-item" activeClassName="is-active" > User Management </NavLink> : null} {store.currentUser && store.hasPermission('tokens.manage_tokens') && <NavLink to="/tokens" className="navbar-item" activeClassName="is-active" > API Tokens </NavLink>} {store.currentUser && store.hasPermission('upload.upload_symbols') && <NavLink to="/uploads" className="navbar-item" activeClassName="is-active" > Uploads </NavLink>} <NavLink to="/help" className="navbar-item" activeClassName="is-active" > Help </NavLink> <span className="navbar-item"> {store.currentUser && <button onClick={this.props.signOut} className="button is-info" title={`Signed in as ${store.currentUser.email}`} > Sign Out </button>} {!store.currentUser && store.signInUrl && <button onClick={this.props.signIn} className="button is-info" > Sign In </button>} </span> </div> </div> </nav> ) } } ) export default Nav
fixes bug 1395285 - Nav not updating which tab is active (#357)
frontend/src/Nav.js
fixes bug 1395285 - Nav not updating which tab is active (#357)
<ide><path>rontend/src/Nav.js <ide> this.state = { <ide> menuToggled: true <ide> } <add> } <add> <add> shouldComponentUpdate(nextProps, nextState) { <add> // We do this so that this component is always re-rendered. <add> // The reason is that the NavLink component in react-router-dom <add> // might get a different idea of what's active and what's not <add> // if the location has changed but none of the "local" props <add> // and state has changed. <add> return true <ide> } <ide> <ide> toggleMenu = event => {
Java
apache-2.0
031120b66d8c8db22ff043ace5b91c646791314e
0
foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,TanayParikh/foam2,foam-framework/foam2,foam-framework/foam2,TanayParikh/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,TanayParikh/foam2,TanayParikh/foam2,jacksonic/vjlofvhjfgm
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.pool; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import foam.core.ContextAgent; import foam.core.X; import foam.nanos.logger.NanoLogger; import foam.nanos.pm.PM; public class FixedThreadPool extends AbstractFixedThreadPool { protected ExecutorService pool_ = null; protected Object queuedLock_ = new Object(); protected Object executingLock_ = new Object(); protected Object executedLock_ = new Object(); class ContextAgentRunnable implements Runnable { final X x_; final ContextAgent agent_; public ContextAgentRunnable(X x, ContextAgent agent) { x_ = x; agent_ = agent; } public void run() { incrExecuting(1); NanoLogger logger = (NanoLogger) getX().get("logger"); PM pm = new PM(this.getClass(), agent_.getClass().getName()); try { agent_.execute(x_); } catch (Throwable t) { logger.error(this.getClass(), t.getMessage()); } finally { incrExecuting(-1); incrExecuted(); pm.log(getX()); } } } public FixedThreadPool() { } public void incrExecuting(int d) { synchronized ( executingLock_ ) { executing_ += d; } } public void incrExecuted() { synchronized ( executedLock_ ) { executed_++; } } public void incrQueued() { synchronized ( queuedLock_ ) { queued_++; } } public synchronized ExecutorService getPool() { if ( pool_ == null ) { pool_ = Executors.newFixedThreadPool(getNumberOfThreads()); } return pool_; } public void submit(X x, ContextAgent agent) { incrQueued(); getPool().submit(new ContextAgentRunnable(x, agent)); } }
src/foam/nanos/pool/FixedThreadPool.java
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.pool; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import foam.core.ContextAgent; import foam.core.X; import foam.nanos.logger.NanoLogger; import foam.nanos.pm.PM; public class FixedThreadPool extends AbstractFixedThreadPool { protected ExecutorService pool_ = null; protected Object queuedLock_ = new Object(); protected Object executingLock_ = new Object(); protected Object executedLock_ = new Object(); class ContextAgentRunnable implements Runnable { final X x_; final ContextAgent agent_; public ContextAgentRunnable(X x, ContextAgent agent) { x_ = x; agent_ = agent; } public void run() { incrExecuting(1); NanoLogger logger = (NanoLogger) getX().get("logger"); PM pm = new PM(this.getClass(), agent_.getClass().getName()); try { agent_.execute(x_); } catch (Throwable t) { logger.error(this.getClass(), t.getMessage()); } finally { incrExecuting(-1); incrExecuted(); pm.log(getX()); } } } public FixedThreadPool() { } public void incrExecuting(int d) { synchronized ( executingLock_ ) { executing_ += d; } } public void incrExecuted() { synchronized ( executedLock_ ) { executed_++; } } public void incrQueued() { synchronized ( queuedLock_ ) { queued_++; } } public synchronized ExecutorService getPool() { if ( pool_ == null ) { pool_ = Executors.newFixedThreadPool(numberOfThreads_); } return pool_; } public void submit(X x, ContextAgent agent) { incrQueued(); getPool().submit(new ContextAgentRunnable(x, agent)); } }
Fix ThreadPool not setting number of threads properly.
src/foam/nanos/pool/FixedThreadPool.java
Fix ThreadPool not setting number of threads properly.
<ide><path>rc/foam/nanos/pool/FixedThreadPool.java <ide> <ide> public synchronized ExecutorService getPool() { <ide> if ( pool_ == null ) { <del> pool_ = Executors.newFixedThreadPool(numberOfThreads_); <add> pool_ = Executors.newFixedThreadPool(getNumberOfThreads()); <ide> } <ide> return pool_; <ide> }
Java
apache-2.0
6024522aa76d7af92b51e0eafa59c764deca6e6c
0
SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base
/* * Copyright 2022, TeamDev. All rights reserved. * * 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.environment; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.Immutable; /** * Testing environment. * * <p>Detected by checking stack trace for mentions of the known testing frameworks. * * <p>This option is mutually exclusive with {@link DefaultMode}, i.e. one of them is always enabled. */ @Immutable public final class Tests extends StandardEnvironmentType { private static final Tests INSTANCE = new Tests(); @SuppressWarnings("DuplicateStringLiteralInspection" /* Used in another context. */) private static final ImmutableList<String> KNOWN_TESTING_FRAMEWORKS = ImmutableList.of("org.junit", "org.testng", "org.spekframework", // v2 "io.spine.testing", "io.kotest"); /** * The names of the packages that when discovered in a stacktrace would tell that * the code is executed under tests. * * @see #enabled() */ public static ImmutableList<String> knownTestingFrameworks() { return KNOWN_TESTING_FRAMEWORKS; } /** * Obtains the singleton instance. */ public static Tests type() { return INSTANCE; } /** Prevents direct instantiation. */ private Tests() { super(); } /** * Verifies if the code currently runs under a unit testing framework. * * <p>The method returns {@code true} if {@linkplain #knownTestingFrameworks() * known testing framework packages} are discovered in the stacktrace. * * @return {@code true} if the code runs under a testing framework, {@code false} otherwise * @implNote In addition to checking the stack trace, this method checks the * environment variable value. If you wish to simulate not being in tests, the * variable must be set to {@code false} explicitly. If your framework is not * among the {@linkplain #knownTestingFrameworks() known ones}, make sure to set * the system property explicitly. * @see #knownTestingFrameworks() */ @Override public boolean enabled() { var property = new TestsProperty(); if (property.isSet()) { return property.value(); } var stacktrace = Throwables.getStackTraceAsString(new RuntimeException("")); var result = knownTestingFrameworks().stream() .anyMatch(stacktrace::contains); return result; } }
base/src/main/java/io/spine/environment/Tests.java
/* * Copyright 2022, TeamDev. All rights reserved. * * 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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 io.spine.environment; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.Immutable; /** * Testing environment. * * <p>Detected by checking stack trace for mentions of the known testing frameworks. * * <p>This option is mutually exclusive with {@link DefaultMode}, i.e. one of them is always enabled. */ @Immutable public final class Tests extends StandardEnvironmentType { private static final Tests INSTANCE = new Tests(); @SuppressWarnings("DuplicateStringLiteralInspection" /* Used in another context. */) private static final ImmutableList<String> KNOWN_TESTING_FRAMEWORKS = ImmutableList.of("org.junit", "org.testng", "org.spekframework", "io.spine.testing", "io.kotest"); /** * The names of the packages that when discovered in a stacktrace would tell that * the code is executed under tests. * * <p>The returned package names are: * <ol> * <li>"org.junit" * <li>"org.testng" * <li>"io.spine.testing" * </ol> * * @see #enabled() */ public static ImmutableList<String> knownTestingFrameworks() { return KNOWN_TESTING_FRAMEWORKS; } /** * Obtains the singleton instance. */ public static Tests type() { return INSTANCE; } /** Prevents direct instantiation. */ private Tests() { super(); } /** * Verifies if the code currently runs under a unit testing framework. * * <p>The method returns {@code true} if {@linkplain #knownTestingFrameworks() * known testing framework packages} are discovered in the stacktrace. * * @return {@code true} if the code runs under a testing framework, {@code false} otherwise * @implNote In addition to checking the stack trace, this method checks the * environment variable value. If you wish to simulate not being in tests, the * variable must be set to {@code false} explicitly. If your framework is not * among the {@linkplain #knownTestingFrameworks() known ones}, make sure to set * the system property explicitly. * @see #knownTestingFrameworks() */ @Override public boolean enabled() { var property = new TestsProperty(); if (property.isSet()) { return property.value(); } var stacktrace = Throwables.getStackTraceAsString(new RuntimeException("")); var result = knownTestingFrameworks().stream() .anyMatch(stacktrace::contains); return result; } }
Improve documentation
base/src/main/java/io/spine/environment/Tests.java
Improve documentation
<ide><path>ase/src/main/java/io/spine/environment/Tests.java <ide> private static final ImmutableList<String> KNOWN_TESTING_FRAMEWORKS = <ide> ImmutableList.of("org.junit", <ide> "org.testng", <del> "org.spekframework", <add> "org.spekframework", // v2 <ide> "io.spine.testing", <ide> "io.kotest"); <ide> <ide> /** <ide> * The names of the packages that when discovered in a stacktrace would tell that <ide> * the code is executed under tests. <del> * <del> * <p>The returned package names are: <del> * <ol> <del> * <li>"org.junit" <del> * <li>"org.testng" <del> * <li>"io.spine.testing" <del> * </ol> <ide> * <ide> * @see #enabled() <ide> */
Java
apache-2.0
937681af653500051eec7e60929847451058a6eb
0
vpavic/spring-boot,shangyi0102/spring-boot,dreis2211/spring-boot,htynkn/spring-boot,ptahchiev/spring-boot,dreis2211/spring-boot,htynkn/spring-boot,donhuvy/spring-boot,pvorb/spring-boot,lburgazzoli/spring-boot,tsachev/spring-boot,kdvolder/spring-boot,tsachev/spring-boot,felipeg48/spring-boot,vakninr/spring-boot,felipeg48/spring-boot,lburgazzoli/spring-boot,mbenson/spring-boot,isopov/spring-boot,donhuvy/spring-boot,habuma/spring-boot,wilkinsona/spring-boot,linead/spring-boot,joshiste/spring-boot,dreis2211/spring-boot,philwebb/spring-boot,royclarkson/spring-boot,shakuzen/spring-boot,donhuvy/spring-boot,zhanhb/spring-boot,drumonii/spring-boot,ilayaperumalg/spring-boot,Buzzardo/spring-boot,deki/spring-boot,sebastiankirsch/spring-boot,bbrouwer/spring-boot,bclozel/spring-boot,chrylis/spring-boot,DeezCashews/spring-boot,ilayaperumalg/spring-boot,mosoft521/spring-boot,ihoneymon/spring-boot,isopov/spring-boot,habuma/spring-boot,royclarkson/spring-boot,habuma/spring-boot,rweisleder/spring-boot,bjornlindstrom/spring-boot,vakninr/spring-boot,Buzzardo/spring-boot,habuma/spring-boot,tsachev/spring-boot,bbrouwer/spring-boot,bbrouwer/spring-boot,spring-projects/spring-boot,deki/spring-boot,tiarebalbi/spring-boot,olivergierke/spring-boot,isopov/spring-boot,kamilszymanski/spring-boot,rweisleder/spring-boot,yangdd1205/spring-boot,michael-simons/spring-boot,NetoDevel/spring-boot,ptahchiev/spring-boot,linead/spring-boot,eddumelendez/spring-boot,ptahchiev/spring-boot,donhuvy/spring-boot,royclarkson/spring-boot,tsachev/spring-boot,felipeg48/spring-boot,jxblum/spring-boot,pvorb/spring-boot,jayarampradhan/spring-boot,drumonii/spring-boot,philwebb/spring-boot,linead/spring-boot,yangdd1205/spring-boot,Nowheresly/spring-boot,bclozel/spring-boot,htynkn/spring-boot,drumonii/spring-boot,drumonii/spring-boot,zhanhb/spring-boot,zhanhb/spring-boot,ilayaperumalg/spring-boot,linead/spring-boot,donhuvy/spring-boot,bjornlindstrom/spring-boot,ihoneymon/spring-boot,DeezCashews/spring-boot,NetoDevel/spring-boot,shakuzen/spring-boot,Buzzardo/spring-boot,kdvolder/spring-boot,hello2009chen/spring-boot,NetoDevel/spring-boot,kdvolder/spring-boot,joshiste/spring-boot,bclozel/spring-boot,vpavic/spring-boot,kdvolder/spring-boot,mosoft521/spring-boot,jayarampradhan/spring-boot,mbenson/spring-boot,zhanhb/spring-boot,mdeinum/spring-boot,hello2009chen/spring-boot,michael-simons/spring-boot,jayarampradhan/spring-boot,tiarebalbi/spring-boot,felipeg48/spring-boot,bclozel/spring-boot,vakninr/spring-boot,shangyi0102/spring-boot,pvorb/spring-boot,tsachev/spring-boot,kamilszymanski/spring-boot,jxblum/spring-boot,sebastiankirsch/spring-boot,michael-simons/spring-boot,habuma/spring-boot,tsachev/spring-boot,olivergierke/spring-boot,jayarampradhan/spring-boot,ptahchiev/spring-boot,jxblum/spring-boot,drumonii/spring-boot,scottfrederick/spring-boot,shakuzen/spring-boot,hello2009chen/spring-boot,spring-projects/spring-boot,olivergierke/spring-boot,bjornlindstrom/spring-boot,mbenson/spring-boot,DeezCashews/spring-boot,philwebb/spring-boot,shakuzen/spring-boot,felipeg48/spring-boot,eddumelendez/spring-boot,wilkinsona/spring-boot,ilayaperumalg/spring-boot,olivergierke/spring-boot,eddumelendez/spring-boot,tiarebalbi/spring-boot,NetoDevel/spring-boot,michael-simons/spring-boot,htynkn/spring-boot,jxblum/spring-boot,drumonii/spring-boot,kdvolder/spring-boot,dreis2211/spring-boot,royclarkson/spring-boot,vpavic/spring-boot,isopov/spring-boot,Nowheresly/spring-boot,royclarkson/spring-boot,aahlenst/spring-boot,ptahchiev/spring-boot,michael-simons/spring-boot,shakuzen/spring-boot,mbenson/spring-boot,joshiste/spring-boot,tiarebalbi/spring-boot,ihoneymon/spring-boot,jxblum/spring-boot,hello2009chen/spring-boot,eddumelendez/spring-boot,tiarebalbi/spring-boot,lburgazzoli/spring-boot,Buzzardo/spring-boot,pvorb/spring-boot,tiarebalbi/spring-boot,bjornlindstrom/spring-boot,zhanhb/spring-boot,wilkinsona/spring-boot,bjornlindstrom/spring-boot,mosoft521/spring-boot,Buzzardo/spring-boot,lburgazzoli/spring-boot,joshiste/spring-boot,scottfrederick/spring-boot,spring-projects/spring-boot,joshiste/spring-boot,sebastiankirsch/spring-boot,chrylis/spring-boot,jxblum/spring-boot,habuma/spring-boot,yangdd1205/spring-boot,chrylis/spring-boot,htynkn/spring-boot,DeezCashews/spring-boot,scottfrederick/spring-boot,mdeinum/spring-boot,rweisleder/spring-boot,spring-projects/spring-boot,dreis2211/spring-boot,wilkinsona/spring-boot,wilkinsona/spring-boot,pvorb/spring-boot,deki/spring-boot,mbenson/spring-boot,deki/spring-boot,sebastiankirsch/spring-boot,mosoft521/spring-boot,chrylis/spring-boot,vpavic/spring-boot,kamilszymanski/spring-boot,NetoDevel/spring-boot,dreis2211/spring-boot,philwebb/spring-boot,ihoneymon/spring-boot,ilayaperumalg/spring-boot,aahlenst/spring-boot,vakninr/spring-boot,michael-simons/spring-boot,eddumelendez/spring-boot,shangyi0102/spring-boot,ptahchiev/spring-boot,scottfrederick/spring-boot,mdeinum/spring-boot,donhuvy/spring-boot,Nowheresly/spring-boot,rweisleder/spring-boot,Nowheresly/spring-boot,spring-projects/spring-boot,aahlenst/spring-boot,joshiste/spring-boot,aahlenst/spring-boot,scottfrederick/spring-boot,philwebb/spring-boot,lburgazzoli/spring-boot,deki/spring-boot,shangyi0102/spring-boot,sebastiankirsch/spring-boot,felipeg48/spring-boot,rweisleder/spring-boot,zhanhb/spring-boot,vpavic/spring-boot,mbenson/spring-boot,htynkn/spring-boot,isopov/spring-boot,isopov/spring-boot,kamilszymanski/spring-boot,mdeinum/spring-boot,mosoft521/spring-boot,eddumelendez/spring-boot,philwebb/spring-boot,ihoneymon/spring-boot,DeezCashews/spring-boot,chrylis/spring-boot,hello2009chen/spring-boot,ihoneymon/spring-boot,aahlenst/spring-boot,olivergierke/spring-boot,kdvolder/spring-boot,bclozel/spring-boot,ilayaperumalg/spring-boot,vakninr/spring-boot,vpavic/spring-boot,mdeinum/spring-boot,jayarampradhan/spring-boot,spring-projects/spring-boot,linead/spring-boot,shakuzen/spring-boot,bbrouwer/spring-boot,bclozel/spring-boot,scottfrederick/spring-boot,bbrouwer/spring-boot,aahlenst/spring-boot,chrylis/spring-boot,wilkinsona/spring-boot,Nowheresly/spring-boot,rweisleder/spring-boot,Buzzardo/spring-boot,kamilszymanski/spring-boot,mdeinum/spring-boot,shangyi0102/spring-boot
/* * Copyright 2012-2017 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.springframework.boot.actuate.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMappingCustomizer; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for MVC {@link Endpoint}s. * * @author Dave Syer */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "foo.bar=baz") @DirtiesContext @TestPropertySource(properties = "management.security.enabled=false") public class EndpointMvcIntegrationTests { @LocalServerPort private int port; @Autowired private TestInterceptor interceptor; @Test public void envEndpointNotHidden() throws InterruptedException { String body = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/env/foo.bar", String.class); assertThat(body).isNotNull().contains("\"baz\""); assertThat(this.interceptor.invoked()).isTrue(); } @Test public void healthEndpointNotHidden() throws InterruptedException { String body = new TestRestTemplate() .getForObject("http://localhost:" + this.port + "/health", String.class); assertThat(body).isNotNull().contains("status"); assertThat(this.interceptor.invoked()).isTrue(); } @Configuration @MinimalWebConfiguration @Import({ JacksonAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class }) @RestController protected static class Application { private final List<HttpMessageConverter<?>> converters; public Application(ObjectProvider<List<HttpMessageConverter<?>>> converters) { this.converters = converters.getIfAvailable(); } @RequestMapping("/{name}/{env}/{bar}") public Map<String, Object> master(@PathVariable String name, @PathVariable String env, @PathVariable String label) { return Collections.singletonMap("foo", (Object) "bar"); } @RequestMapping("/{name}/{env}") public Map<String, Object> master(@PathVariable String name, @PathVariable String env) { return Collections.singletonMap("foo", (Object) "bar"); } @Bean @ConditionalOnMissingBean public HttpMessageConverters messageConverters() { return new HttpMessageConverters(this.converters == null ? Collections.<HttpMessageConverter<?>>emptyList() : this.converters); } @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { return new EndpointHandlerMappingCustomizer() { @Override public void customize(EndpointHandlerMapping mapping) { mapping.setInterceptors(interceptor()); } }; } @Bean protected TestInterceptor interceptor() { return new TestInterceptor(); } } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } protected static class TestInterceptor extends HandlerInterceptorAdapter { private final CountDownLatch latch = new CountDownLatch(1); @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { this.latch.countDown(); } public boolean invoked() throws InterruptedException { return this.latch.await(30, TimeUnit.SECONDS); } } }
spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java
/* * Copyright 2012-2017 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.springframework.boot.actuate.autoconfigure; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping; import org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMappingCustomizer; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for MVC {@link Endpoint}s. * * @author Dave Syer */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext @TestPropertySource(properties = "management.security.enabled=false") public class EndpointMvcIntegrationTests { @LocalServerPort private int port; @Autowired private TestInterceptor interceptor; @Test public void envEndpointNotHidden() throws InterruptedException { String body = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/env/user.dir", String.class); assertThat(body).isNotNull().contains("spring-boot-actuator"); assertThat(this.interceptor.invoked()).isTrue(); } @Test public void healthEndpointNotHidden() throws InterruptedException { String body = new TestRestTemplate() .getForObject("http://localhost:" + this.port + "/health", String.class); assertThat(body).isNotNull().contains("status"); assertThat(this.interceptor.invoked()).isTrue(); } @Configuration @MinimalWebConfiguration @Import({ JacksonAutoConfiguration.class, EndpointAutoConfiguration.class, EndpointWebMvcAutoConfiguration.class, AuditAutoConfiguration.class }) @RestController protected static class Application { private final List<HttpMessageConverter<?>> converters; public Application(ObjectProvider<List<HttpMessageConverter<?>>> converters) { this.converters = converters.getIfAvailable(); } @RequestMapping("/{name}/{env}/{bar}") public Map<String, Object> master(@PathVariable String name, @PathVariable String env, @PathVariable String label) { return Collections.singletonMap("foo", (Object) "bar"); } @RequestMapping("/{name}/{env}") public Map<String, Object> master(@PathVariable String name, @PathVariable String env) { return Collections.singletonMap("foo", (Object) "bar"); } @Bean @ConditionalOnMissingBean public HttpMessageConverters messageConverters() { return new HttpMessageConverters(this.converters == null ? Collections.<HttpMessageConverter<?>>emptyList() : this.converters); } @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { return new EndpointHandlerMappingCustomizer() { @Override public void customize(EndpointHandlerMapping mapping) { mapping.setInterceptors(interceptor()); } }; } @Bean protected TestInterceptor interceptor() { return new TestInterceptor(); } } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ ServletWebServerFactoryAutoConfiguration.class, DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, ErrorMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) protected @interface MinimalWebConfiguration { } protected static class TestInterceptor extends HandlerInterceptorAdapter { private final CountDownLatch latch = new CountDownLatch(1); @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { this.latch.countDown(); } public boolean invoked() throws InterruptedException { return this.latch.await(30, TimeUnit.SECONDS); } } }
Avoid problem caused by new mime mappings in Framework snapshots
spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java
Avoid problem caused by new mime mappings in Framework snapshots
<ide><path>pring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointMvcIntegrationTests.java <ide> * @author Dave Syer <ide> */ <ide> @RunWith(SpringRunner.class) <del>@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) <add>@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "foo.bar=baz") <ide> @DirtiesContext <ide> @TestPropertySource(properties = "management.security.enabled=false") <ide> public class EndpointMvcIntegrationTests { <ide> @Test <ide> public void envEndpointNotHidden() throws InterruptedException { <ide> String body = new TestRestTemplate().getForObject( <del> "http://localhost:" + this.port + "/env/user.dir", String.class); <del> assertThat(body).isNotNull().contains("spring-boot-actuator"); <add> "http://localhost:" + this.port + "/env/foo.bar", String.class); <add> assertThat(body).isNotNull().contains("\"baz\""); <ide> assertThat(this.interceptor.invoked()).isTrue(); <ide> } <ide>
Java
mit
1ed5e2b2ded40950e187b4c40e44520253751525
0
openforis/collect,openforis/collect,openforis/collect,openforis/collect
package org.openforis.collect.model; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.namespace.QName; import org.apache.commons.lang3.StringUtils; import org.openforis.idm.metamodel.AttributeDefinition; import org.openforis.idm.metamodel.EntityDefinition; import org.openforis.idm.metamodel.NodeDefinition; import org.openforis.idm.metamodel.validation.ValidationResultFlag; import org.openforis.idm.metamodel.validation.ValidationResults; import org.openforis.idm.model.Attribute; import org.openforis.idm.model.Code; import org.openforis.idm.model.CodeAttribute; import org.openforis.idm.model.Entity; import org.openforis.idm.model.Field; import org.openforis.idm.model.Node; import org.openforis.idm.model.NodeVisitor; import org.openforis.idm.model.NumberAttribute; import org.openforis.idm.model.Record; import org.openforis.idm.model.TextAttribute; /** * @author G. Miceli * @author M. Togna */ public class CollectRecord extends Record { private static final QName COUNT_ANNOTATION = new QName("http://www.openforis.org/collect/3.0/collect", "count"); private static final int APPROVED_MISSING_POSITION = 0; private static final int CONFIRMED_ERROR_POSITION = 0; private static final int DEFAULT_APPLIED_POSITION = 1; public enum Step { ENTRY(1), CLEANSING(2), ANALYSIS(3); private int stepNumber; private Step(int stepNumber) { this.stepNumber = stepNumber; } public int getStepNumber() { return stepNumber; } public static Step valueOf(int stepNumber) { Step[] values = Step.values(); for (Step step : values) { if (step.getStepNumber() == stepNumber) { return step; } } return null; } public Step getNext() { switch(this) { case ENTRY: return CLEANSING; case CLEANSING: return ANALYSIS; default: throw new IllegalArgumentException("This record cannot be promoted."); } } public Step getPrevious() { switch(this) { case CLEANSING: return Step.ENTRY; case ANALYSIS: return Step.CLEANSING; default: throw new IllegalArgumentException("This record cannot be promoted."); } } } public enum State { REJECTED("R"); private String code; private State(String code) { this.code = code; } public String getCode() { return code; } public static State fromCode(String code) { State[] values = State.values(); for (State state : values) { if (state.getCode().equals(code)) { return state; } } return null; } } private transient Step step; private transient State state; private transient Date creationDate; private transient User createdBy; private transient Date modifiedDate; private transient User modifiedBy; private transient Integer missing; private transient Integer missingErrors; private transient Integer missingWarnings; private transient Integer skipped; private transient Integer errors; private transient Integer warnings; private List<String> rootEntityKeyValues; private List<Integer> entityCounts; private Map<Integer, Set<String>> minCountErrorCounts; private Map<Integer, Set<String>> minCountWarningCounts; private Map<Integer, Set<String>> maxCountErrorCounts; private Map<Integer, Set<String>> maxCountWarningCounts; private Map<Integer, Integer> errorCounts; private Map<Integer, Integer> warningCounts; private Set<Integer> skippedNodes; public CollectRecord(CollectSurvey survey, String versionName) { super(survey, versionName); this.step = Step.ENTRY; // use List to preserve the order of the keys and counts rootEntityKeyValues = new ArrayList<String>(); entityCounts = new ArrayList<Integer>(); initErrorCountInfo(); } private void initErrorCountInfo() { minCountErrorCounts = new HashMap<Integer, Set<String>>(); minCountWarningCounts = new HashMap<Integer, Set<String>>(); maxCountErrorCounts = new HashMap<Integer, Set<String>>(); maxCountWarningCounts = new HashMap<Integer, Set<String>>(); errorCounts = new HashMap<Integer, Integer>(); warningCounts = new HashMap<Integer, Integer>(); skippedNodes = new HashSet<Integer>(); skipped = null; missing = null; missingErrors = null; missingWarnings = null; errors = null; warnings = null; } public Node<?> deleteNode(Node<?> node) { if(node.isDetached()) { throw new IllegalArgumentException("Unable to delete a node already detached"); } Entity parentEntity = node.getParent(); int index = node.getIndex(); Node<?> deletedNode = parentEntity.remove(node.getName(), index); removeValidationCounts(deletedNode.getInternalId()); return deletedNode; } public void setErrorConfirmed(Attribute<?,?> attribute, boolean confirmed){ int fieldCount = attribute.getFieldCount(); for( int i=0; i <fieldCount; i++ ){ Field<?> field = attribute.getField(i); field.getState().set(CONFIRMED_ERROR_POSITION, confirmed); } } public boolean isErrorConfirmed(Attribute<?,?> attribute){ int fieldCount = attribute.getFieldCount(); for( int i=0; i <fieldCount; i++ ){ Field<?> field = attribute.getField(i); if( !field.getState().get(CONFIRMED_ERROR_POSITION) ){ return false; } } return true; } public void setMissingApproved(Entity parentEntity, String childName, boolean approved) { org.openforis.idm.model.State childState = parentEntity.getChildState(childName); childState.set(APPROVED_MISSING_POSITION, approved); } public boolean isMissingApproved(Entity parentEntity, String childName){ org.openforis.idm.model.State childState = parentEntity.getChildState(childName); return childState.get(APPROVED_MISSING_POSITION); } public void setDefaultValueApplied(Attribute<?, ?> attribute, boolean applied) { int fieldCount = attribute.getFieldCount(); for( int i=0; i <fieldCount; i++ ){ Field<?> field = attribute.getField(i); field.getState().set(DEFAULT_APPLIED_POSITION, applied); } } public boolean isDefaultValueApplied(Attribute<?, ?> attribute) { int fieldCount = attribute.getFieldCount(); for( int i=0; i <fieldCount; i++ ){ Field<?> field = attribute.getField(i); if( !field.getState().get(DEFAULT_APPLIED_POSITION) ){ return false; } } return true; } public void updateValidationMinCounts(Integer entityId, String childName, ValidationResultFlag flag) { Set<String> errors = clearEntityValidationCounts(minCountErrorCounts, entityId, childName); Set<String> warnings = clearEntityValidationCounts(minCountWarningCounts, entityId, childName); switch (flag) { case ERROR: errors.add(childName); break; case WARNING: warnings.add(childName); break; } this.missing = null; this.missingErrors = null; this.missingWarnings = null; this.errors = null; this.warnings = null; } public void updateValidationMaxCounts(Integer entityId, String childName, ValidationResultFlag flag) { Set<String> errors = clearEntityValidationCounts(maxCountErrorCounts, entityId, childName); Set<String> warnings = clearEntityValidationCounts(maxCountWarningCounts, entityId, childName); switch(flag) { case ERROR: errors.add(childName); break; case WARNING: warnings.add(childName); break; } this.errors = null; this.warnings = null; } public void updateValidationCounts(Integer attributeId, ValidationResults validationResults) { removeValidationCounts(attributeId); int errorCounts = validationResults.getErrors().size(); int warningCounts = validationResults.getWarnings().size(); this.errorCounts.put(attributeId, errorCounts); this.warningCounts.put(attributeId, warningCounts); errors = null; warnings = null; } public void updateSkippedCount(Integer attributeId) { removeValidationCounts(attributeId); skippedNodes.add(attributeId); skipped = null; } public void removeValidationCounts(Integer nodeId) { Node<?> node = this.getNodeByInternalId(nodeId); if(node instanceof Attribute<?, ?>) { skippedNodes.remove(nodeId); errorCounts.remove(nodeId); warningCounts.remove(nodeId); } else { minCountErrorCounts.remove(nodeId); maxCountErrorCounts.remove(nodeId); minCountWarningCounts.remove(nodeId); maxCountWarningCounts.remove(nodeId); } skipped = null; missing = null; missingErrors = null; missingWarnings = null; errors = null; warnings = null; } public Step getStep() { return step; } public void setStep(Step step) { this.step = step; } public State getState() { return state; } public void setState(State state) { this.state = state; } public Date getCreationDate() { return this.creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public User getCreatedBy() { return this.createdBy; } public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } public Date getModifiedDate() { return this.modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public User getModifiedBy() { return this.modifiedBy; } public void setModifiedBy(User modifiedBy) { this.modifiedBy = modifiedBy; } public Integer getSkipped() { if ( skipped == null ) { skipped = skippedNodes.size(); } return skipped; } public void setSkipped(Integer skipped) { this.skipped = skipped; } public Integer getMissing() { if (missing == null) { Integer errors = getMissingErrors(); Integer warnings = getMissingWarnings(); missing = errors + warnings; } return missing; } public Integer getMissingErrors() { if ( missingErrors == null ) { missingErrors = getMissingCount( minCountErrorCounts ); } return missingErrors; } public Integer getMissingWarnings() { if ( missingWarnings == null ) { missingWarnings = getMissingCount( minCountWarningCounts); } return missingWarnings; } public void setMissing(Integer missing) { this.missing = missing; } public Integer getErrors() { if(errors == null) { errors = getAttributeValidationCount(errorCounts); errors += getEntityValidationCount(maxCountErrorCounts); } return errors; } public void setErrors(Integer errors) { this.errors = errors; } public Integer getWarnings() { if(warnings == null) { warnings = getAttributeValidationCount(warningCounts); warnings += getEntityValidationCount(maxCountWarningCounts); } return warnings; } public void setWarnings(Integer warnings) { this.warnings = warnings; } public List<String> getRootEntityKeyValues() { return rootEntityKeyValues; } public void updateRootEntityKeyValues(){ Entity rootEntity = getRootEntity(); if(rootEntity != null) { rootEntityKeyValues = new ArrayList<String>(); EntityDefinition rootEntityDefn = rootEntity.getDefinition(); List<AttributeDefinition> keyDefns = rootEntityDefn.getKeyAttributeDefinitions(); for (AttributeDefinition keyDefn : keyDefns) { String keyValue = null; Node<?> keyNode = rootEntity.get(keyDefn.getName(), 0); if(keyNode instanceof CodeAttribute) { Code code = ((CodeAttribute) keyNode).getValue(); if(code != null) { keyValue = code.getCode(); } } else if(keyNode instanceof TextAttribute) { keyValue = ((TextAttribute) keyNode).getValue(); } else if(keyNode instanceof NumberAttribute<?>) { Object obj = ((NumberAttribute<?>) keyNode).getValue(); if(obj != null) { keyValue = obj.toString(); } } if(StringUtils.isNotEmpty(keyValue)){ rootEntityKeyValues.add(keyValue); } else { //todo throw error in this case? rootEntityKeyValues.add(null); } } } } public void updateEntityCounts() { Entity rootEntity = getRootEntity(); List<EntityDefinition> countableDefns = getCountableEntitiesInList(); //set counts List<Integer> counts = new ArrayList<Integer>(); for (EntityDefinition defn : countableDefns) { String name = defn.getName(); int count = rootEntity.getCount(name); counts.add(count); } entityCounts = counts; } public void setRootEntityKeyValues(List<String> keys) { this.rootEntityKeyValues = keys; } public List<Integer> getEntityCounts() { return entityCounts; } public void setEntityCounts(List<Integer> counts) { this.entityCounts = counts; } private Set<String> clearEntityValidationCounts(Map<Integer, Set<String>> counts, Integer entityId, String childName) { Set<String> set = counts.get(entityId); if(set == null) { set = new HashSet<String>(); counts.put(entityId, set); } else { set.remove(childName); } return set; } private Integer getEntityValidationCount(Map<Integer, Set<String>> map) { int count = 0; for (Set<String> set : map.values()) { count += set.size(); } return count; } private Integer getMissingCount(Map<Integer, Set<String>> minCounts) { int result = 0; Set<Integer> keySet = minCounts.keySet(); for (Integer id : keySet) { Entity entity = (Entity) getNodeByInternalId(id); Set<String> set = minCounts.get(id); for (String childName : set) { int missingCount = entity.getMissingCount(childName); result += missingCount; } } return result; } private Integer getAttributeValidationCount(Map<Integer, Integer> map) { int count = 0; for (Integer i : map.values()) { count += i; } return count; } /** * Clear all node states and all attribute symbols */ public void clearNodeStates() { Entity rootEntity = getRootEntity(); rootEntity.traverse( new NodeVisitor() { @Override public void visit(Node<? extends NodeDefinition> node, int idx) { if ( node instanceof Attribute ) { Attribute<?,?> attribute = (Attribute<?, ?>) node; // if ( step == Step.ENTRY ) { // attribute.clearFieldSymbols(); // } attribute.clearFieldStates(); attribute.clearValidationResults(); } else if( node instanceof Entity ) { Entity entity = (Entity) node; entity.clearChildStates(); EntityDefinition definition = entity.getDefinition(); List<NodeDefinition> childDefinitions = definition.getChildDefinitions(); for (NodeDefinition childDefinition : childDefinitions) { String childName = childDefinition.getName(); entity.clearRelevanceState(childName); entity.clearRequiredState(childName); } } } } ); } /** * Update all derived states of all nodes */ public void updateDerivedStates() { initErrorCountInfo(); Entity rootEntity = getRootEntity(); rootEntity.traverse(new NodeVisitor() { @Override public void visit(Node<? extends NodeDefinition> node, int idx) { if ( node instanceof Attribute ) { Attribute<?,?> attribute = (Attribute<?, ?>) node; attribute.validateValue(); } else if ( node instanceof Entity ) { Entity entity = (Entity) node; EntityDefinition definition = entity.getDefinition(); List<NodeDefinition> childDefinitions = definition.getChildDefinitions(); for (NodeDefinition childDefinition : childDefinitions) { String childName = childDefinition.getName(); entity.validateMaxCount( childName ); entity.validateMinCount( childName ); } } } }); } /** * Returns first level entity definitions that have the attribute countInSummaryList set to true * * @param rootEntityDefinition * @return */ private List<EntityDefinition> getCountableEntitiesInList() { List<EntityDefinition> result = new ArrayList<EntityDefinition>(); EntityDefinition rootEntityDefinition = getRootEntity().getDefinition(); List<NodeDefinition> childDefinitions = rootEntityDefinition .getChildDefinitions(); for (NodeDefinition childDefinition : childDefinitions) { if(childDefinition instanceof EntityDefinition) { EntityDefinition entityDefinition = (EntityDefinition) childDefinition; String annotation = childDefinition.getAnnotation(COUNT_ANNOTATION); if(annotation != null && Boolean.parseBoolean(annotation)) { result.add(entityDefinition); } } } return result; } }
collect-core/src/main/java/org/openforis/collect/model/CollectRecord.java
package org.openforis.collect.model; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.namespace.QName; import org.apache.commons.lang3.StringUtils; import org.openforis.idm.metamodel.AttributeDefinition; import org.openforis.idm.metamodel.EntityDefinition; import org.openforis.idm.metamodel.NodeDefinition; import org.openforis.idm.metamodel.validation.ValidationResultFlag; import org.openforis.idm.metamodel.validation.ValidationResults; import org.openforis.idm.model.Attribute; import org.openforis.idm.model.Code; import org.openforis.idm.model.CodeAttribute; import org.openforis.idm.model.Entity; import org.openforis.idm.model.Field; import org.openforis.idm.model.Node; import org.openforis.idm.model.NodeVisitor; import org.openforis.idm.model.NumberAttribute; import org.openforis.idm.model.Record; import org.openforis.idm.model.TextAttribute; /** * @author G. Miceli * @author M. Togna */ public class CollectRecord extends Record { private static final QName COUNT_ANNOTATION = new QName("http://www.openforis.org/collect/3.0/collect", "count"); private static final int APPROVED_MISSING_POSITION = 0; private static final int CONFIRMED_ERROR_POSITION = 0; public enum Step { ENTRY(1), CLEANSING(2), ANALYSIS(3); private int stepNumber; private Step(int stepNumber) { this.stepNumber = stepNumber; } public int getStepNumber() { return stepNumber; } public static Step valueOf(int stepNumber) { Step[] values = Step.values(); for (Step step : values) { if (step.getStepNumber() == stepNumber) { return step; } } return null; } public Step getNext() { switch(this) { case ENTRY: return CLEANSING; case CLEANSING: return ANALYSIS; default: throw new IllegalArgumentException("This record cannot be promoted."); } } public Step getPrevious() { switch(this) { case CLEANSING: return Step.ENTRY; case ANALYSIS: return Step.CLEANSING; default: throw new IllegalArgumentException("This record cannot be promoted."); } } } public enum State { REJECTED("R"); private String code; private State(String code) { this.code = code; } public String getCode() { return code; } public static State fromCode(String code) { State[] values = State.values(); for (State state : values) { if (state.getCode().equals(code)) { return state; } } return null; } } private transient Step step; private transient State state; private transient Date creationDate; private transient User createdBy; private transient Date modifiedDate; private transient User modifiedBy; private transient Integer missing; private transient Integer missingErrors; private transient Integer missingWarnings; private transient Integer skipped; private transient Integer errors; private transient Integer warnings; private List<String> rootEntityKeyValues; private List<Integer> entityCounts; private Map<Integer, Set<String>> minCountErrorCounts; private Map<Integer, Set<String>> minCountWarningCounts; private Map<Integer, Set<String>> maxCountErrorCounts; private Map<Integer, Set<String>> maxCountWarningCounts; private Map<Integer, Integer> errorCounts; private Map<Integer, Integer> warningCounts; private Set<Integer> skippedNodes; public CollectRecord(CollectSurvey survey, String versionName) { super(survey, versionName); this.step = Step.ENTRY; // use List to preserve the order of the keys and counts rootEntityKeyValues = new ArrayList<String>(); entityCounts = new ArrayList<Integer>(); initErrorCountInfo(); } private void initErrorCountInfo() { minCountErrorCounts = new HashMap<Integer, Set<String>>(); minCountWarningCounts = new HashMap<Integer, Set<String>>(); maxCountErrorCounts = new HashMap<Integer, Set<String>>(); maxCountWarningCounts = new HashMap<Integer, Set<String>>(); errorCounts = new HashMap<Integer, Integer>(); warningCounts = new HashMap<Integer, Integer>(); skippedNodes = new HashSet<Integer>(); skipped = null; missing = null; missingErrors = null; missingWarnings = null; errors = null; warnings = null; } public Node<?> deleteNode(Node<?> node) { if(node.isDetached()) { throw new IllegalArgumentException("Unable to delete a node already detached"); } Entity parentEntity = node.getParent(); int index = node.getIndex(); Node<?> deletedNode = parentEntity.remove(node.getName(), index); removeValidationCounts(deletedNode.getInternalId()); return deletedNode; } public void setErrorConfirmed(Attribute<?,?> attribute, boolean confirmed){ int fieldCount = attribute.getFieldCount(); for( int i=0; i <fieldCount; i++ ){ Field<?> field = attribute.getField(i); field.getState().set(CONFIRMED_ERROR_POSITION, confirmed); } } public boolean isErrorConfirmed(Attribute<?,?> attribute){ int fieldCount = attribute.getFieldCount(); for( int i=0; i <fieldCount; i++ ){ Field<?> field = attribute.getField(i); if( !field.getState().get(CONFIRMED_ERROR_POSITION) ){ return false; } } return true; } public void setMissingApproved(Entity parentEntity, String childName, boolean approved) { org.openforis.idm.model.State childState = parentEntity.getChildState(childName); childState.set(APPROVED_MISSING_POSITION, approved); } public boolean isMissingApproved(Entity parentEntity, String childName){ org.openforis.idm.model.State childState = parentEntity.getChildState(childName); return childState.get(APPROVED_MISSING_POSITION); } public void updateValidationMinCounts(Integer entityId, String childName, ValidationResultFlag flag) { Set<String> errors = clearEntityValidationCounts(minCountErrorCounts, entityId, childName); Set<String> warnings = clearEntityValidationCounts(minCountWarningCounts, entityId, childName); switch (flag) { case ERROR: errors.add(childName); break; case WARNING: warnings.add(childName); break; } this.missing = null; this.missingErrors = null; this.missingWarnings = null; this.errors = null; this.warnings = null; } public void updateValidationMaxCounts(Integer entityId, String childName, ValidationResultFlag flag) { Set<String> errors = clearEntityValidationCounts(maxCountErrorCounts, entityId, childName); Set<String> warnings = clearEntityValidationCounts(maxCountWarningCounts, entityId, childName); switch(flag) { case ERROR: errors.add(childName); break; case WARNING: warnings.add(childName); break; } this.errors = null; this.warnings = null; } public void updateValidationCounts(Integer attributeId, ValidationResults validationResults) { removeValidationCounts(attributeId); int errorCounts = validationResults.getErrors().size(); int warningCounts = validationResults.getWarnings().size(); this.errorCounts.put(attributeId, errorCounts); this.warningCounts.put(attributeId, warningCounts); errors = null; warnings = null; } public void updateSkippedCount(Integer attributeId) { removeValidationCounts(attributeId); skippedNodes.add(attributeId); skipped = null; } public void removeValidationCounts(Integer nodeId) { Node<?> node = this.getNodeByInternalId(nodeId); if(node instanceof Attribute<?, ?>) { skippedNodes.remove(nodeId); errorCounts.remove(nodeId); warningCounts.remove(nodeId); } else { minCountErrorCounts.remove(nodeId); maxCountErrorCounts.remove(nodeId); minCountWarningCounts.remove(nodeId); maxCountWarningCounts.remove(nodeId); } skipped = null; missing = null; missingErrors = null; missingWarnings = null; errors = null; warnings = null; } public Step getStep() { return step; } public void setStep(Step step) { this.step = step; } public State getState() { return state; } public void setState(State state) { this.state = state; } public Date getCreationDate() { return this.creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public User getCreatedBy() { return this.createdBy; } public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } public Date getModifiedDate() { return this.modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public User getModifiedBy() { return this.modifiedBy; } public void setModifiedBy(User modifiedBy) { this.modifiedBy = modifiedBy; } public Integer getSkipped() { if ( skipped == null ) { skipped = skippedNodes.size(); } return skipped; } public void setSkipped(Integer skipped) { this.skipped = skipped; } public Integer getMissing() { if (missing == null) { Integer errors = getMissingErrors(); Integer warnings = getMissingWarnings(); missing = errors + warnings; } return missing; } public Integer getMissingErrors() { if ( missingErrors == null ) { missingErrors = getMissingCount( minCountErrorCounts ); } return missingErrors; } public Integer getMissingWarnings() { if ( missingWarnings == null ) { missingWarnings = getMissingCount( minCountWarningCounts); } return missingWarnings; } public void setMissing(Integer missing) { this.missing = missing; } public Integer getErrors() { if(errors == null) { errors = getAttributeValidationCount(errorCounts); errors += getEntityValidationCount(maxCountErrorCounts); } return errors; } public void setErrors(Integer errors) { this.errors = errors; } public Integer getWarnings() { if(warnings == null) { warnings = getAttributeValidationCount(warningCounts); warnings += getEntityValidationCount(maxCountWarningCounts); } return warnings; } public void setWarnings(Integer warnings) { this.warnings = warnings; } public List<String> getRootEntityKeyValues() { return rootEntityKeyValues; } public void updateRootEntityKeyValues(){ Entity rootEntity = getRootEntity(); if(rootEntity != null) { rootEntityKeyValues = new ArrayList<String>(); EntityDefinition rootEntityDefn = rootEntity.getDefinition(); List<AttributeDefinition> keyDefns = rootEntityDefn.getKeyAttributeDefinitions(); for (AttributeDefinition keyDefn : keyDefns) { String keyValue = null; Node<?> keyNode = rootEntity.get(keyDefn.getName(), 0); if(keyNode instanceof CodeAttribute) { Code code = ((CodeAttribute) keyNode).getValue(); if(code != null) { keyValue = code.getCode(); } } else if(keyNode instanceof TextAttribute) { keyValue = ((TextAttribute) keyNode).getValue(); } else if(keyNode instanceof NumberAttribute<?>) { Object obj = ((NumberAttribute<?>) keyNode).getValue(); if(obj != null) { keyValue = obj.toString(); } } if(StringUtils.isNotEmpty(keyValue)){ rootEntityKeyValues.add(keyValue); } else { //todo throw error in this case? rootEntityKeyValues.add(null); } } } } public void updateEntityCounts() { Entity rootEntity = getRootEntity(); List<EntityDefinition> countableDefns = getCountableEntitiesInList(); //set counts List<Integer> counts = new ArrayList<Integer>(); for (EntityDefinition defn : countableDefns) { String name = defn.getName(); int count = rootEntity.getCount(name); counts.add(count); } entityCounts = counts; } public void setRootEntityKeyValues(List<String> keys) { this.rootEntityKeyValues = keys; } public List<Integer> getEntityCounts() { return entityCounts; } public void setEntityCounts(List<Integer> counts) { this.entityCounts = counts; } private Set<String> clearEntityValidationCounts(Map<Integer, Set<String>> counts, Integer entityId, String childName) { Set<String> set = counts.get(entityId); if(set == null) { set = new HashSet<String>(); counts.put(entityId, set); } else { set.remove(childName); } return set; } private Integer getEntityValidationCount(Map<Integer, Set<String>> map) { int count = 0; for (Set<String> set : map.values()) { count += set.size(); } return count; } private Integer getMissingCount(Map<Integer, Set<String>> minCounts) { int result = 0; Set<Integer> keySet = minCounts.keySet(); for (Integer id : keySet) { Entity entity = (Entity) getNodeByInternalId(id); Set<String> set = minCounts.get(id); for (String childName : set) { int missingCount = entity.getMissingCount(childName); result += missingCount; } } return result; } private Integer getAttributeValidationCount(Map<Integer, Integer> map) { int count = 0; for (Integer i : map.values()) { count += i; } return count; } /** * Clear all node states and all attribute symbols */ public void clearNodeStates() { Entity rootEntity = getRootEntity(); rootEntity.traverse( new NodeVisitor() { @Override public void visit(Node<? extends NodeDefinition> node, int idx) { if ( node instanceof Attribute ) { Attribute<?,?> attribute = (Attribute<?, ?>) node; // if ( step == Step.ENTRY ) { // attribute.clearFieldSymbols(); // } attribute.clearFieldStates(); attribute.clearValidationResults(); } else if( node instanceof Entity ) { Entity entity = (Entity) node; entity.clearChildStates(); EntityDefinition definition = entity.getDefinition(); List<NodeDefinition> childDefinitions = definition.getChildDefinitions(); for (NodeDefinition childDefinition : childDefinitions) { String childName = childDefinition.getName(); entity.clearRelevanceState(childName); entity.clearRequiredState(childName); } } } } ); } /** * Update all derived states of all nodes */ public void updateDerivedStates() { initErrorCountInfo(); Entity rootEntity = getRootEntity(); rootEntity.traverse(new NodeVisitor() { @Override public void visit(Node<? extends NodeDefinition> node, int idx) { if ( node instanceof Attribute ) { Attribute<?,?> attribute = (Attribute<?, ?>) node; attribute.validateValue(); } else if ( node instanceof Entity ) { Entity entity = (Entity) node; EntityDefinition definition = entity.getDefinition(); List<NodeDefinition> childDefinitions = definition.getChildDefinitions(); for (NodeDefinition childDefinition : childDefinitions) { String childName = childDefinition.getName(); entity.validateMaxCount( childName ); entity.validateMinCount( childName ); } } } }); } /** * Returns first level entity definitions that have the attribute countInSummaryList set to true * * @param rootEntityDefinition * @return */ private List<EntityDefinition> getCountableEntitiesInList() { List<EntityDefinition> result = new ArrayList<EntityDefinition>(); EntityDefinition rootEntityDefinition = getRootEntity().getDefinition(); List<NodeDefinition> childDefinitions = rootEntityDefinition .getChildDefinitions(); for (NodeDefinition childDefinition : childDefinitions) { if(childDefinition instanceof EntityDefinition) { EntityDefinition entityDefinition = (EntityDefinition) childDefinition; String annotation = childDefinition.getAnnotation(COUNT_ANNOTATION); if(annotation != null && Boolean.parseBoolean(annotation)) { result.add(entityDefinition); } } } return result; } }
OFC-557 When applying default, mark as default applied in binary state
collect-core/src/main/java/org/openforis/collect/model/CollectRecord.java
OFC-557 When applying default, mark as default applied in binary state
<ide><path>ollect-core/src/main/java/org/openforis/collect/model/CollectRecord.java <ide> <ide> private static final int APPROVED_MISSING_POSITION = 0; <ide> private static final int CONFIRMED_ERROR_POSITION = 0; <add> private static final int DEFAULT_APPLIED_POSITION = 1; <ide> <ide> public enum Step { <ide> ENTRY(1), CLEANSING(2), ANALYSIS(3); <ide> org.openforis.idm.model.State childState = parentEntity.getChildState(childName); <ide> return childState.get(APPROVED_MISSING_POSITION); <ide> } <add> <add> public void setDefaultValueApplied(Attribute<?, ?> attribute, boolean applied) { <add> int fieldCount = attribute.getFieldCount(); <add> <add> for( int i=0; i <fieldCount; i++ ){ <add> Field<?> field = attribute.getField(i); <add> field.getState().set(DEFAULT_APPLIED_POSITION, applied); <add> } <add> } <add> <add> public boolean isDefaultValueApplied(Attribute<?, ?> attribute) { <add> int fieldCount = attribute.getFieldCount(); <add> for( int i=0; i <fieldCount; i++ ){ <add> Field<?> field = attribute.getField(i); <add> if( !field.getState().get(DEFAULT_APPLIED_POSITION) ){ <add> return false; <add> } <add> } <add> return true; <add> } <ide> <ide> public void updateValidationMinCounts(Integer entityId, String childName, ValidationResultFlag flag) { <ide> Set<String> errors = clearEntityValidationCounts(minCountErrorCounts, entityId, childName);
Java
lgpl-2.1
a0911252d0914f5755bb316b094a1aaf5fe47a23
0
hal/core,hal/core,hal/core,hal/core,hal/core
/* * JBoss, Home of Professional Open Source * Copyright 2013 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.patching.wizard; import static org.jboss.as.console.client.shared.patching.PatchType.CUMULATIVE; import static org.jboss.as.console.client.shared.patching.PatchType.ONE_OFF; import java.util.HashMap; import java.util.Map; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RadioButton; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.administration.role.form.EnumFormItem; import org.jboss.as.console.client.shared.patching.PatchInfo; import org.jboss.as.console.client.shared.patching.PatchType; import org.jboss.ballroom.client.widgets.forms.Form; import org.jboss.ballroom.client.widgets.forms.TextItem; /** * @author Harald Pehl */ public class AppliedOkStep extends ApplyPatchWizard.Step { private final String serverOrHost; private RadioButton yes; private RadioButton no; private Form<PatchInfo> form; public AppliedOkStep(final ApplyPatchWizard wizard) { super(wizard, Console.CONSTANTS.patch_manager_applied_success_title(), Console.CONSTANTS.common_label_finish()); this.serverOrHost = wizard.context.standalone ? "server" : "host"; } @Override IsWidget header() { return new HTML("<h3 class=\"success\"><i class=\"icon-ok icon-large\"></i> " + title + "</h3>"); } @Override protected IsWidget body() { FlowPanel body = new FlowPanel(); form = new Form<PatchInfo>(PatchInfo.class); form.setEnabled(false); TextItem id = new TextItem("id", "ID"); TextItem version = new TextItem("version", "Version"); Map<PatchType, String> values = new HashMap<PatchType, String>(); values.put(CUMULATIVE, CUMULATIVE.label()); values.put(ONE_OFF, ONE_OFF.label()); EnumFormItem<PatchType> type = new EnumFormItem<PatchType>("type", Console.CONSTANTS.common_label_type()); type.setValues(values); form.setFields(id, version, type); body.add(form); body.add(new HTML("<h3 class=\"apply-patch-followup-header\">" + Console.MESSAGES .patch_manager_restart_title(serverOrHost) + "</h3>")); body.add(new Label(Console.MESSAGES.patch_manager_applied_restart_body(serverOrHost))); yes = new RadioButton("restart_host", Console.MESSAGES.patch_manager_restart_yes(serverOrHost)); yes.addStyleName("apply-patch-radio"); yes.setValue(true); no = new RadioButton("restart_host", Console.MESSAGES.patch_manager_restart_no(serverOrHost)); no.addStyleName("apply-patch-radio"); body.add(yes); body.add(no); return body; } @Override void onShow(final ApplyPatchWizard.Context context) { form.edit(context.patchInfo); } @Override void onNext() { wizard.context.restartToUpdate = yes.getValue(); super.onNext(); } }
gui/src/main/java/org/jboss/as/console/client/shared/patching/wizard/AppliedOkStep.java
/* * JBoss, Home of Professional Open Source * Copyright 2013 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.patching.wizard; import static org.jboss.as.console.client.shared.patching.PatchType.CUMULATIVE; import static org.jboss.as.console.client.shared.patching.PatchType.ONE_OFF; import java.util.HashMap; import java.util.Map; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RadioButton; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.administration.role.form.EnumFormItem; import org.jboss.as.console.client.shared.patching.PatchInfo; import org.jboss.as.console.client.shared.patching.PatchType; import org.jboss.ballroom.client.widgets.forms.Form; import org.jboss.ballroom.client.widgets.forms.TextItem; /** * @author Harald Pehl */ public class AppliedOkStep extends ApplyPatchWizard.Step { private final String serverOrHost; private RadioButton yes; private RadioButton no; private Form<PatchInfo> form; public AppliedOkStep(final ApplyPatchWizard wizard) { super(wizard, Console.CONSTANTS.patch_manager_applied_success_title()); this.serverOrHost = wizard.context.standalone ? "server" : "host"; } @Override IsWidget header() { return new HTML("<h3 class=\"success\"><i class=\"icon-ok icon-large\"></i> " + title + "</h3>"); } @Override protected IsWidget body() { FlowPanel body = new FlowPanel(); form = new Form<PatchInfo>(PatchInfo.class); form.setEnabled(false); TextItem id = new TextItem("id", "ID"); TextItem version = new TextItem("version", "Version"); Map<PatchType, String> values = new HashMap<PatchType, String>(); values.put(CUMULATIVE, CUMULATIVE.label()); values.put(ONE_OFF, ONE_OFF.label()); EnumFormItem<PatchType> type = new EnumFormItem<PatchType>("type", Console.CONSTANTS.common_label_type()); type.setValues(values); form.setFields(id, version, type); body.add(form); body.add(new HTML("<h3 class=\"apply-patch-followup-header\">" + Console.MESSAGES.patch_manager_restart_title(serverOrHost) + "</h3>")); body.add(new Label(Console.MESSAGES.patch_manager_applied_restart_body(serverOrHost))); yes = new RadioButton("restart_host", Console.MESSAGES.patch_manager_restart_yes(serverOrHost)); yes.addStyleName("apply-patch-radio"); yes.setValue(true); no = new RadioButton("restart_host", Console.MESSAGES.patch_manager_restart_no(serverOrHost)); no.addStyleName("apply-patch-radio"); body.add(yes); body.add(no); return body; } @Override void onShow(final ApplyPatchWizard.Context context) { form.edit(context.patchInfo); } @Override void onNext() { wizard.context.restartToUpdate = yes.getValue(); super.onNext(); } }
EAP6-18: StopServersFailedStep - wip
gui/src/main/java/org/jboss/as/console/client/shared/patching/wizard/AppliedOkStep.java
EAP6-18: StopServersFailedStep - wip
<ide><path>ui/src/main/java/org/jboss/as/console/client/shared/patching/wizard/AppliedOkStep.java <ide> private Form<PatchInfo> form; <ide> <ide> public AppliedOkStep(final ApplyPatchWizard wizard) { <del> super(wizard, Console.CONSTANTS.patch_manager_applied_success_title()); <add> super(wizard, Console.CONSTANTS.patch_manager_applied_success_title(), Console.CONSTANTS.common_label_finish()); <ide> this.serverOrHost = wizard.context.standalone ? "server" : "host"; <ide> } <ide> <ide> form.setFields(id, version, type); <ide> body.add(form); <ide> <del> body.add(new HTML("<h3 class=\"apply-patch-followup-header\">" + Console.MESSAGES.patch_manager_restart_title(serverOrHost) + "</h3>")); <add> body.add(new HTML("<h3 class=\"apply-patch-followup-header\">" + Console.MESSAGES <add> .patch_manager_restart_title(serverOrHost) + "</h3>")); <ide> body.add(new Label(Console.MESSAGES.patch_manager_applied_restart_body(serverOrHost))); <ide> <ide> yes = new RadioButton("restart_host", Console.MESSAGES.patch_manager_restart_yes(serverOrHost));
Java
apache-2.0
2003988bf9513831622eaa700ccc4276cf5d4e98
0
SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list,SpineEventEngine/todo-list
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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.spine3.examples.todolist.q.projection; import org.spine3.base.EventContext; import org.spine3.examples.todolist.LabelColor; import org.spine3.examples.todolist.LabelDetails; import org.spine3.examples.todolist.LabelId; import org.spine3.examples.todolist.TaskDetails; import org.spine3.examples.todolist.TaskId; import org.spine3.examples.todolist.c.enrichments.DetailsEnrichment; import org.spine3.examples.todolist.c.events.LabelAssignedToTask; import org.spine3.examples.todolist.c.events.LabelDetailsUpdated; import org.spine3.examples.todolist.c.events.LabelRemovedFromTask; import org.spine3.examples.todolist.c.events.LabelledTaskRestored; import org.spine3.examples.todolist.c.events.TaskCompleted; import org.spine3.examples.todolist.c.events.TaskDeleted; import org.spine3.examples.todolist.c.events.TaskDescriptionUpdated; import org.spine3.examples.todolist.c.events.TaskDueDateUpdated; import org.spine3.examples.todolist.c.events.TaskPriorityUpdated; import org.spine3.examples.todolist.c.events.TaskReopened; import org.spine3.server.event.Subscribe; import org.spine3.server.projection.Projection; import java.util.List; import java.util.stream.Collectors; import static org.spine3.examples.todolist.EnrichmentHelper.getEnrichment; import static org.spine3.examples.todolist.q.projection.ProjectionHelper.removeViewByTaskId; import static org.spine3.examples.todolist.q.projection.ProjectionHelper.updateTaskViewList; /** * A projection state of the created tasks marked with a certain label. * * <p> Contains the data about the task view. * <p> This view includes all tasks per label that are neither in a draft state nor deleted. * * @author Illia Shepilov */ @SuppressWarnings("OverlyCoupledClass") public class LabelledTasksViewProjection extends Projection<LabelId, LabelledTasksView> { /** * Creates a new instance. * * @param id the ID for the new instance * @throws IllegalArgumentException if the ID is not of one of the supported types */ public LabelledTasksViewProjection(LabelId id) { super(id); } @Subscribe public void on(LabelAssignedToTask event, EventContext context) { final DetailsEnrichment enrichment = getEnrichment(DetailsEnrichment.class, context); final TaskDetails taskDetails = enrichment.getTaskDetails(); final LabelId labelId = event.getLabelId(); final TaskId taskId = event.getTaskId(); final TaskView taskView = viewFor(taskDetails, labelId, taskId); final LabelDetails labelDetails = enrichment.getLabelDetails(); final LabelledTasksView state = addLabel(taskView, labelDetails).setLabelId(labelId) .build(); incrementState(state); } @Subscribe public void on(LabelledTaskRestored event, EventContext context) { final DetailsEnrichment enrichment = getEnrichment(DetailsEnrichment.class, context); final TaskDetails taskDetails = enrichment.getTaskDetails(); final LabelId labelId = event.getLabelId(); final TaskId taskId = event.getTaskId(); final TaskView taskView = viewFor(taskDetails, labelId, taskId); final LabelDetails labelDetails = enrichment.getLabelDetails(); final LabelledTasksView state = addLabel(taskView, labelDetails).setLabelId(labelId) .build(); incrementState(state); } @Subscribe public void on(LabelRemovedFromTask event) { final LabelId labelId = event.getLabelId(); final boolean isEquals = getState().getLabelId() .equals(labelId); if (isEquals) { final LabelledTasksView state = LabelledTasksView.newBuilder() .setLabelId(getState().getLabelId()) .build(); incrementState(state); } } @Subscribe public void on(TaskDeleted event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList() .stream() .collect(Collectors.toList()); final TaskListView taskListView = removeViewByTaskId(views, event.getTaskId()); final LabelledTasksView labelledTasksView = getState(); final LabelledTasksView state = getState().newBuilderForType() .setLabelledTasks(taskListView) .setLabelTitle(labelledTasksView.getLabelTitle()) .setLabelColor(labelledTasksView.getLabelColor()) .build(); incrementState(state); } @Subscribe public void on(TaskDescriptionUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskPriorityUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskDueDateUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskCompleted event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskReopened event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(LabelDetailsUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelDetails newDetails = event.getLabelDetailsChange() .getNewDetails(); final LabelledTasksView state = toViewState(newDetails, updatedList); incrementState(state); } private static TaskView viewFor(TaskDetails taskDetails, LabelId labelId, TaskId taskId) { final TaskView result = TaskView.newBuilder() .setId(taskId) .setLabelId(labelId) .setDescription(taskDetails.getDescription()) .setPriority(taskDetails.getPriority()) .build(); return result; } private LabelledTasksView toViewState(LabelDetails labelDetails, List<TaskView> updatedList) { final LabelledTasksView state = getState(); final TaskListView listView = TaskListView.newBuilder() .addAllItems(updatedList) .build(); final LabelledTasksView result = getState().newBuilderForType() .setLabelId(state.getLabelId()) .setLabelColor(LabelColorView.valueOf(labelDetails.getColor())) .setLabelTitle(labelDetails.getTitle()) .setLabelledTasks(listView) .build(); return result; } private LabelledTasksView toViewState(List<TaskView> updatedList) { final LabelledTasksView state = getState(); final TaskListView listView = TaskListView.newBuilder() .addAllItems(updatedList) .build(); final LabelledTasksView result = getState().newBuilderForType() .setLabelId(state.getLabelId()) .setLabelColor(state.getLabelColor()) .setLabelTitle(state.getLabelTitle()) .setLabelledTasks(listView) .build(); return result; } private LabelledTasksView.Builder addLabel(TaskView taskView, LabelDetails labelDetails) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList() .stream() .collect(Collectors.toList()); views.add(taskView); final TaskListView taskListView = TaskListView.newBuilder() .addAllItems(views) .build(); final LabelledTasksView.Builder result = getState().newBuilderForType() .setLabelledTasks(taskListView) .setLabelTitle(labelDetails.getTitle()); if (labelDetails.getColor() != LabelColor.LC_UNDEFINED) { final String hexColor = LabelColorView.valueOf(labelDetails.getColor()); result.setLabelColor(hexColor); } return result; } }
api-java/src/main/java/org/spine3/examples/todolist/q/projection/LabelledTasksViewProjection.java
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * 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.spine3.examples.todolist.q.projection; import org.spine3.base.EventContext; import org.spine3.examples.todolist.LabelColor; import org.spine3.examples.todolist.LabelDetails; import org.spine3.examples.todolist.LabelId; import org.spine3.examples.todolist.TaskDetails; import org.spine3.examples.todolist.TaskId; import org.spine3.examples.todolist.c.enrichments.DetailsEnrichment; import org.spine3.examples.todolist.c.events.LabelAssignedToTask; import org.spine3.examples.todolist.c.events.LabelDetailsUpdated; import org.spine3.examples.todolist.c.events.LabelRemovedFromTask; import org.spine3.examples.todolist.c.events.LabelledTaskRestored; import org.spine3.examples.todolist.c.events.TaskCompleted; import org.spine3.examples.todolist.c.events.TaskDeleted; import org.spine3.examples.todolist.c.events.TaskDescriptionUpdated; import org.spine3.examples.todolist.c.events.TaskDueDateUpdated; import org.spine3.examples.todolist.c.events.TaskPriorityUpdated; import org.spine3.examples.todolist.c.events.TaskReopened; import org.spine3.server.event.Subscribe; import org.spine3.server.projection.Projection; import java.util.List; import java.util.stream.Collectors; import static org.spine3.examples.todolist.EnrichmentHelper.getEnrichment; import static org.spine3.examples.todolist.q.projection.ProjectionHelper.removeViewByTaskId; import static org.spine3.examples.todolist.q.projection.ProjectionHelper.updateTaskViewList; /** * A projection state of the created tasks marked with a certain label. * * <p> Contains the data about the task view. * <p> This view includes all tasks per label that are neither in a draft state nor deleted. * * @author Illia Shepilov */ @SuppressWarnings("OverlyCoupledClass") public class LabelledTasksViewProjection extends Projection<LabelId, LabelledTasksView> { /** * Creates a new instance. * * @param id the ID for the new instance * @throws IllegalArgumentException if the ID is not of one of the supported types */ public LabelledTasksViewProjection(LabelId id) { super(id); } @Subscribe public void on(LabelAssignedToTask event, EventContext context) { final DetailsEnrichment enrichment = getEnrichment(DetailsEnrichment.class, context); final TaskDetails taskDetails = enrichment.getTaskDetails(); final LabelId labelId = event.getLabelId(); final TaskId taskId = event.getTaskId(); final TaskView taskView = constructTaskView(taskDetails, labelId, taskId); final LabelDetails labelDetails = enrichment.getLabelDetails(); final LabelledTasksView state = addLabel(taskView, labelDetails).setLabelId(labelId) .build(); incrementState(state); } @Subscribe public void on(LabelledTaskRestored event, EventContext context) { final DetailsEnrichment enrichment = getEnrichment(DetailsEnrichment.class, context); final TaskDetails taskDetails = enrichment.getTaskDetails(); final LabelId labelId = event.getLabelId(); final TaskId taskId = event.getTaskId(); final TaskView taskView = constructTaskView(taskDetails, labelId, taskId); final LabelDetails labelDetails = enrichment.getLabelDetails(); final LabelledTasksView state = addLabel(taskView, labelDetails).setLabelId(labelId) .build(); incrementState(state); } @Subscribe public void on(LabelRemovedFromTask event) { final LabelId labelId = event.getLabelId(); final boolean isEquals = getState().getLabelId() .equals(labelId); if (isEquals) { final LabelledTasksView state = LabelledTasksView.newBuilder() .setLabelId(getState().getLabelId()) .build(); incrementState(state); } } @Subscribe public void on(TaskDeleted event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList() .stream() .collect(Collectors.toList()); final TaskListView taskListView = removeViewByTaskId(views, event.getTaskId()); final LabelledTasksView labelledTasksView = getState(); final LabelledTasksView state = getState().newBuilderForType() .setLabelledTasks(taskListView) .setLabelTitle(labelledTasksView.getLabelTitle()) .setLabelColor(labelledTasksView.getLabelColor()) .build(); incrementState(state); } @Subscribe public void on(TaskDescriptionUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskPriorityUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskDueDateUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskCompleted event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(TaskReopened event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelledTasksView state = toViewState(updatedList); incrementState(state); } @Subscribe public void on(LabelDetailsUpdated event) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList(); final List<TaskView> updatedList = updateTaskViewList(views, event); final LabelDetails newDetails = event.getLabelDetailsChange() .getNewDetails(); final LabelledTasksView state = toViewState(newDetails, updatedList); incrementState(state); } private static TaskView constructTaskView(TaskDetails taskDetails, LabelId labelId, TaskId taskId) { final TaskView result = TaskView.newBuilder() .setId(taskId) .setLabelId(labelId) .setDescription(taskDetails.getDescription()) .setPriority(taskDetails.getPriority()) .build(); return result; } private LabelledTasksView toViewState(LabelDetails labelDetails, List<TaskView> updatedList) { final LabelledTasksView state = getState(); final TaskListView listView = TaskListView.newBuilder() .addAllItems(updatedList) .build(); final LabelledTasksView result = getState().newBuilderForType() .setLabelId(state.getLabelId()) .setLabelColor(LabelColorView.valueOf(labelDetails.getColor())) .setLabelTitle(labelDetails.getTitle()) .setLabelledTasks(listView) .build(); return result; } private LabelledTasksView toViewState(List<TaskView> updatedList) { final LabelledTasksView state = getState(); final TaskListView listView = TaskListView.newBuilder() .addAllItems(updatedList) .build(); final LabelledTasksView result = getState().newBuilderForType() .setLabelId(state.getLabelId()) .setLabelColor(state.getLabelColor()) .setLabelTitle(state.getLabelTitle()) .setLabelledTasks(listView) .build(); return result; } private LabelledTasksView.Builder addLabel(TaskView taskView, LabelDetails labelDetails) { final List<TaskView> views = getState().getLabelledTasks() .getItemsList() .stream() .collect(Collectors.toList()); views.add(taskView); final TaskListView taskListView = TaskListView.newBuilder() .addAllItems(views) .build(); final LabelledTasksView.Builder result = getState().newBuilderForType() .setLabelledTasks(taskListView) .setLabelTitle(labelDetails.getTitle()); if (labelDetails.getColor() != LabelColor.LC_UNDEFINED) { final String hexColor = LabelColorView.valueOf(labelDetails.getColor()); result.setLabelColor(hexColor); } return result; } }
Rename method in the `LabelledTasksViewProjection` class.
api-java/src/main/java/org/spine3/examples/todolist/q/projection/LabelledTasksViewProjection.java
Rename method in the `LabelledTasksViewProjection` class.
<ide><path>pi-java/src/main/java/org/spine3/examples/todolist/q/projection/LabelledTasksViewProjection.java <ide> final LabelId labelId = event.getLabelId(); <ide> final TaskId taskId = event.getTaskId(); <ide> <del> final TaskView taskView = constructTaskView(taskDetails, labelId, taskId); <add> final TaskView taskView = viewFor(taskDetails, labelId, taskId); <ide> final LabelDetails labelDetails = enrichment.getLabelDetails(); <ide> final LabelledTasksView state = addLabel(taskView, labelDetails).setLabelId(labelId) <ide> .build(); <ide> final LabelId labelId = event.getLabelId(); <ide> final TaskId taskId = event.getTaskId(); <ide> <del> final TaskView taskView = constructTaskView(taskDetails, labelId, taskId); <add> final TaskView taskView = viewFor(taskDetails, labelId, taskId); <ide> final LabelDetails labelDetails = enrichment.getLabelDetails(); <ide> final LabelledTasksView state = addLabel(taskView, labelDetails).setLabelId(labelId) <ide> .build(); <ide> incrementState(state); <ide> } <ide> <del> private static TaskView constructTaskView(TaskDetails taskDetails, LabelId labelId, TaskId taskId) { <add> private static TaskView viewFor(TaskDetails taskDetails, LabelId labelId, TaskId taskId) { <ide> final TaskView result = TaskView.newBuilder() <ide> .setId(taskId) <ide> .setLabelId(labelId)
Java
mit
9c604d66fb99ec833937273bef2036aeca24523c
0
maslowis/twitter-ripper
/* * The MIT License (MIT) * * Copyright (c) 2015 Ivan Maslov * * 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 info.maslowis.twitterripper.application; import com.beust.jcommander.JCommander; import com.beust.jcommander.MissingCommandException; import com.beust.jcommander.ParameterException; import info.maslowis.twitterripper.command.Command; import info.maslowis.twitterripper.command.ExecuteCmdException; import info.maslowis.twitterripper.jcommander.JCommanderFactory; import jline.console.ConsoleReader; import org.apache.log4j.Logger; import java.io.IOException; import java.util.List; import static java.lang.System.exit; import static java.lang.System.out; import static org.fusesource.jansi.Ansi.*; /** * Console listener * <p/> * <p>Listen console input and run a command in separate task</p> * * @author Ivan Maslov */ class ConsoleListener implements Runnable { private final static Logger logger = Logger.getLogger(ConsoleListener.class); private final ConsoleReader reader; ConsoleListener(ConsoleReader reader) { this.reader = reader; } @Override public void run() { printWelcome(); while (true) { try { String line = reader.readLine(); if (line == null) return; if (line.isEmpty()) { printEnter(); continue; } go(line); } catch (IOException e) { logger.error("Error reading input", e); exit(-1); } } } private void go(String line) { String inputCommand = ""; try { final String[] input = line.split(" "); if (input.length > 0) { inputCommand = input[0]; final JCommander jCommander = JCommanderFactory.getInstance(); jCommander.parse(input); final String parsedCommand = jCommander.getParsedCommand(); final List<Object> commands = jCommander.getCommands().get(parsedCommand).getObjects(); for (final Object object : commands) { if (object instanceof Command) { Command command = (Command) object; try { command.execute(); } catch (ExecuteCmdException e) { logger.error("Error", e); } finally { printEnter(); } } } } else { logger.info("Command not found!"); } } catch (MissingCommandException e) { logger.info(inputCommand + ": command not found!"); printEnter(); } catch (ParameterException e) { logger.info(inputCommand + ": invalid parameters passed " + e.getMessage()); printEnter(); } catch (Exception e) { logger.error("Error", e); } } private void printWelcome() { out.println(ansi().eraseScreen().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Welcome to Twitter-Ripper application!").newline().reset()); JCommanderFactory.getInstance().usage(); printEnter(); } private void printEnter() { logger.info(System.lineSeparator()); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Enter the command:").reset()); } }
src/main/java/info/maslowis/twitterripper/application/ConsoleListener.java
/* * The MIT License (MIT) * * Copyright (c) 2015 Ivan Maslov * * 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 info.maslowis.twitterripper.application; import com.beust.jcommander.JCommander; import com.beust.jcommander.MissingCommandException; import com.beust.jcommander.ParameterException; import info.maslowis.twitterripper.command.Command; import info.maslowis.twitterripper.command.ExecuteCmdException; import info.maslowis.twitterripper.jcommander.JCommanderFactory; import jline.console.ConsoleReader; import org.apache.log4j.Logger; import java.io.IOException; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import static java.lang.System.exit; import static java.lang.System.out; import static org.fusesource.jansi.Ansi.*; /** * Console listener * <p/> * <p>Listen console input and run a command in separate task</p> * * @author Ivan Maslov */ class ConsoleListener implements Runnable { private final static Logger logger = Logger.getLogger(ConsoleListener.class); private final Executor executorCommand; private final ConsoleReader reader; ConsoleListener(ConsoleReader reader) { this.executorCommand = Executors.newCachedThreadPool(); this.reader = reader; } @Override public void run() { printWelcome(); while (true) { try { String line = reader.readLine(); if (line == null) return; if (line.isEmpty()) { printEnter(); continue; } go(line); } catch (IOException e) { logger.error("Error reading input", e); exit(-1); } } } private void go(String line) { String inputCommand = ""; try { final String[] input = line.split(" "); if (input.length > 0) { inputCommand = input[0]; final JCommander jCommander = JCommanderFactory.getInstance(); jCommander.parse(input); final String parsedCommand = jCommander.getParsedCommand(); final List<Object> commands = jCommander.getCommands().get(parsedCommand).getObjects(); for (final Object object : commands) { if (object instanceof Command) { executorCommand.execute(new Runnable() { @Override public void run() { Command command = (Command) object; try { command.execute(); } catch (ExecuteCmdException e) { logger.error("Error", e); } finally { printEnter(); } } }); } } } else { logger.info("Command not found!"); } } catch (MissingCommandException e) { logger.info(inputCommand + ": command not found!"); printEnter(); } catch (ParameterException e) { logger.info(inputCommand + ": invalid parameters passed " + e.getMessage()); printEnter(); } catch (Exception e) { logger.error("Error", e); } } private void printWelcome() { out.println(ansi().eraseScreen().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Welcome to Twitter-Ripper application!").newline().reset()); JCommanderFactory.getInstance().usage(); printEnter(); } private void printEnter() { logger.info(System.lineSeparator()); out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Enter the command:").reset()); } }
Delete the executor for commands
src/main/java/info/maslowis/twitterripper/application/ConsoleListener.java
Delete the executor for commands
<ide><path>rc/main/java/info/maslowis/twitterripper/application/ConsoleListener.java <ide> <ide> import java.io.IOException; <ide> import java.util.List; <del>import java.util.concurrent.Executor; <del>import java.util.concurrent.Executors; <ide> <ide> import static java.lang.System.exit; <ide> import static java.lang.System.out; <ide> <ide> private final static Logger logger = Logger.getLogger(ConsoleListener.class); <ide> <del> private final Executor executorCommand; <ide> private final ConsoleReader reader; <ide> <ide> ConsoleListener(ConsoleReader reader) { <del> this.executorCommand = Executors.newCachedThreadPool(); <ide> this.reader = reader; <ide> } <ide> <ide> final List<Object> commands = jCommander.getCommands().get(parsedCommand).getObjects(); <ide> for (final Object object : commands) { <ide> if (object instanceof Command) { <del> executorCommand.execute(new Runnable() { <del> @Override <del> public void run() { <del> Command command = (Command) object; <del> try { <del> command.execute(); <del> } catch (ExecuteCmdException e) { <del> logger.error("Error", e); <del> } finally { <del> printEnter(); <del> } <del> } <del> }); <add> Command command = (Command) object; <add> try { <add> command.execute(); <add> } catch (ExecuteCmdException e) { <add> logger.error("Error", e); <add> } finally { <add> printEnter(); <add> } <ide> } <ide> } <ide> } else {
Java
apache-2.0
4f2b6d2492a64753c52a6edd9c02894c45c8dac5
0
vherilier/jmeter,ubikloadpack/jmeter,etnetera/jmeter,etnetera/jmeter,etnetera/jmeter,etnetera/jmeter,ubikloadpack/jmeter,vherilier/jmeter,ubikloadpack/jmeter,vherilier/jmeter,ubikloadpack/jmeter,etnetera/jmeter,vherilier/jmeter
/* * 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.jmeter.testbeans.gui; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyEditorSupport; import javax.swing.JTextField; /** * This class implements a property editor for possible null String properties that * supports custom editing (i.e.: provides a GUI component) based on a text * field. * <p> * The provided GUI is a simple text field. * */ class FieldStringEditor extends PropertyEditorSupport implements ActionListener, FocusListener { /** * This will hold the text editing component, either a plain JTextField (in * cases where the combo box would not have other options than 'Edit'), or * the text editing component in the combo box. */ private final JTextField textField; /** * Value on which we started the editing. Used to avoid firing * PropertyChanged events when there's not been such change. */ private String initialValue; protected FieldStringEditor() { super(); textField = new JTextField(); textField.addActionListener(this); textField.addFocusListener(this); initialValue = textField.getText(); } @Override public String getAsText() { return textField.getText(); } @Override public void setAsText(String value) { initialValue = value; textField.setText(value); } @Override public Object getValue() { return getAsText(); } @Override public void setValue(Object value) { if (value instanceof String) { setAsText((String) value); } else if (value == null) { setAsText(null); } else { throw new IllegalArgumentException("Expected String but got " + value.getClass() + ", value=" + value); } } /** * {@inheritDoc} */ @Override public Component getCustomEditor() { return textField; } // TODO should this implement supportsCustomEditor() ? /** * {@inheritDoc} */ @Override public void firePropertyChange() { String newValue = getAsText(); if (equalOldValueOrBothNull(newValue)) { return; } initialValue = newValue; super.firePropertyChange(); } private boolean equalOldValueOrBothNull(String newValue) { return initialValue != null && initialValue.equals(newValue) || initialValue == null && newValue == null; } /** * {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { firePropertyChange(); } /** * {@inheritDoc} */ @Override public void focusGained(FocusEvent e) { } /** * {@inheritDoc} */ @Override public void focusLost(FocusEvent e) { firePropertyChange(); } }
src/core/org/apache/jmeter/testbeans/gui/FieldStringEditor.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.jmeter.testbeans.gui; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyEditorSupport; import javax.swing.JTextField; /** * This class implements a property editor for possible null String properties that * supports custom editing (i.e.: provides a GUI component) based on a text * field. * <p> * The provided GUI is a simple text field. * */ class FieldStringEditor extends PropertyEditorSupport implements ActionListener, FocusListener { /** * This will hold the text editing component, either a plain JTextField (in * cases where the combo box would not have other options than 'Edit'), or * the text editing component in the combo box. */ private final JTextField textField; /** * Value on which we started the editing. Used to avoid firing * PropertyChanged events when there's not been such change. */ private String initialValue; protected FieldStringEditor() { super(); textField = new JTextField(); textField.addActionListener(this); textField.addFocusListener(this); initialValue = textField.getText(); } @Override public String getAsText() { return textField.getText(); } @Override public void setAsText(String value) { initialValue = value; textField.setText(value); } @Override public Object getValue() { return getAsText(); } @Override public void setValue(Object value) { if (value instanceof String) { setAsText((String) value); } else if (value == null) { setAsText(""); } else { throw new IllegalArgumentException("Expected String but got " + value.getClass() + ", value=" + value); } } /** * {@inheritDoc} */ @Override public Component getCustomEditor() { return textField; } // TODO should this implement supportsCustomEditor() ? /** * {@inheritDoc} */ @Override public void firePropertyChange() { String newValue = getAsText(); if (equalOldValueOrBothNull(newValue)) { return; } initialValue = newValue; super.firePropertyChange(); } private boolean equalOldValueOrBothNull(String newValue) { return initialValue != null && initialValue.equals(newValue) || initialValue == null && newValue == null; } /** * {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { firePropertyChange(); } /** * {@inheritDoc} */ @Override public void focusGained(FocusEvent e) { } /** * {@inheritDoc} */ @Override public void focusLost(FocusEvent e) { firePropertyChange(); } }
Set null explicitly in FieldStringEditor to allow undefined values Relates to #394 on github. git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1842263 13f79535-47bb-0310-9956-ffa450edef68
src/core/org/apache/jmeter/testbeans/gui/FieldStringEditor.java
Set null explicitly in FieldStringEditor to allow undefined values
<ide><path>rc/core/org/apache/jmeter/testbeans/gui/FieldStringEditor.java <ide> if (value instanceof String) { <ide> setAsText((String) value); <ide> } else if (value == null) { <del> setAsText(""); <add> setAsText(null); <ide> } else { <ide> throw new IllegalArgumentException("Expected String but got " + value.getClass() + ", value=" + value); <ide> }
Java
apache-2.0
d38a82b1ad136f51e5864f643c7244f1a6328d31
0
microcks/microcks,microcks/microcks,microcks/microcks,microcks/microcks,microcks/microcks
/* * Licensed to Laurent Broudoux (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author 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 io.github.microcks.util.openapi; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.github.microcks.domain.*; import io.github.microcks.util.DispatchStyles; import io.github.microcks.util.MockRepositoryImportException; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * This is a test case for class OpenAPIImporter. * @author laurent */ public class OpenAPIImporterTest { @Test public void testSimpleOpenAPIImportYAML() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi.yaml"); } catch (IOException ioe) { fail("Exception should not be thrown"); } importAndAssertOnSimpleOpenAPI(importer); } @Test public void testSimpleOpenAPIImportJSON() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi.json"); } catch (IOException ioe) { fail("Exception should not be thrown"); } importAndAssertOnSimpleOpenAPI(importer); } @Test public void testOpenAPIImportYAMLWithHeaders() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi-headers.yaml"); } catch (IOException ioe) { fail("Exception should not be thrown"); } // Check that basic service properties are there. List<Service> services = null; try { services = importer.getServiceDefinitions(); } catch (MockRepositoryImportException e) { fail("Exception should not be thrown"); } assertEquals(1, services.size()); Service service = services.get(0); assertEquals("OpenAPI Car API", service.getName()); Assert.assertEquals(ServiceType.REST, service.getType()); assertEquals("1.0.0", service.getVersion()); // Check that resources have been parsed, correctly renamed, etc... List<Resource> resources = importer.getResourceDefinitions(service); assertEquals(1, resources.size()); assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType()); assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion())); assertNotNull(resources.get(0).getContent()); // Check that operation and input/output have been found. assertEquals(1, service.getOperations().size()); Operation operation = service.getOperations().get(0); assertEquals("GET /owner/{owner}/car", operation.getName()); assertEquals("GET", operation.getMethod()); assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher()); assertEquals("owner ?? page && limit && x-user-id", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_cars", request.getName()); assertEquals("laurent_cars", response.getName()); assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria()); assertEquals("200", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); // Check headers now. assertEquals(2, request.getHeaders().size()); Iterator<Header> headers = request.getHeaders().iterator(); while (headers.hasNext()) { Header header = headers.next(); if ("x-user-id".equals(header.getName())) { assertEquals(1, header.getValues().size()); assertEquals("poiuytrezamlkjhgfdsq", header.getValues().iterator().next()); } else if ("Accept".equals(header.getName())) { assertEquals(1, header.getValues().size()); assertEquals("application/json", header.getValues().iterator().next()); } else { fail("Unexpected header name in request"); } } assertEquals(1, response.getHeaders().size()); Header header = response.getHeaders().iterator().next(); assertEquals("x-result-count", header.getName()); assertEquals(1, header.getValues().size()); assertEquals("2", header.getValues().iterator().next()); } } @Test public void testOpenAPIJsonPointer() { try { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); byte[] bytes = Files.readAllBytes(Paths.get("target/test-classes/io/github/microcks/util/openapi/cars-openapi.yaml")); JsonNode openapiSpec = mapper.readTree(bytes); String verb = "get"; String path = "/owner/{owner}/car"; String pointer = "/paths/" + path.replace("/", "~1") + "/" + verb + "/responses/200/content/" + "application/json".replace("/", "~1"); JsonNode responseNode = openapiSpec.at(pointer); assertNotNull(responseNode); assertFalse(responseNode.isMissingNode()); } catch (Exception e) { fail("Exception should not be thrown"); } } @Test public void testCompleteOpenAPIImportYAML() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi-complete.yaml"); } catch (IOException ioe) { fail("Exception should not be thrown"); } // Check that basic service properties are there. List<Service> services = null; try { services = importer.getServiceDefinitions(); } catch (MockRepositoryImportException e) { fail("Exception should not be thrown"); } assertEquals(1, services.size()); Service service = services.get(0); assertEquals("OpenAPI Car API", service.getName()); Assert.assertEquals(ServiceType.REST, service.getType()); assertEquals("1.1.0", service.getVersion()); // Check that resources have been parsed, correctly renamed, etc... List<Resource> resources = importer.getResourceDefinitions(service); assertEquals(1, resources.size()); assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType()); assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion())); assertNotNull(resources.get(0).getContent()); // Check that operations and input/output have been found. assertEquals(4, service.getOperations().size()); for (Operation operation : service.getOperations()) { if ("GET /owner/{owner}/car".equals(operation.getName())) { assertEquals("GET", operation.getMethod()); assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher()); assertEquals("owner ?? page && limit", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_cars", request.getName()); assertEquals("laurent_cars", response.getName()); assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria()); assertEquals("200", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("POST /owner/{owner}/car".equals(operation.getName())) { assertEquals("POST", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_307", request.getName()); assertEquals("laurent_307", response.getName()); assertEquals("/owner=laurent", response.getDispatchCriteria()); assertEquals("201", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("GET /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { assertEquals("GET", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner && car", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car/307/passenger", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_307_passengers", request.getName()); assertEquals("laurent_307_passengers", response.getName()); assertEquals("/car=307/owner=laurent", response.getDispatchCriteria()); assertEquals("200", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { assertEquals("POST", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner && car", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(0, messages.size()); } else { fail("Unknown operation name: " + operation.getName()); } } } private void importAndAssertOnSimpleOpenAPI(OpenAPIImporter importer) { // Check that basic service properties are there. List<Service> services = null; try { services = importer.getServiceDefinitions(); } catch (MockRepositoryImportException e) { fail("Exception should not be thrown"); } assertEquals(1, services.size()); Service service = services.get(0); assertEquals("OpenAPI Car API", service.getName()); Assert.assertEquals(ServiceType.REST, service.getType()); assertEquals("1.0.0", service.getVersion()); // Check that resources have been parsed, correctly renamed, etc... List<Resource> resources = importer.getResourceDefinitions(service); assertEquals(1, resources.size()); assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType()); assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion())); assertNotNull(resources.get(0).getContent()); // Check that operations and input/output have been found. assertEquals(3, service.getOperations().size()); for (Operation operation : service.getOperations()) { if ("GET /owner/{owner}/car".equals(operation.getName())) { assertEquals("GET", operation.getMethod()); assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher()); assertEquals("owner ?? page && limit", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_cars", request.getName()); assertEquals("laurent_cars", response.getName()); assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria()); assertEquals("200", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("POST /owner/{owner}/car".equals(operation.getName())) { assertEquals("POST", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_307", request.getName()); assertEquals("laurent_307", response.getName()); assertEquals("/owner=laurent", response.getDispatchCriteria()); assertEquals("201", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { assertEquals("POST", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner && car", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(0, messages.size()); } else { fail("Unknown operation name: " + operation.getName()); } } } }
src/test/java/io/github/microcks/util/openapi/OpenAPIImporterTest.java
/* * Licensed to Laurent Broudoux (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author 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 io.github.microcks.util.openapi; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.github.microcks.domain.*; import io.github.microcks.util.DispatchStyles; import io.github.microcks.util.MockRepositoryImportException; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * This is a test case for class OpenAPIImporter. * @author laurent */ public class OpenAPIImporterTest { @Test public void testSimpleOpenAPIImportYAML() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi.yaml"); } catch (IOException ioe) { fail("Exception should not be thrown"); } importAndAssertOnSimpleOpenAPI(importer); } @Test public void testSimpleOpenAPIImportJSON() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi.json"); } catch (IOException ioe) { fail("Exception should not be thrown"); } importAndAssertOnSimpleOpenAPI(importer); } @Test public void testOpenAPIImportYAMLWithHeaders() { OpenAPIImporter importer = null; try { importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi-headers.yaml"); } catch (IOException ioe) { fail("Exception should not be thrown"); } // Check that basic service properties are there. List<Service> services = null; try { services = importer.getServiceDefinitions(); } catch (MockRepositoryImportException e) { fail("Exception should not be thrown"); } assertEquals(1, services.size()); Service service = services.get(0); assertEquals("OpenAPI Car API", service.getName()); Assert.assertEquals(ServiceType.REST, service.getType()); assertEquals("1.0.0", service.getVersion()); // Check that resources have been parsed, correctly renamed, etc... List<Resource> resources = importer.getResourceDefinitions(service); assertEquals(1, resources.size()); assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType()); assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion())); assertNotNull(resources.get(0).getContent()); // Check that operation and input/output have been found. assertEquals(1, service.getOperations().size()); Operation operation = service.getOperations().get(0); assertEquals("GET /owner/{owner}/car", operation.getName()); assertEquals("GET", operation.getMethod()); assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher()); assertEquals("owner ?? page && limit && x-user-id", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_cars", request.getName()); assertEquals("laurent_cars", response.getName()); assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria()); assertEquals("200", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); // Check headers now. assertEquals(2, request.getHeaders().size()); Iterator<Header> headers = request.getHeaders().iterator(); while (headers.hasNext()) { Header header = headers.next(); if ("x-user-id".equals(header.getName())) { assertEquals(1, header.getValues().size()); assertEquals("poiuytrezamlkjhgfdsq", header.getValues().iterator().next()); } else if ("Accept".equals(header.getName())) { assertEquals(1, header.getValues().size()); assertEquals("application/json", header.getValues().iterator().next()); } else { fail("Unexpected header name in request"); } } assertEquals(1, response.getHeaders().size()); Header header = response.getHeaders().iterator().next(); assertEquals("x-result-count", header.getName()); assertEquals(1, header.getValues().size()); assertEquals("2", header.getValues().iterator().next()); } } @Test public void testOpenAPIJsonPointer() { try { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); byte[] bytes = Files.readAllBytes(Paths.get("target/test-classes/io/github/microcks/util/openapi/cars-openapi.yaml")); JsonNode openapiSpec = mapper.readTree(bytes); String verb = "get"; String path = "/owner/{owner}/car"; String pointer = "/paths/" + path.replace("/", "~1") + "/" + verb + "/responses/200/content/" + "application/json".replace("/", "~1"); JsonNode responseNode = openapiSpec.at(pointer); assertNotNull(responseNode); assertFalse(responseNode.isMissingNode()); } catch (Exception e) { fail("Exception should not be thrown"); } } private void importAndAssertOnSimpleOpenAPI(OpenAPIImporter importer) { // Check that basic service properties are there. List<Service> services = null; try { services = importer.getServiceDefinitions(); } catch (MockRepositoryImportException e) { fail("Exception should not be thrown"); } assertEquals(1, services.size()); Service service = services.get(0); assertEquals("OpenAPI Car API", service.getName()); Assert.assertEquals(ServiceType.REST, service.getType()); assertEquals("1.0.0", service.getVersion()); // Check that resources have been parsed, correctly renamed, etc... List<Resource> resources = importer.getResourceDefinitions(service); assertEquals(1, resources.size()); assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType()); assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion())); assertNotNull(resources.get(0).getContent()); // Check that operations and input/output have been found. assertEquals(3, service.getOperations().size()); for (Operation operation : service.getOperations()) { if ("GET /owner/{owner}/car".equals(operation.getName())) { assertEquals("GET", operation.getMethod()); assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher()); assertEquals("owner ?? page && limit", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_cars", request.getName()); assertEquals("laurent_cars", response.getName()); assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria()); assertEquals("200", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("POST /owner/{owner}/car".equals(operation.getName())) { assertEquals("POST", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(1, messages.size()); assertEquals(1, operation.getResourcePaths().size()); assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); for (Map.Entry<Request, Response> entry : messages.entrySet()) { Request request = entry.getKey(); Response response = entry.getValue(); assertNotNull(request); assertNotNull(response); assertEquals("laurent_307", request.getName()); assertEquals("laurent_307", response.getName()); assertEquals("/owner=laurent", response.getDispatchCriteria()); assertEquals("201", response.getStatus()); assertEquals("application/json", response.getMediaType()); assertNotNull(response.getContent()); } } else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { assertEquals("POST", operation.getMethod()); assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); assertEquals("owner && car", operation.getDispatcherRules()); // Check that messages have been correctly found. Map<Request, Response> messages = null; try { messages = importer.getMessageDefinitions(service, operation); } catch (Exception e) { fail("No exception should be thrown when importing message definitions."); } assertEquals(0, messages.size()); } else { fail("Unknown operation name: " + operation.getName()); } } } }
Adding more tests on OpenAPI spec
src/test/java/io/github/microcks/util/openapi/OpenAPIImporterTest.java
Adding more tests on OpenAPI spec
<ide><path>rc/test/java/io/github/microcks/util/openapi/OpenAPIImporterTest.java <ide> } <ide> } <ide> <del> <del> private void importAndAssertOnSimpleOpenAPI(OpenAPIImporter importer) { <add> @Test <add> public void testCompleteOpenAPIImportYAML() { <add> OpenAPIImporter importer = null; <add> try { <add> importer = new OpenAPIImporter("target/test-classes/io/github/microcks/util/openapi/cars-openapi-complete.yaml"); <add> } catch (IOException ioe) { <add> fail("Exception should not be thrown"); <add> } <add> <ide> // Check that basic service properties are there. <ide> List<Service> services = null; <ide> try { <ide> Service service = services.get(0); <ide> assertEquals("OpenAPI Car API", service.getName()); <ide> Assert.assertEquals(ServiceType.REST, service.getType()); <del> assertEquals("1.0.0", service.getVersion()); <add> assertEquals("1.1.0", service.getVersion()); <ide> <ide> // Check that resources have been parsed, correctly renamed, etc... <ide> List<Resource> resources = importer.getResourceDefinitions(service); <ide> assertNotNull(resources.get(0).getContent()); <ide> <ide> // Check that operations and input/output have been found. <del> assertEquals(3, service.getOperations().size()); <add> assertEquals(4, service.getOperations().size()); <ide> for (Operation operation : service.getOperations()) { <ide> <ide> if ("GET /owner/{owner}/car".equals(operation.getName())) { <ide> assertNotNull(response.getContent()); <ide> } <ide> } <add> else if ("GET /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { <add> assertEquals("GET", operation.getMethod()); <add> assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); <add> assertEquals("owner && car", operation.getDispatcherRules()); <add> <add> // Check that messages have been correctly found. <add> Map<Request, Response> messages = null; <add> try { <add> messages = importer.getMessageDefinitions(service, operation); <add> } catch (Exception e) { <add> fail("No exception should be thrown when importing message definitions."); <add> } <add> assertEquals(1, messages.size()); <add> assertEquals(1, operation.getResourcePaths().size()); <add> assertEquals("/owner/laurent/car/307/passenger", operation.getResourcePaths().get(0)); <add> <add> for (Map.Entry<Request, Response> entry : messages.entrySet()) { <add> Request request = entry.getKey(); <add> Response response = entry.getValue(); <add> assertNotNull(request); <add> assertNotNull(response); <add> assertEquals("laurent_307_passengers", request.getName()); <add> assertEquals("laurent_307_passengers", response.getName()); <add> assertEquals("/car=307/owner=laurent", response.getDispatchCriteria()); <add> assertEquals("200", response.getStatus()); <add> assertEquals("application/json", response.getMediaType()); <add> assertNotNull(response.getContent()); <add> } <add> } <ide> else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { <ide> assertEquals("POST", operation.getMethod()); <ide> assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); <ide> } <ide> } <ide> } <add> <add> <add> private void importAndAssertOnSimpleOpenAPI(OpenAPIImporter importer) { <add> // Check that basic service properties are there. <add> List<Service> services = null; <add> try { <add> services = importer.getServiceDefinitions(); <add> } catch (MockRepositoryImportException e) { <add> fail("Exception should not be thrown"); <add> } <add> assertEquals(1, services.size()); <add> Service service = services.get(0); <add> assertEquals("OpenAPI Car API", service.getName()); <add> Assert.assertEquals(ServiceType.REST, service.getType()); <add> assertEquals("1.0.0", service.getVersion()); <add> <add> // Check that resources have been parsed, correctly renamed, etc... <add> List<Resource> resources = importer.getResourceDefinitions(service); <add> assertEquals(1, resources.size()); <add> assertEquals(ResourceType.OPEN_API_SPEC, resources.get(0).getType()); <add> assertTrue(resources.get(0).getName().startsWith(service.getName() + "-" + service.getVersion())); <add> assertNotNull(resources.get(0).getContent()); <add> <add> // Check that operations and input/output have been found. <add> assertEquals(3, service.getOperations().size()); <add> for (Operation operation : service.getOperations()) { <add> <add> if ("GET /owner/{owner}/car".equals(operation.getName())) { <add> assertEquals("GET", operation.getMethod()); <add> assertEquals(DispatchStyles.URI_ELEMENTS, operation.getDispatcher()); <add> assertEquals("owner ?? page && limit", operation.getDispatcherRules()); <add> <add> // Check that messages have been correctly found. <add> Map<Request, Response> messages = null; <add> try { <add> messages = importer.getMessageDefinitions(service, operation); <add> } catch (Exception e) { <add> fail("No exception should be thrown when importing message definitions."); <add> } <add> assertEquals(1, messages.size()); <add> assertEquals(1, operation.getResourcePaths().size()); <add> assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); <add> <add> for (Map.Entry<Request, Response> entry : messages.entrySet()) { <add> Request request = entry.getKey(); <add> Response response = entry.getValue(); <add> assertNotNull(request); <add> assertNotNull(response); <add> assertEquals("laurent_cars", request.getName()); <add> assertEquals("laurent_cars", response.getName()); <add> assertEquals("/owner=laurent?limit=20?page=0", response.getDispatchCriteria()); <add> assertEquals("200", response.getStatus()); <add> assertEquals("application/json", response.getMediaType()); <add> assertNotNull(response.getContent()); <add> } <add> } <add> else if ("POST /owner/{owner}/car".equals(operation.getName())) { <add> assertEquals("POST", operation.getMethod()); <add> assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); <add> assertEquals("owner", operation.getDispatcherRules()); <add> <add> // Check that messages have been correctly found. <add> Map<Request, Response> messages = null; <add> try { <add> messages = importer.getMessageDefinitions(service, operation); <add> } catch (Exception e) { <add> fail("No exception should be thrown when importing message definitions."); <add> } <add> assertEquals(1, messages.size()); <add> assertEquals(1, operation.getResourcePaths().size()); <add> assertEquals("/owner/laurent/car", operation.getResourcePaths().get(0)); <add> <add> for (Map.Entry<Request, Response> entry : messages.entrySet()) { <add> Request request = entry.getKey(); <add> Response response = entry.getValue(); <add> assertNotNull(request); <add> assertNotNull(response); <add> assertEquals("laurent_307", request.getName()); <add> assertEquals("laurent_307", response.getName()); <add> assertEquals("/owner=laurent", response.getDispatchCriteria()); <add> assertEquals("201", response.getStatus()); <add> assertEquals("application/json", response.getMediaType()); <add> assertNotNull(response.getContent()); <add> } <add> } <add> else if ("POST /owner/{owner}/car/{car}/passenger".equals(operation.getName())) { <add> assertEquals("POST", operation.getMethod()); <add> assertEquals(DispatchStyles.URI_PARTS, operation.getDispatcher()); <add> assertEquals("owner && car", operation.getDispatcherRules()); <add> <add> // Check that messages have been correctly found. <add> Map<Request, Response> messages = null; <add> try { <add> messages = importer.getMessageDefinitions(service, operation); <add> } catch (Exception e) { <add> fail("No exception should be thrown when importing message definitions."); <add> } <add> assertEquals(0, messages.size()); <add> } else { <add> fail("Unknown operation name: " + operation.getName()); <add> } <add> } <add> } <ide> }
JavaScript
bsd-3-clause
55c11a1abc96bd20fdd30bc950e39107c4dcd03e
0
flynx/pWiki,flynx/pWiki
/********************************************************************** * * * XXX ASAP start writing docs in pwiki * - transparent sync/backup * - fs store/export in browser or a simple way to export/import... * ...can't seem to get it to work without asking for permission * on every startup (one more thing left to try, keeping the * handler live in a service worker, but the hopes are low)... * - pouchdb-couchdb sync - * - pouchdb-pouchdb sync (p2p via webrtc) - XXX * - images - XXX * - WYSIWYG markdown editor/viewer (ASAP) - XXX * - need a UI a-la milkdown * ...milkdown is good but 500mb dev-env and (apparently) * no AMD support are problems -- need more testing... * - minimal/functional editor - DONE * ...<pre> sometimes ties formatting while <textarea>/<input type=text> * handle resizing in a really odd way... * - tags - DONE * - search - DONE * - GUI - * general UI/UX * drag-n-drop * - CLI - * - server / replication target * - management * * * * XXX things that will help: * - async render (infinite scroll + search + large pages) * unresolved -> dom placeholder * iterator prepends to placeholder * when resolved/done remove placeholder * - * * * XXX load new page at .scrollTop = 0 if no anchors are given... * ...or remember scroll position per page... * XXX macros: else/default macro args essentially mean the same thing, should we * unify them to use the same name??? * XXX parser: error handling: revise page quoting... * ...need a standard mechanism to quote urls, url-args and paths... * XXX BUG? can't use < and > (both?) in page title... * XXX parser: error handling: add line number + context... (???) * XXX BUG: parser: * This will break: * await pwiki.parse('<macro src=../tags join=", ">@source(.)</macro>') * This will not: * await pwiki.parse('<macro src="../tags" join=", ">@source(.)</macro>') * XXX ASAP test: can we store the file handler with permissions in a ServiceWorker?? * XXX macros: Q: do we need macros for printing errors and the like??? * XXX macros: Q: do we need a macro to define user macros (live)??? * ...not yet sure... * Q: should the defined macro be global or local to page? * the obvious is to make it local (.defmacro(..) is global), the * next obvious thought is to add an ability to define global macros * via either a special page (better) or a special macro (worse) * ...it would be nice to make the "globals" pages parse-on-write * ...it is also obvious that "globals" pages can be placed in * different parts of the tree and thus define different sub * namespaces, this essentially leads to duplicating part of the * current functionality... * A: Global macros REJECTED, based on KISS * ...see: <page>.defmacro(..) * XXX the parser should handle all action return values, including: * - lists -- XXX * - strings -- DONE * - numbers -- DONE * - misc: * dates -- ??? * note that an action returning a list is not the same as a list * stoted in <data>.text -- since we can't identify what an action * returns without calling it, and we only call actions on * .raw/.text/.parse(..), we can't iterate over such results. * Q: can we make a list reder as a list of pages?? * ...likely no... * ...would depend on where we iterate pages and on whether * we can/should reach that spot from within the parser... * XXX ASAP revise/update sort... * XXX ASAP: MetaStore: need to correctly integrate the following store * methods: * .get(..) -- DONE * .metadata(..) -- * .delete(..) * XXX deleting something in .next will break stuff... * ... * XXX FEATURE images... * XXX BUG?: count does not appear to affect /Test/list/generator and /Test/list/static... * ...do we need to support this??? * XXX index: need to disable index persistence on memory stores... * XXX index: would be nice to somehow persistently auto-generate index id's... * ...maybe: "<prefix>:<path>" or something similar... * ...would be nice to have store ids... * XXX index: journal: might be a fun idea to try a simple sync file store * - a json format simply appending elements in the format: * ',\n\t[ ... ]' * - appending a '\n}' on exit * XXX <store>.journal: needed to break the update recursion -- i.e. decouple * index .update(..) handlers from stored page updates by first * updating the journal and on a timer updating the .cache/<index> page... * XXX BUG: indexedDB: .deleteDatabase(..) does not actually delete the * database from the list until reload. * this breaks trying to open a database with the same name again... * XXX FEATURE: would be nice to have a buffered store (mixin)... * - state stored in memory * - get state from memory (sync) * - background updates (async) * - update strategy * - asap * - timer -- save grouped changes * (changed paths + removed paths) * - idle * - ... * - state query -- pending/saved/... * XXX Q: can we get state and update in one go??? * ...usefull where we need to get state to update... * XXX macro: macro:count / macro:index vars can be overridden by count/index * attributes.... * ...this can be usefull but this needs testing... * XXX should @macro(..) handle offset in the same manner as count??? * XXX FEATURE store: mirror (slave) -- a way to hold data in one store * and to mirror everything (async) to a separate store... * example: * PouchDB (main) -- FileSore (export) * XXX Q: do we need a way to index/access a list item via path??? * XXX STYLE: should style loading be done via the event mechanics * (see: pwiki2.html) or via the base templates (see: pwiki/page.js:_view * template)??? * XXX TAGS * - add tags to page -- macro/filter * - <page>.text -> <page>.tags (cached on .update(..)) * - ??? * - manual/API - DONE * - editor - * - a way to list tags -- folder like? - DONE * - tag cache <store>.tags - DONE * - tag-path filtering... - DONE * XXX TAGS add a more advanced query -- e.g. "/**:tagged=y,z:untagged=x" ??? * XXX INDEX DOC can index validation be async??? * ...likely no * XXX INDEX add option to set default action (get/lazy/cached) * XXX BUG: CachedStore seems to be broken (see: pwiki/store/base.js:837) * XXX might be a good idea to create memory store (sandbox) from the * page API -- action?? * XXX Chrome started spamming CORS error: * Access to manifest at 'file:///L:/work/pWiki/manifest.json' * from origin 'null' ... * not sure why... * (switched off in console filter for now) * XXX might be a good idea to wrap the wysiwig editor into a separate template * and use it in the main edit template to make it user-selectable... * XXX generalize html/dom api... * ...see refresh() in pwiki2.html * XXX test pouchdb latency at scale in browser... * XXX macros: .depends: need fast path pattern matching... * XXX macros / CACHE: convert a /path/* dependency to /path/** if a script * is recursive... * XXX might also be a good idea to investigate a .tree directory index * as a supplement to .paths() * XXX CACHE need to explicitly prevent caching of some actions/pages... * XXX async/live render... * might be fun to push the async parts of the render to the dom... * ...i.e. return a partially rendered DOM with handlers to fill * in the blanks wen they are ready... * something like: * place placeholder element * -> on visible / close to visible * -> trigger load (set id) * -> on load * -> fill content (on id) * example: * @include(./path ..) * -> <span pwiki="@include(/full/path ..)"/> * XXX prevent paths from using reserved chars like: ":", "#", ... * XXX OPTIMIZE CACHE catch page creation -- match pattern path... * 1) explicit subpath matching -- same as .match(..) * 2) identify recursive patterns -- same as ** * XXX do we need something like /System/Actions/.. for fast actions called * in the same way as direct page actions??? * ...experiment?? * XXX fs: handle odd file names... * - we need '*' and '**' * - would be nice to be able to name files without * any resyrictions other than the internally reserved * cars... * (currently: '#', and ':') * XXX ENERGETIC: Q: do we need to make this a path syntax thing??? * ...i.e. * /some/path/action/! (current) * vs. * /some/path/!action * ..."!" is removed before the <store>.__<name>__(..) calls... * XXX OPTIMIZE load pages in packs... * might be a good idea to move stuff down the stack to Store: * .each() -> .store.each(<path>) * ...this will enable us to optimize page loading on a store * level... * ...another approach would be to make .get(..) accept a list of * paths and return an iterator... * XXX OPTIMIZE MATCH limit candidates to actual page name matches -- this will * limit the number of requests to actual number of pages with that * name... * e.g. when searching for xxx/tree the only "tree" available is * System/tree, and if it is overloaded it's now a question of * picking one out of two and not out of tens generated by .paths() * XXX OPTIMIZE CACHE track store (external) changes... * XXX OPTIMIZE CACHE/DEPENDS might be a good idea to add a dependencyUpdated event... * ...and use it for cache invalidation... * XXX OPTIMIZE NORMCACHE .normalize(..) cache normalized strings... * ...seems to have little impact... * XXX OPTIMIZE: the actions that depend on lots of tiny requests (/tree) * can get really slow... * ...it feels like one reason is the async/await ping-pong... * problems: * - too many async requests * micro cache? * pack requests? * - redundant path normalization (RENORMALIZE) * mark the normalized string and return it as-is on * renormalization... * ...initial experiment made things slower... * XXX FEATURE self-doc: * - some thing lile Action(<name>, <doc>, <func>|<str>) * - System/doc -- show <doc> for action... * XXX GENERATOR make pattern path parsing a generator... * ...experiment with a controllable iterator/range thing... * This would require: * 1) the rendering infrastructure to support generation and * partial rendering starting from .expand(..) and up... * input output * .expand(..) DONE DONE * .resolve(..) partial DONE * XXX for-await-of (vs. for-of-await) breaks things * (see: /test_slots, ..?) * .parse(..) DONE NO * XXX with the current implementation of filters * this can't work as a generator... * ...might be a good idea to make filters local only... * XXX slots/macros might also pose a problem... * 2) all the macros that can source pages to produce generators (DONE) * XXX might be a good idea to parse a page into an executable/function * that would render self in a given context... * XXX add support for <join> tag in include/source/quote??? * XXX introspection: * /stores -- DONE * list stores... * /info -- DONE? * list page/store info * /storage -- XXX * list storage usage / limits * /time -- DONE * time page load/render * XXX BUG: FF: conflict between object.run and PouchDB... * ...seems to be a race, also affects chrome sometimes... * XXX add a way to indicate and reset overloaded (bootstrap/.next) pages... * - per page * - global * XXX should render templates (_view and the like) be a special case * or render as any other page??? * ...currently they are rendered in the context of the page and * not in their own context... * ...document this * XXX macros: add @defmacro(<name> ..) to be exactly as @macro(<name> ..) * but defines a @<name>(..) macro... * ...this would be useful for things like: * <pw:delete src="."/> * or: * <pw:info src="."/> * generating delete and info buttons... * ...this is not possible because: * - we statically set the macro name list (regexp) parser.lex(..) * - we need this list to parser.group(..) * XXX EXPERIMENTAL DOC INHERIT_ARGS added a special-case... * as basename will get appended :$ARGS if no args are given... * ...this only applies to paths referring to the current context * page, i.e.: * await pwiki * .get('/page:x:y:z') * // this will get the args... * .parse('@source(./location)') * * await pwiki * .get('/page:x:y:z') * // this will not get the args -- different page... * .parse('@source(./x/location)') * * await pwiki * .get('/page:x:y:z') * // this will get explicitly given empty args... * .parse('@source(./location:)') * * special args that auto-inherit are given in .actions_inherit_args * XXX this is currently implemented on the level of macro parsing, * should this be in a more general way??? * XXX should this be done when isolated??? * ...yes (current) * * * * XXX ROADMAP: * - run in browser * - basics, loading -- DONE * - localStorage / sessionStorage -- DONE * - pouchdb -- DONE * - render page -- DONE * - navigation -- DONE * - hash/anchor -- DONE * - action redirects (see: System/delete) -- ??? (unify api) * - basic editor and interactivity -- DONE * - export * - json -- DONE * - zip (json/tree) -- * - sync (auto) -- XXX * - page actions -- DONE * - migrate/rewrite bootstrap -- * - store topology -- DONE * - config??? * - images XXX * - get -- * - download -- * - upload -- * - tags * - get tags from page -- DONE * - show tagged pages -- DONE * - search * - paths -- ??? * - text -- DONE * - markdown -- DONE * - WikiWord -- DONE * - dom filter mechanics -- DONE * - filters * - markdown (???) -- ??? * this can be done in one of two ways: * - wrapping blocks in elemens * ...requires negative filter calls, either on -wikiword * or a different filter like nowikiwords... * - tags (current) * - raw / code -- DONE? * - nl2br -- * - nowhitespace -- * clear extra whitespace from text elements * - dom filters: * - editor * basic -- DONE * see: /System/edit * MediumEditor (markdown-plugin) -- REJECTED XXX * https://github.com/yabwe/medium-editor * https://github.com/IonicaBizau/medium-editor-markdown * - heavy-ish markdown plugin * ToastUI (markdown) * https://github.com/nhn/tui.editor * - quite heavy * Pen (markdown) * https://github.com/sofish/pen * - no npm module * - not sure if it works on mobile * + small * tiptap (no-markdown, investigate y.js) * - wikiword / path2link -- * ..do we need to be able to control this??? * - templates * - all (tree) -- DONE * - configuration * - defaults -- * - System/config (global) -- * - pwa * - service worker -- ??? * ...handle relative urls (???) * - fs access (external sync) -- ??? * - cli * - basic wiki manipulations (1:1 methods) * - import/export/sync * - introspection/repl * - archive old code -- * - update docs -- * - refactor and cleanup * - module structure -- REVISE * - package * - pwa -- ??? * - electron -- * - android -- ??? * - iOS -- ??? * * * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * Architecture: * * store <-> index * ^ ^ * | | * +---------+ * | * page <--> renderer * ^ * | * | * client * * * * Modules: * pwiki/ * page - base pages and page APIs * parser - pWiki macro parser * path - base path API * store/ - stores * base - memory store and store API and utils * file - file store * localstorage - localStorage / sessionStorage stores * pouchdb - PouchDB store * ... * filter/ - page filters * base - base filters incl. wikiword * markdown - markdown renderer * ... * pwiki2 - main cli / node entry point * browser - browser entry point * pwiki2-test - testing and experimenting (XXX move to test.js) * * * Q: can we make this a single module with +/- some plugins?? * ...this would make things quite a bit simpler but will negate the * use of high level libs like types... * * * XXX DOC: * - macro isolation in relation to slots... * - paths in pWiki behave a bit differently than traditional * file-system paths, this is due to one key distinction: * in pWiki there is no distinction between a file and a * directory * i.e. each path can both contain data as a file and at the same * time support sub-paths etc. * for this reason behaviour of some APIs will differ, all paths * within a page (a-la file) are relative to its children and not * to it's siblings. For example, for page "/a/b/c" a link to "./x" * will resolve to "/a/b/c/x" and this is independent of whether * the base path is given as "/a/b/c/" or "/a/b/c" * * NOTE: implementing things in a traditional manner would * introduce lots of edge-cases and subtle ways to make * mistakes, bugs and inconsistencies. * - types of recursion * (see: pwiki/page.js: Page.macros.include(..) notes) * - slot <content/> order -- * (see: page.js: Page's .macros.slot(..) notes) * - arguments in macros that contain macros must be in quotes, e.g. * @include("./*:@(all)") * otherwise the macro will end on the first ')'... * - :all argument to all pattern paths... * * * XXX weaknesses to review: * - <store>.paths() as an index... * + decouples the search logic from the store backend * - requires the whole list of pages to be in memory * ...need to be independent of the number of pages if at * all possible -- otherwise this will hinder long-term use... * .paths() should be cached to make all path searches away from * async waits as we can test quite a number of paths before we * find a page... * ...another solution is to offload the search to the store backend * but this would require the stores to reimplement most of pwiki/path * - * * * TODO?: * - <page>.then() -- resolve when all pending write operations done ??? * - an async REPL??? * - custom element??? * - might be a good idea to try signature based security: * - sign changes * - sign sync session * - refuse changes with wrong signatures * - public keys available on client and on server * - check signatures localy * - check signatures remotely * - private key available only with author * - keep both the last signed and superceding unsigned version * - on sync ask to overwrite unsigned with signed * - check if we can use the same mechanics as ssh... * - in this view a user in the system is simply a set of keys and * a signature (a page =)) * * XXX RELATIVE relative urls are a bit odd... * Path/to/page opens Moo -> Path/to/Page/Moo * should be (???): * Path/to/page opens Moo -> Path/to/Moo * this boils down to how path.relative(..) works, treating the base * as a directory always (current) vs. only if '/' is at the end, on * one hand the current approach is more uniform with less subtle ways * to make mistakes but on the other hand this may introduce a lot * of complexity to the user writing links, e.g. how should the * following be interpreted? * page: /SomePage * link: SomeOtherPage * -> /SomeOtherPage * -> /SomePage/SomeOtherPage (current) * the current approach does not seem to be intuitive... * can this be fixed uniformly across the whole system??? * XXX document this! * * XXX need to think about search -- page function argument syntax??? * * XXX might need to get all the links (macro-level) from a page... * ...would be useful for caching... * * * **********************************************************************/ ((typeof define)[0]=='u'?function(f){module.exports=f(require)}:define) (function(require){ var module={} // make module AMD/node compatible... /*********************************************************************/ // XXX //var object = require('lib/object') var object = require('ig-object') var types = require('ig-types') var pwpath = module.path = require('./pwiki/path') var page = require('./pwiki/page') var basestore = require('./pwiki/store/base') var pouchdbstore = require('./pwiki/store/pouchdb') //--------------------------------------------------------------------- // Basic setup... // // // Store topology: // XXX // var store = module.store = { // XXX base localstorage... __proto__: pouchdbstore.PouchDBStore, /*/ __proto__: basestore.MetaStore, //*/ next: { __proto__: basestore.MetaStore }, } // XXX these are async... // ...see browser.js for a way to deal with this... // XXX note sure how to organize the system actions -- there can be two // options: // - a root ram store with all the static stuff and nest the rest // - a nested store (as is the case here) // XXX nested system store... module.setup = Promise.all([ //store.next.update('System', store.next.update( pwpath.sanitize(pwpath.SYSTEM_PATH), Object.create(basestore.BaseStore).load(page.System)), store.next.update('.templates', Object.create(basestore.BaseStore).load(page.Templates)), store.update('.config', Object.create(basestore.BaseStore).load(page.Config)), ]) // NOTE: in general the root wiki api is simply a page instance. // XXX not yet sure how to organize the actual client -- UI, hooks, .. etc var pwiki = module.pwiki = //page.Page('/', '/', store) page.CachedPage('/', '/', store) //--------------------------------------------------------------------- // comandline... if(typeof(__filename) != 'undefined' && __filename == (require.main || {}).filename){ } /********************************************************************** * vim:set ts=4 sw=4 nowrap : */ return module })
pwiki2.js
/********************************************************************** * * * XXX ASAP start writing docs in pwiki * - transparent sync/backup * - fs store/export in browser or a simple way to export/import... * ...can't seem to get it to work without asking for permission * on every startup (one more thing left to try, keeping the * handler live in a service worker, but the hopes are low)... * - pouchdb-couchdb sync - * - pouchdb-pouchdb sync (p2p via webrtc) - XXX * - images - XXX * - WYSIWYG markdown editor/viewer (ASAP) - XXX * - need a UI a-la milkdown * ...milkdown is good but 500mb dev-env and (apparently) * no AMD support are problems -- need more testing... * - minimal/functional editor - DONE * ...<pre> sometimes ties formatting while <textarea>/<input type=text> * handle resizing in a really odd way... * - tags - DONE * - search - DONE * - GUI - * general UI/UX * drag-n-drop * - CLI - * - server / replication target * - management * * * * XXX things that will help: * - async render (infinite scroll + search + large pages) * unresolved -> dom placeholder * iterator prepends to placeholder * when resolved/done remove placeholder * - * * * XXX load new page at .scrollTop = 0 if no anchors are given... * ... or remember scroll position per page... * XXX parser: error handling: revise page quoting... * ...need a standard mechanism to quote urls, url-args and paths... * XXX BUG? can't use < and > (both?) in page title... * XXX parser: error handling: add line number + context... (???) * XXX BUG: parser: * This will break: * await pwiki.parse('<macro src=../tags join=", ">@source(.)</macro>') * This will not: * await pwiki.parse('<macro src="../tags" join=", ">@source(.)</macro>') * XXX ASAP test: can we store the file handler with permissions in a ServiceWorker?? * XXX macros: Q: do we need macros for printing errors and the like??? * XXX macros: Q: do we need a macro to define user macros (live)??? * ...not yet sure... * Q: should the defined macro be global or local to page? * the obvious is to make it local (.defmacro(..) is global), the * next obvious thought is to add an ability to define global macros * via either a special page (better) or a special macro (worse) * ...it would be nice to make the "globals" pages parse-on-write * ...it is also obvious that "globals" pages can be placed in * different parts of the tree and thus define different sub * namespaces, this essentially leads to duplicating part of the * current functionality... * A: Global macros REJECTED, based on KISS * ...see: <page>.defmacro(..) * XXX the parser should handle all action return values, including: * - lists -- XXX * - strings -- DONE * - numbers -- DONE * - misc: * dates -- ??? * note that an action returning a list is not the same as a list * stoted in <data>.text -- since we can't identify what an action * returns without calling it, and we only call actions on * .raw/.text/.parse(..), we can't iterate over such results. * Q: can we make a list reder as a list of pages?? * ...likely no... * ...would depend on where we iterate pages and on whether * we can/should reach that spot from within the parser... * XXX ASAP revise/update sort... * XXX ASAP: MetaStore: need to correctly integrate the following store * methods: * .get(..) -- DONE * .metadata(..) -- * .delete(..) * XXX deleting something in .next will break stuff... * ... * XXX FEATURE images... * XXX BUG?: count does not appear to affect /Test/list/generator and /Test/list/static... * ...do we need to support this??? * XXX index: need to disable index persistence on memory stores... * XXX index: would be nice to somehow persistently auto-generate index id's... * ...maybe: "<prefix>:<path>" or something similar... * ...would be nice to have store ids... * XXX index: journal: might be a fun idea to try a simple sync file store * - a json format simply appending elements in the format: * ',\n\t[ ... ]' * - appending a '\n}' on exit * XXX <store>.journal: needed to break the update recursion -- i.e. decouple * index .update(..) handlers from stored page updates by first * updating the journal and on a timer updating the .cache/<index> page... * XXX BUG: indexedDB: .deleteDatabase(..) does not actually delete the * database from the list until reload. * this breaks trying to open a database with the same name again... * XXX FEATURE: would be nice to have a buffered store (mixin)... * - state stored in memory * - get state from memory (sync) * - background updates (async) * - update strategy * - asap * - timer -- save grouped changes * (changed paths + removed paths) * - idle * - ... * - state query -- pending/saved/... * XXX Q: can we get state and update in one go??? * ...usefull where we need to get state to update... * XXX macro: macro:count / macro:index vars can be overridden by count/index * attributes.... * ...this can be usefull but this needs testing... * XXX should @macro(..) handle offset in the same manner as count??? * XXX FEATURE store: mirror (slave) -- a way to hold data in one store * and to mirror everything (async) to a separate store... * example: * PouchDB (main) -- FileSore (export) * XXX Q: do we need a way to index/access a list item via path??? * XXX STYLE: should style loading be done via the event mechanics * (see: pwiki2.html) or via the base templates (see: pwiki/page.js:_view * template)??? * XXX TAGS * - add tags to page -- macro/filter * - <page>.text -> <page>.tags (cached on .update(..)) * - ??? * - manual/API - DONE * - editor - * - a way to list tags -- folder like? - DONE * - tag cache <store>.tags - DONE * - tag-path filtering... - DONE * XXX TAGS add a more advanced query -- e.g. "/**:tagged=y,z:untagged=x" ??? * XXX INDEX DOC can index validation be async??? * ...likely no * XXX INDEX add option to set default action (get/lazy/cached) * XXX BUG: CachedStore seems to be broken (see: pwiki/store/base.js:837) * XXX might be a good idea to create memory store (sandbox) from the * page API -- action?? * XXX Chrome started spamming CORS error: * Access to manifest at 'file:///L:/work/pWiki/manifest.json' * from origin 'null' ... * not sure why... * (switched off in console filter for now) * XXX might be a good idea to wrap the wysiwig editor into a separate template * and use it in the main edit template to make it user-selectable... * XXX generalize html/dom api... * ...see refresh() in pwiki2.html * XXX test pouchdb latency at scale in browser... * XXX macros: .depends: need fast path pattern matching... * XXX macros / CACHE: convert a /path/* dependency to /path/** if a script * is recursive... * XXX might also be a good idea to investigate a .tree directory index * as a supplement to .paths() * XXX CACHE need to explicitly prevent caching of some actions/pages... * XXX async/live render... * might be fun to push the async parts of the render to the dom... * ...i.e. return a partially rendered DOM with handlers to fill * in the blanks wen they are ready... * something like: * place placeholder element * -> on visible / close to visible * -> trigger load (set id) * -> on load * -> fill content (on id) * example: * @include(./path ..) * -> <span pwiki="@include(/full/path ..)"/> * XXX prevent paths from using reserved chars like: ":", "#", ... * XXX OPTIMIZE CACHE catch page creation -- match pattern path... * 1) explicit subpath matching -- same as .match(..) * 2) identify recursive patterns -- same as ** * XXX do we need something like /System/Actions/.. for fast actions called * in the same way as direct page actions??? * ...experiment?? * XXX fs: handle odd file names... * - we need '*' and '**' * - would be nice to be able to name files without * any resyrictions other than the internally reserved * cars... * (currently: '#', and ':') * XXX ENERGETIC: Q: do we need to make this a path syntax thing??? * ...i.e. * /some/path/action/! (current) * vs. * /some/path/!action * ..."!" is removed before the <store>.__<name>__(..) calls... * XXX OPTIMIZE load pages in packs... * might be a good idea to move stuff down the stack to Store: * .each() -> .store.each(<path>) * ...this will enable us to optimize page loading on a store * level... * ...another approach would be to make .get(..) accept a list of * paths and return an iterator... * XXX OPTIMIZE MATCH limit candidates to actual page name matches -- this will * limit the number of requests to actual number of pages with that * name... * e.g. when searching for xxx/tree the only "tree" available is * System/tree, and if it is overloaded it's now a question of * picking one out of two and not out of tens generated by .paths() * XXX OPTIMIZE CACHE track store (external) changes... * XXX OPTIMIZE CACHE/DEPENDS might be a good idea to add a dependencyUpdated event... * ...and use it for cache invalidation... * XXX OPTIMIZE NORMCACHE .normalize(..) cache normalized strings... * ...seems to have little impact... * XXX OPTIMIZE: the actions that depend on lots of tiny requests (/tree) * can get really slow... * ...it feels like one reason is the async/await ping-pong... * problems: * - too many async requests * micro cache? * pack requests? * - redundant path normalization (RENORMALIZE) * mark the normalized string and return it as-is on * renormalization... * ...initial experiment made things slower... * XXX FEATURE self-doc: * - some thing lile Action(<name>, <doc>, <func>|<str>) * - System/doc -- show <doc> for action... * XXX GENERATOR make pattern path parsing a generator... * ...experiment with a controllable iterator/range thing... * This would require: * 1) the rendering infrastructure to support generation and * partial rendering starting from .expand(..) and up... * input output * .expand(..) DONE DONE * .resolve(..) partial DONE * XXX for-await-of (vs. for-of-await) breaks things * (see: /test_slots, ..?) * .parse(..) DONE NO * XXX with the current implementation of filters * this can't work as a generator... * ...might be a good idea to make filters local only... * XXX slots/macros might also pose a problem... * 2) all the macros that can source pages to produce generators (DONE) * XXX might be a good idea to parse a page into an executable/function * that would render self in a given context... * XXX add support for <join> tag in include/source/quote??? * XXX introspection: * /stores -- DONE * list stores... * /info -- DONE? * list page/store info * /storage -- XXX * list storage usage / limits * /time -- DONE * time page load/render * XXX BUG: FF: conflict between object.run and PouchDB... * ...seems to be a race, also affects chrome sometimes... * XXX add a way to indicate and reset overloaded (bootstrap/.next) pages... * - per page * - global * XXX should render templates (_view and the like) be a special case * or render as any other page??? * ...currently they are rendered in the context of the page and * not in their own context... * ...document this * XXX macros: add @defmacro(<name> ..) to be exactly as @macro(<name> ..) * but defines a @<name>(..) macro... * ...this would be useful for things like: * <pw:delete src="."/> * or: * <pw:info src="."/> * generating delete and info buttons... * ...this is not possible because: * - we statically set the macro name list (regexp) parser.lex(..) * - we need this list to parser.group(..) * XXX EXPERIMENTAL DOC INHERIT_ARGS added a special-case... * as basename will get appended :$ARGS if no args are given... * ...this only applies to paths referring to the current context * page, i.e.: * await pwiki * .get('/page:x:y:z') * // this will get the args... * .parse('@source(./location)') * * await pwiki * .get('/page:x:y:z') * // this will not get the args -- different page... * .parse('@source(./x/location)') * * await pwiki * .get('/page:x:y:z') * // this will get explicitly given empty args... * .parse('@source(./location:)') * * special args that auto-inherit are given in .actions_inherit_args * XXX this is currently implemented on the level of macro parsing, * should this be in a more general way??? * XXX should this be done when isolated??? * ...yes (current) * * * * XXX ROADMAP: * - run in browser * - basics, loading -- DONE * - localStorage / sessionStorage -- DONE * - pouchdb -- DONE * - render page -- DONE * - navigation -- DONE * - hash/anchor -- DONE * - action redirects (see: System/delete) -- ??? (unify api) * - basic editor and interactivity -- DONE * - export * - json -- DONE * - zip (json/tree) -- * - sync (auto) -- XXX * - page actions -- DONE * - migrate/rewrite bootstrap -- * - store topology -- DONE * - config??? * - images XXX * - get -- * - download -- * - upload -- * - tags * - get tags from page -- DONE * - show tagged pages -- DONE * - search * - paths -- ??? * - text -- DONE * - markdown -- DONE * - WikiWord -- DONE * - dom filter mechanics -- DONE * - filters * - markdown (???) -- ??? * this can be done in one of two ways: * - wrapping blocks in elemens * ...requires negative filter calls, either on -wikiword * or a different filter like nowikiwords... * - tags (current) * - raw / code -- DONE? * - nl2br -- * - nowhitespace -- * clear extra whitespace from text elements * - dom filters: * - editor * basic -- DONE * see: /System/edit * MediumEditor (markdown-plugin) -- REJECTED XXX * https://github.com/yabwe/medium-editor * https://github.com/IonicaBizau/medium-editor-markdown * - heavy-ish markdown plugin * ToastUI (markdown) * https://github.com/nhn/tui.editor * - quite heavy * Pen (markdown) * https://github.com/sofish/pen * - no npm module * - not sure if it works on mobile * + small * tiptap (no-markdown, investigate y.js) * - wikiword / path2link -- * ..do we need to be able to control this??? * - templates * - all (tree) -- DONE * - configuration * - defaults -- * - System/config (global) -- * - pwa * - service worker -- ??? * ...handle relative urls (???) * - fs access (external sync) -- ??? * - cli * - basic wiki manipulations (1:1 methods) * - import/export/sync * - introspection/repl * - archive old code -- * - update docs -- * - refactor and cleanup * - module structure -- REVISE * - package * - pwa -- ??? * - electron -- * - android -- ??? * - iOS -- ??? * * * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * Architecture: * * store <-> index * ^ ^ * | | * +---------+ * | * page <--> renderer * ^ * | * | * client * * * * Modules: * pwiki/ * page - base pages and page APIs * parser - pWiki macro parser * path - base path API * store/ - stores * base - memory store and store API and utils * file - file store * localstorage - localStorage / sessionStorage stores * pouchdb - PouchDB store * ... * filter/ - page filters * base - base filters incl. wikiword * markdown - markdown renderer * ... * pwiki2 - main cli / node entry point * browser - browser entry point * pwiki2-test - testing and experimenting (XXX move to test.js) * * * Q: can we make this a single module with +/- some plugins?? * ...this would make things quite a bit simpler but will negate the * use of high level libs like types... * * * XXX DOC: * - macro isolation in relation to slots... * - paths in pWiki behave a bit differently than traditional * file-system paths, this is due to one key distinction: * in pWiki there is no distinction between a file and a * directory * i.e. each path can both contain data as a file and at the same * time support sub-paths etc. * for this reason behaviour of some APIs will differ, all paths * within a page (a-la file) are relative to its children and not * to it's siblings. For example, for page "/a/b/c" a link to "./x" * will resolve to "/a/b/c/x" and this is independent of whether * the base path is given as "/a/b/c/" or "/a/b/c" * * NOTE: implementing things in a traditional manner would * introduce lots of edge-cases and subtle ways to make * mistakes, bugs and inconsistencies. * - types of recursion * (see: pwiki/page.js: Page.macros.include(..) notes) * - slot <content/> order -- * (see: page.js: Page's .macros.slot(..) notes) * - arguments in macros that contain macros must be in quotes, e.g. * @include("./*:@(all)") * otherwise the macro will end on the first ')'... * - :all argument to all pattern paths... * * * XXX weaknesses to review: * - <store>.paths() as an index... * + decouples the search logic from the store backend * - requires the whole list of pages to be in memory * ...need to be independent of the number of pages if at * all possible -- otherwise this will hinder long-term use... * .paths() should be cached to make all path searches away from * async waits as we can test quite a number of paths before we * find a page... * ...another solution is to offload the search to the store backend * but this would require the stores to reimplement most of pwiki/path * - * * * TODO?: * - <page>.then() -- resolve when all pending write operations done ??? * - an async REPL??? * - custom element??? * - might be a good idea to try signature based security: * - sign changes * - sign sync session * - refuse changes with wrong signatures * - public keys available on client and on server * - check signatures localy * - check signatures remotely * - private key available only with author * - keep both the last signed and superceding unsigned version * - on sync ask to overwrite unsigned with signed * - check if we can use the same mechanics as ssh... * - in this view a user in the system is simply a set of keys and * a signature (a page =)) * * XXX RELATIVE relative urls are a bit odd... * Path/to/page opens Moo -> Path/to/Page/Moo * should be (???): * Path/to/page opens Moo -> Path/to/Moo * this boils down to how path.relative(..) works, treating the base * as a directory always (current) vs. only if '/' is at the end, on * one hand the current approach is more uniform with less subtle ways * to make mistakes but on the other hand this may introduce a lot * of complexity to the user writing links, e.g. how should the * following be interpreted? * page: /SomePage * link: SomeOtherPage * -> /SomeOtherPage * -> /SomePage/SomeOtherPage (current) * the current approach does not seem to be intuitive... * can this be fixed uniformly across the whole system??? * XXX document this! * * XXX need to think about search -- page function argument syntax??? * * XXX might need to get all the links (macro-level) from a page... * ...would be useful for caching... * * * **********************************************************************/ ((typeof define)[0]=='u'?function(f){module.exports=f(require)}:define) (function(require){ var module={} // make module AMD/node compatible... /*********************************************************************/ // XXX //var object = require('lib/object') var object = require('ig-object') var types = require('ig-types') var pwpath = module.path = require('./pwiki/path') var page = require('./pwiki/page') var basestore = require('./pwiki/store/base') var pouchdbstore = require('./pwiki/store/pouchdb') //--------------------------------------------------------------------- // Basic setup... // // // Store topology: // XXX // var store = module.store = { // XXX base localstorage... __proto__: pouchdbstore.PouchDBStore, /*/ __proto__: basestore.MetaStore, //*/ next: { __proto__: basestore.MetaStore }, } // XXX these are async... // ...see browser.js for a way to deal with this... // XXX note sure how to organize the system actions -- there can be two // options: // - a root ram store with all the static stuff and nest the rest // - a nested store (as is the case here) // XXX nested system store... module.setup = Promise.all([ //store.next.update('System', store.next.update( pwpath.sanitize(pwpath.SYSTEM_PATH), Object.create(basestore.BaseStore).load(page.System)), store.next.update('.templates', Object.create(basestore.BaseStore).load(page.Templates)), store.update('.config', Object.create(basestore.BaseStore).load(page.Config)), ]) // NOTE: in general the root wiki api is simply a page instance. // XXX not yet sure how to organize the actual client -- UI, hooks, .. etc var pwiki = module.pwiki = //page.Page('/', '/', store) page.CachedPage('/', '/', store) //--------------------------------------------------------------------- // comandline... if(typeof(__filename) != 'undefined' && __filename == (require.main || {}).filename){ } /********************************************************************** * vim:set ts=4 sw=4 nowrap : */ return module })
notes... Signed-off-by: Alex A. Naanou <[email protected]>
pwiki2.js
notes...
<ide><path>wiki2.js <ide> * <ide> * <ide> * XXX load new page at .scrollTop = 0 if no anchors are given... <del>* ... or remember scroll position per page... <add>* ...or remember scroll position per page... <add>* XXX macros: else/default macro args essentially mean the same thing, should we <add>* unify them to use the same name??? <ide> * XXX parser: error handling: revise page quoting... <ide> * ...need a standard mechanism to quote urls, url-args and paths... <ide> * XXX BUG? can't use < and > (both?) in page title...
Java
apache-2.0
83cad4a9157f08eaa613ad6d32c9aa31eaadc971
0
devhub-tud/devhub-prototype,devhub-tud/devhub-prototype,devhub-tud/devhub-prototype
package nl.tudelft.ewi.dea.jaxrs.account; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.net.URI; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import javax.persistence.NoResultException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import nl.tudelft.ewi.dea.dao.RegistrationTokenDao; import nl.tudelft.ewi.dea.dao.UserDao; import nl.tudelft.ewi.dea.jaxrs.utils.Renderer; import nl.tudelft.ewi.dea.model.RegistrationToken; import nl.tudelft.ewi.dea.model.User; import nl.tudelft.ewi.dea.security.UserFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; @Singleton @Path("account") public class AccountResource { private static final Logger LOG = LoggerFactory.getLogger(AccountResource.class); private final Provider<Renderer> renderers; private final RegistrationTokenDao registrationTokenDao; private final UserDao userDao; private final UserFactory userFactory; @Inject public AccountResource(final Provider<Renderer> renderers, final RegistrationTokenDao registrationTokenDao, final UserDao userDao, final UserFactory userFactory) { this.renderers = renderers; this.registrationTokenDao = registrationTokenDao; this.userDao = userDao; this.userFactory = userFactory; } @GET @Path("activate/{token}") @Produces(MediaType.TEXT_HTML) public String servePage(@PathParam("token") final String token) { LOG.trace("Serving activation page for token: {}", token); checkArgument(isNotEmpty(token)); try { registrationTokenDao.findByToken(token); } catch (final NoResultException e) { LOG.trace("Token not found in database, so not active: {}", token, e); // TODO: Render page with 'unknown token' message. return renderers.get() .setValue("scripts", Lists.newArrayList("activate-unknown-token.js")) .render("activate-unknown-token.tpl"); } // TODO: Render page with account input form. return renderers.get() .setValue("scripts", Lists.newArrayList("activate.js")) .render("activate.tpl"); } @POST @Path("activate/{token}") @Consumes(MediaType.APPLICATION_JSON) public Response processActivation(@PathParam("token") final String token, final ActivationRequest request) { LOG.trace("Processing activation with token {} and request {}", token, request); checkArgument(isNotEmpty(token)); checkNotNull(request); // TODO: The following code should be run inside a method annotated with // @Transactional. // check if token is still valid, and account doesn't exist yet. RegistrationToken registrationToken; try { registrationToken = registrationTokenDao.findByToken(token); } catch (final NoResultException e) { LOG.trace("Token not found in database, so not active: {}", token, e); return Response.status(Status.FORBIDDEN).entity("Token is not active").build(); } assert registrationToken.getEmail() != null; if (!registrationToken.getEmail().equals(request.getEmail())) { // TODO: Error: token email and request email should be the same. } final String email = registrationToken.getEmail(); boolean userExists = true; try { userDao.findByEmail(email); } catch (final NoResultException e) { LOG.trace("No user found with email: {}", email); userExists = false; } if (userExists) { // TODO: user already exists. Something is wrong. Handle this. } // TODO: Not all user fields are already there, fix this. final User u = userFactory.createUser(email, request.getDisplayName(), request.getPassword()); registrationTokenDao.remove(registrationToken); userDao.persist(u); // TODO: automatically log user in, and send a confirmation email. final long accountId = u.getId(); return Response.seeOther(URI.create("/account/" + accountId)).build(); } @GET @Path("email/{email}") @Produces(MediaType.APPLICATION_JSON) public Response findByEmail(@PathParam("email") final String email) { // TODO: Return a list of users with a matching email address. return Response.serverError().build(); } @POST @Path("{id}/promote") public Response promoteUserToTeacher(@PathParam("id") final long id) { // TODO: Promote user to teacher status. return Response.serverError().build(); } }
dev-env-admin-web/src/main/java/nl/tudelft/ewi/dea/jaxrs/account/AccountResource.java
package nl.tudelft.ewi.dea.jaxrs.account; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.net.URI; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import javax.persistence.NoResultException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import nl.tudelft.ewi.dea.dao.RegistrationTokenDao; import nl.tudelft.ewi.dea.jaxrs.utils.Renderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; @Singleton @Path("account") public class AccountResource { private static final Logger LOG = LoggerFactory.getLogger(AccountResource.class); private final Provider<Renderer> renderers; private final RegistrationTokenDao registrationTokenDao; @Inject public AccountResource(final Provider<Renderer> renderers, final RegistrationTokenDao registrationTokenDao) { this.renderers = renderers; this.registrationTokenDao = registrationTokenDao; } @GET @Path("activate/{token}") @Produces(MediaType.TEXT_HTML) public String servePage(@PathParam("token") final String token) { LOG.trace("Serving activation page for token: {}", token); checkArgument(isNotEmpty(token)); try { registrationTokenDao.findByToken(token); } catch (final NoResultException e) { LOG.trace("Token not found in database, so not active: {}", token, e); // TODO: Render page with 'unknown token' message. return renderers.get() .setValue("scripts", Lists.newArrayList("activate-unknown-token.js")) .render("activate-unknown-token.tpl"); } // TODO: Render page with account input form. return renderers.get() .setValue("scripts", Lists.newArrayList("activate.js")) .render("activate.tpl"); } @POST @Path("activate/{token}") @Consumes(MediaType.APPLICATION_JSON) public Response processActivation(@PathParam("token") final String token, final ActivationRequest request) { // TODO: check if token is still valid, and account doesn't exist yet. // TODO: delete token from database, and create account from request (in // single transaction). // TODO: automatically log user in, and send a confirmation email. final long accountId = 0; return Response.seeOther(URI.create("/account/" + accountId)).build(); } @GET @Path("email/{email}") @Produces(MediaType.APPLICATION_JSON) public Response findByEmail(@PathParam("email") final String email) { // TODO: Return a list of users with a matching email address. return Response.serverError().build(); } @POST @Path("{id}/promote") public Response promoteUserToTeacher(@PathParam("id") final long id) { // TODO: Promote user to teacher status. return Response.serverError().build(); } }
Mostly implemented activation process.
dev-env-admin-web/src/main/java/nl/tudelft/ewi/dea/jaxrs/account/AccountResource.java
Mostly implemented activation process.
<ide><path>ev-env-admin-web/src/main/java/nl/tudelft/ewi/dea/jaxrs/account/AccountResource.java <ide> package nl.tudelft.ewi.dea.jaxrs.account; <ide> <ide> import static com.google.common.base.Preconditions.checkArgument; <add>import static com.google.common.base.Preconditions.checkNotNull; <ide> import static org.apache.commons.lang3.StringUtils.isNotEmpty; <ide> <ide> import java.net.URI; <ide> import javax.ws.rs.Produces; <ide> import javax.ws.rs.core.MediaType; <ide> import javax.ws.rs.core.Response; <add>import javax.ws.rs.core.Response.Status; <ide> <ide> import nl.tudelft.ewi.dea.dao.RegistrationTokenDao; <add>import nl.tudelft.ewi.dea.dao.UserDao; <ide> import nl.tudelft.ewi.dea.jaxrs.utils.Renderer; <add>import nl.tudelft.ewi.dea.model.RegistrationToken; <add>import nl.tudelft.ewi.dea.model.User; <add>import nl.tudelft.ewi.dea.security.UserFactory; <ide> <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> private static final Logger LOG = LoggerFactory.getLogger(AccountResource.class); <ide> <ide> private final Provider<Renderer> renderers; <add> <ide> private final RegistrationTokenDao registrationTokenDao; <add> private final UserDao userDao; <add> <add> private final UserFactory userFactory; <ide> <ide> @Inject <del> public AccountResource(final Provider<Renderer> renderers, final RegistrationTokenDao registrationTokenDao) { <add> public AccountResource(final Provider<Renderer> renderers, final RegistrationTokenDao registrationTokenDao, final UserDao userDao, final UserFactory userFactory) { <ide> this.renderers = renderers; <ide> this.registrationTokenDao = registrationTokenDao; <add> this.userDao = userDao; <add> this.userFactory = userFactory; <ide> } <ide> <ide> @GET <ide> @Path("activate/{token}") <ide> @Consumes(MediaType.APPLICATION_JSON) <ide> public Response processActivation(@PathParam("token") final String token, final ActivationRequest request) { <del> // TODO: check if token is still valid, and account doesn't exist yet. <del> // TODO: delete token from database, and create account from request (in <del> // single transaction). <add> <add> LOG.trace("Processing activation with token {} and request {}", token, request); <add> <add> checkArgument(isNotEmpty(token)); <add> checkNotNull(request); <add> <add> // TODO: The following code should be run inside a method annotated with <add> // @Transactional. <add> <add> // check if token is still valid, and account doesn't exist yet. <add> RegistrationToken registrationToken; <add> try { <add> registrationToken = registrationTokenDao.findByToken(token); <add> } catch (final NoResultException e) { <add> LOG.trace("Token not found in database, so not active: {}", token, e); <add> return Response.status(Status.FORBIDDEN).entity("Token is not active").build(); <add> } <add> <add> assert registrationToken.getEmail() != null; <add> <add> if (!registrationToken.getEmail().equals(request.getEmail())) { <add> // TODO: Error: token email and request email should be the same. <add> } <add> <add> final String email = registrationToken.getEmail(); <add> <add> boolean userExists = true; <add> try { <add> userDao.findByEmail(email); <add> } catch (final NoResultException e) { <add> LOG.trace("No user found with email: {}", email); <add> userExists = false; <add> } <add> <add> if (userExists) { <add> // TODO: user already exists. Something is wrong. Handle this. <add> } <add> <add> // TODO: Not all user fields are already there, fix this. <add> final User u = userFactory.createUser(email, request.getDisplayName(), request.getPassword()); <add> <add> registrationTokenDao.remove(registrationToken); <add> userDao.persist(u); <add> <ide> // TODO: automatically log user in, and send a confirmation email. <ide> <del> final long accountId = 0; <add> final long accountId = u.getId(); <ide> <ide> return Response.seeOther(URI.create("/account/" + accountId)).build(); <add> <ide> } <ide> <ide> @GET
Java
apache-2.0
error: pathspec 'microscope-collector/src/main/java/com/vipshop/microscope/collector/receiver/NettyMessageReceiver.java' did not match any file(s) known to git
27da866d3022748f22a0bb2de1167723ed1ac1e1
1
c3p0hz/microscope,c3p0hz/microscope
package com.vipshop.microscope.collector.receiver; public class NettyMessageReceiver { }
microscope-collector/src/main/java/com/vipshop/microscope/collector/receiver/NettyMessageReceiver.java
add validater api for collector
microscope-collector/src/main/java/com/vipshop/microscope/collector/receiver/NettyMessageReceiver.java
add validater api for collector
<ide><path>icroscope-collector/src/main/java/com/vipshop/microscope/collector/receiver/NettyMessageReceiver.java <add>package com.vipshop.microscope.collector.receiver; <add> <add>public class NettyMessageReceiver { <add> <add>}
JavaScript
mit
a4c11399dd50678c1c6efb5918407de50e12314a
0
JunoLab/atom-ink
'use babel' import {CompositeDisposable, Emitter} from 'atom' import ResultView from './result-view' let layers = {} export default class Result { constructor (editor, lineRange, opts = {}) { this.emitter = new Emitter() this.disposables = new CompositeDisposable() this.editor = editor this.range = lineRange this.invalid = false opts.scope = opts.scope != null ? opts.scope : 'noscope' opts.type = opts.type != null ? opts.type : 'inline' opts.fade = opts.fade != null ? opts.fade : !(Result.removeLines(this.editor, this.range[0], this.range[1])) opts.loading = opts.loading != null ? opts.content : !(opts.content) opts.buttons = this.buttons() this.type = opts.type this.view = new ResultView(this, opts) this.attach() this.disposables.add(atom.commands.add(this.view.getView(), {'inline-results:clear': () => this.remove()})) this.txt = this.getMarkerText() this.disposables.add(this.editor.onDidChange(() => this.validateText())) } setContent (view, opts) { this.view.setContent(view, opts) } attach () { if (!layers.hasOwnProperty(this.editor.id)) { layers[this.editor.id] = this.editor.addMarkerLayer() } this.marker = layers[this.editor.id].markBufferRange([[this.range[0], 0], [this.range[1], this.editor.lineTextForBufferRow(this.range[1]).length]]) this.marker.result = this this.decorateMarker() this.disposables.add(this.marker.onDidChange((e) => this.checkMarker(e))) } buttons () { return (result) => { return [ { icon: 'icon-unfold', onclick: () => result.toggle() }, { icon: 'icon-x', onclick: () => result.remove() } ] } } decorateMarker () { let decr = {item: this.view.getView(), avoidOverflow: false} if (this.type === 'inline') { decr.type = 'overlay' decr.class = 'ink-overlay' } else if (this.type === 'block') { decr.type = 'block' decr.position = 'after' } this.decoration = this.editor.decorateMarker(this.marker, decr) setTimeout(() => this.emitter.emit('did-attach'), 50) } toggle () { if (this.type !== 'inline') return this.expanded ? this.collapse() : this.expand() } expand () { this.expanded = true if (this.decoration) this.decoration.destroy() let row = this.marker.getEndBufferPosition().row this.expMarker = this.editor.markBufferRange([[row, 0], [row, 1]]) let decr = { item: this.view.getView(), avoidOverflow: false, type: 'overlay', class: 'ink-underlay', invalidate: 'never' } this.expDecoration = this.editor.decorateMarker(this.expMarker, decr) this.emitter.emit('did-update') } collapse () { this.expanded = false if (this.expMarker) this.expMarker.destroy() this.decorateMarker() this.emitter.emit('did-update') } onDidDestroy (f) { this.emitter.on('did-destroy', f) } onDidUpdate (f) { this.emitter.on('did-update', f) } onDidValidate (f) { this.emitter.on('did-validate', f) } onDidInvalidate (f) { this.emitter.on('did-invalidate', f) } onDidAttach (f) { this.emitter.on('did-attach', f) } onDidRemove (f) { this.emitter.on('did-remove', f) } remove () { this.emitter.emit('did-remove') setTimeout(() => this.destroy(), 200) } destroy () { this.emitter.emit('did-destroy') this.isDestroyed = true this.emitter.dispose() this.marker.destroy() if (this.expMarker) this.expMarker.destroy() this.disposables.dispose() } validate () { this.invalid = false this.emitter.emit('did-validate') } invalidate () { this.invalid = true this.emitter.emit('did-invalidate') } validateText (ed) { let txt = this.getMarkerText() if (this.txt === txt && this.invalid) { this.validate() } else if (this.txt !== txt && !this.invalid) { this.invalidate() } } checkMarker (e) { if (!e.isValid || this.marker.getBufferRange().isEmpty()) { this.remove() } else if (e.textChanged) { let old = this.editor.bufferPositionForScreenPosition(e.oldHeadScreenPosition) let nu = this.editor.bufferPositionForScreenPosition(e.newHeadScreenPosition) if (old.isLessThan(nu)) { let text = this.editor.getTextInBufferRange([old, nu]) if (text.match(/^\r?\n\s*$/)) { this.marker.setHeadBufferPosition(old) } } } } getMarkerText () { return this.editor.getTextInBufferRange(this.marker.getBufferRange()).trim() } // static methods static all () { let results = [] for (let item of atom.workspace.getPaneItems()) { if (!atom.workspace.isTextEditor(item) || !layers[item.id]) continue layers[item.id].getMarkers().forEach(m => results.push(m.result)) } return results } static invalidateAll () { for (let result of Result.all()) { delete result.text result.invalidate() } } static forLines (ed, start, end, type = 'any') { if (!layers[ed.id]) return return layers[ed.id].findMarkers({intersectsBufferRowRange: [start, end]}) .filter((m) => (type === 'any' || m.result.type === type)) .map((m) => m.result) } static removeLines (ed, start, end, type = 'any') { let rs = Result.forLines(ed, start, end, type) if (!rs) return rs.map((r) => r.remove()) rs.length > 0 } static removeAll (ed = atom.workspace.getActiveTextEditor()) { if (!layers[ed.id]) return layers[ed.id].getMarkers().forEach((m) => m.result.remove()) } static removeCurrent (e) { const ed = atom.workspace.getActiveTextEditor() let done = false if (ed) { for (let sel of ed.getSelections()) { if (Result.removeLines(ed, sel.getHeadBufferPosition().row, sel.getTailBufferPosition().row)) { done = true } } } if (!done) e.abortKeyBinding() } static toggleCurrent () { const ed = atom.workspace.getActiveTextEditor() for (const sel of ed.getSelections()) { const rs = Result.forLines(ed, sel.getHeadBufferPosition().row, sel.getTailBufferPosition().row) if (!rs) continue rs.forEach((r) => r.toggle()) } } // Commands static activate () { this.subs = new CompositeDisposable() this.subs.add(atom.commands.add('atom-text-editor:not([mini])', { 'inline:clear-current': (e) => Result.removeCurrent(e), 'inline-results:clear-all': () => Result.removeAll(), 'inline-results:toggle': () => Result.toggleCurrent() })) let listener = () => { for (let edid in layers) { let res = layers[edid].getMarkers().map((m) => m.result) res.filter((r) => r.style === 'inline') if (res.length === 0) continue // DOM reads let rect = res[0].editor.editorElement.getBoundingClientRect() res.forEach((r) => r.view.decideUpdateWidth(rect)) // DOM writes res.forEach((r) => r.view.updateWidth(rect)) } setTimeout(() => { process.nextTick(() => window.requestAnimationFrame(listener)) }, 15*1000/60) } window.requestAnimationFrame(listener) return } static deactivate () { this.subs.dispose() } }
lib/editor/result.js
'use babel' import {CompositeDisposable, Emitter} from 'atom' import ResultView from './result-view' let layers = {} export default class Result { constructor (editor, lineRange, opts = {}) { this.emitter = new Emitter() this.disposables = new CompositeDisposable() this.editor = editor this.range = lineRange this.invalid = false opts.scope = opts.scope != null ? opts.scope : 'noscope' opts.type = opts.type != null ? opts.type : 'inline' opts.fade = opts.fade != null ? opts.fade : !(Result.removeLines(this.editor, this.range[0], this.range[1])) opts.loading = opts.loading != null ? opts.content : !(opts.content) opts.buttons = this.buttons() this.type = opts.type this.view = new ResultView(this, opts) this.attach() this.disposables.add(atom.commands.add(this.view.getView(), {'inline-results:clear': () => this.remove()})) this.txt = this.getMarkerText() this.disposables.add(this.editor.onDidChange(() => this.validateText())) } setContent (view, opts) { this.view.setContent(view, opts) } attach () { if (!layers.hasOwnProperty(this.editor.id)) { layers[this.editor.id] = this.editor.addMarkerLayer() } this.marker = layers[this.editor.id].markBufferRange([[this.range[0], 0], [this.range[1], this.editor.lineTextForBufferRow(this.range[1]).length]]) this.marker.result = this this.decorateMarker() this.disposables.add(this.marker.onDidChange((e) => this.checkMarker(e))) } buttons () { return (result) => { return [ { icon: 'icon-unfold', onclick: () => result.toggle() }, { icon: 'icon-x', onclick: () => result.remove() } ] } } decorateMarker () { let decr = {item: this.view.getView(), avoidOverflow: false} if (this.type === 'inline') { decr.type = 'overlay' decr.class = 'ink-overlay' } else if (this.type === 'block') { decr.type = 'block' decr.position = 'after' } this.decoration = this.editor.decorateMarker(this.marker, decr) setTimeout(() => this.emitter.emit('did-attach'), 50) } toggle () { if (this.type !== 'inline') return this.expanded ? this.collapse() : this.expand() } expand () { this.expanded = true if (this.decoration) this.decoration.destroy() let row = this.marker.getEndBufferPosition().row this.expMarker = this.editor.markBufferRange([[row, 0], [row, 1]]) let decr = { item: this.view.getView(), avoidOverflow: false, type: 'overlay', class: 'ink-underlay', invalidate: 'never' } this.expDecoration = this.editor.decorateMarker(this.expMarker, decr) this.emitter.emit('did-update') } collapse () { this.expanded = false if (this.expMarker) this.expMarker.destroy() this.decorateMarker() this.emitter.emit('did-update') } onDidDestroy (f) { this.emitter.on('did-destroy', f) } onDidUpdate (f) { this.emitter.on('did-update', f) } onDidValidate (f) { this.emitter.on('did-validate', f) } onDidInvalidate (f) { this.emitter.on('did-invalidate', f) } onDidAttach (f) { this.emitter.on('did-attach', f) } onDidRemove (f) { this.emitter.on('did-remove', f) } remove () { this.emitter.emit('did-remove') setTimeout(() => this.destroy(), 200) } destroy () { this.emitter.emit('did-destroy') this.isDestroyed = true this.emitter.dispose() this.marker.destroy() if (this.expMarker) this.expMarker.destroy() this.disposables.dispose() } validate () { this.invalid = false this.emitter.emit('did-validate') } invalidate () { this.invalid = true this.emitter.emit('did-invalidate') } validateText (ed) { let txt = this.getMarkerText() if (this.txt === txt && this.invalid) { this.validate() } else if (this.txt !== txt && !this.invalid) { this.invalidate() } } checkMarker (e) { if (!e.isValid || this.marker.getBufferRange().isEmpty()) { this.remove() } else if (e.textChanged) { let old = e.oldHeadScreenPosition let nu = e.newHeadScreenPosition if (old.isLessThan(nu)) { let text = this.editor.getTextInRange([old, nu]) if (text.match(/^\r?\n\s*$/)) { this.marker.setHeadBufferPosition(old) } } } } getMarkerText () { return this.editor.getTextInRange(this.marker.getBufferRange()).trim() } // static methods static all () { let results = [] for (let item of atom.workspace.getPaneItems()) { if (!atom.workspace.isTextEditor(item) || !layers[item.id]) continue layers[item.id].getMarkers().forEach(m => results.push(m.result)) } return results } static invalidateAll () { for (let result of Result.all()) { delete result.text result.invalidate() } } static forLines (ed, start, end, type = 'any') { if (!layers[ed.id]) return return layers[ed.id].findMarkers({intersectsBufferRowRange: [start, end]}) .filter((m) => (type === 'any' || m.result.type === type)) .map((m) => m.result) } static removeLines (ed, start, end, type = 'any') { let rs = Result.forLines(ed, start, end, type) if (!rs) return rs.map((r) => r.remove()) rs.length > 0 } static removeAll (ed = atom.workspace.getActiveTextEditor()) { if (!layers[ed.id]) return layers[ed.id].getMarkers().forEach((m) => m.result.remove()) } static removeCurrent (e) { const ed = atom.workspace.getActiveTextEditor() let done = false if (ed) { for (let sel of ed.getSelections()) { if (Result.removeLines(ed, sel.getHeadBufferPosition().row, sel.getTailBufferPosition().row)) { done = true } } } if (!done) e.abortKeyBinding() } static toggleCurrent () { const ed = atom.workspace.getActiveTextEditor() for (const sel of ed.getSelections()) { const rs = Result.forLines(ed, sel.getHeadBufferPosition().row, sel.getTailBufferPosition().row) if (!rs) continue rs.forEach((r) => r.toggle()) } } // Commands static activate () { this.subs = new CompositeDisposable() this.subs.add(atom.commands.add('atom-text-editor:not([mini])', { 'inline:clear-current': (e) => Result.removeCurrent(e), 'inline-results:clear-all': () => Result.removeAll(), 'inline-results:toggle': () => Result.toggleCurrent() })) let listener = () => { for (let edid in layers) { let res = layers[edid].getMarkers().map((m) => m.result) res.filter((r) => r.style === 'inline') if (res.length === 0) continue // DOM reads let rect = res[0].editor.editorElement.getBoundingClientRect() res.forEach((r) => r.view.decideUpdateWidth(rect)) // DOM writes res.forEach((r) => r.view.updateWidth(rect)) } setTimeout(() => { process.nextTick(() => window.requestAnimationFrame(listener)) }, 15*1000/60) } window.requestAnimationFrame(listener) return } static deactivate () { this.subs.dispose() } }
fix results in editor with wrapped lines
lib/editor/result.js
fix results in editor with wrapped lines
<ide><path>ib/editor/result.js <ide> if (!e.isValid || this.marker.getBufferRange().isEmpty()) { <ide> this.remove() <ide> } else if (e.textChanged) { <del> let old = e.oldHeadScreenPosition <del> let nu = e.newHeadScreenPosition <add> let old = this.editor.bufferPositionForScreenPosition(e.oldHeadScreenPosition) <add> let nu = this.editor.bufferPositionForScreenPosition(e.newHeadScreenPosition) <ide> if (old.isLessThan(nu)) { <del> let text = this.editor.getTextInRange([old, nu]) <add> let text = this.editor.getTextInBufferRange([old, nu]) <ide> if (text.match(/^\r?\n\s*$/)) { <ide> this.marker.setHeadBufferPosition(old) <ide> } <ide> } <ide> <ide> getMarkerText () { <del> return this.editor.getTextInRange(this.marker.getBufferRange()).trim() <add> return this.editor.getTextInBufferRange(this.marker.getBufferRange()).trim() <ide> } <ide> <ide> // static methods
Java
apache-2.0
2f5045d449476c24f3987112485acf9370908706
0
juanavelez/hazelcast,Donnerbart/hazelcast,tombujok/hazelcast,tombujok/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,lmjacksoniii/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,emrahkocaman/hazelcast,dsukhoroslov/hazelcast,emre-aydin/hazelcast,lmjacksoniii/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast
package com.hazelcast.queue; import com.hazelcast.core.IQueue; import com.hazelcast.core.ItemEvent; import com.hazelcast.core.ItemListener; import com.hazelcast.monitor.LocalQueueStats; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.assertEquals; @RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class QueueStatisticsTest extends AbstractQueueTest { @Test public void testItemCount() { IQueue queue = newQueue(); int items = 20; for (int i = 0; i < items; i++) { queue.offer("item" + i); } LocalQueueStats stats = queue.getLocalQueueStats(); assertEquals(20, stats.getOwnedItemCount()); assertEquals(0, stats.getBackupItemCount()); } @Test public void testOfferOperationCount() throws InterruptedException { IQueue queue = newQueue(); for (int i = 0; i < 10; i++) { queue.offer("item" + i); } for (int i = 0; i < 10; i++) { queue.add("item" + i); } for (int i = 0; i < 10; i++) { queue.put("item" + i); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(30, stats.getOfferOperationCount()); } }; assertTrueEventually(task); } @Test public void testRejectedOfferOperationCount() { IQueue queue = newQueue_WithMaxSizeConfig(30); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } for (int i = 0; i < 10; i++) { queue.offer("item" + i); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(10, stats.getRejectedOfferOperationCount()); } }; assertTrueEventually(task); } @Test public void testPollOperationCount() throws InterruptedException { IQueue queue = newQueue(); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } for (int i = 0; i < 10; i++) { queue.remove(); } for (int i = 0; i < 10; i++) { queue.take(); } for (int i = 0; i < 10; i++) { queue.poll(); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(30, stats.getPollOperationCount()); } }; assertTrueEventually(task); } @Test public void testEmptyPollOperationCount() { IQueue queue = newQueue(); for (int i = 0; i < 10; i++) { queue.poll(); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(10, stats.getEmptyPollOperationCount()); } }; assertTrueEventually(task); } @Test public void testOtherOperationCount() { IQueue queue = newQueue(); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } ArrayList<String> list = new ArrayList<String>(); queue.drainTo(list); queue.addAll(list); queue.removeAll(list); final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(3, stats.getOtherOperationsCount()); } }; assertTrueEventually(task); } @Test public void testAge() { IQueue queue = newQueue(); queue.offer("maxAgeItem"); queue.offer("minAgeItem"); LocalQueueStats stats = queue.getLocalQueueStats(); long maxAge = stats.getMaxAge(); long minAge = stats.getMinAge(); long testAge = (maxAge + minAge) / 2; long avgAge = stats.getAvgAge(); assertEquals(testAge, avgAge); } @Test public void testEventOperationCount() { IQueue queue = newQueue(); TestListener listener = new TestListener(30); queue.addItemListener(listener, true); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } for (int i = 0; i < 30; i++) { queue.poll(); } final LocalQueueStats stats = queue.getLocalQueueStats(); assertOpenEventually(listener.addedLatch); assertOpenEventually(listener.removedLatch); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(60, stats.getEventOperationCount()); } }); } private static class TestListener implements ItemListener { public final CountDownLatch addedLatch; public final CountDownLatch removedLatch; public TestListener(int latchCount) { addedLatch = new CountDownLatch(latchCount); removedLatch = new CountDownLatch(latchCount); } public void itemAdded(ItemEvent item) { addedLatch.countDown(); } public void itemRemoved(ItemEvent item) { removedLatch.countDown(); } } }
hazelcast/src/test/java/com/hazelcast/queue/QueueStatisticsTest.java
package com.hazelcast.queue; import com.hazelcast.core.IQueue; import com.hazelcast.core.ItemEvent; import com.hazelcast.core.ItemListener; import com.hazelcast.monitor.LocalQueueStats; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.assertEquals; @RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class QueueStatisticsTest extends AbstractQueueTest { @Test public void testItemCount() { IQueue queue = newQueue(); int items = 20; for (int i = 0; i < items; i++) { queue.offer("item" + i); } LocalQueueStats stats = queue.getLocalQueueStats(); assertEquals(20, stats.getOwnedItemCount()); assertEquals(0, stats.getBackupItemCount()); } @Test public void testOfferOperationCount() throws InterruptedException { IQueue queue = newQueue(); for (int i = 0; i < 10; i++) { queue.offer("item" + i); } for (int i = 0; i < 10; i++) { queue.add("item" + i); } for (int i = 0; i < 10; i++) { queue.put("item" + i); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(30, stats.getOfferOperationCount()); } }; assertTrueEventually(task); } @Test public void testRejectedOfferOperationCount() { IQueue queue = newQueue_WithMaxSizeConfig(30); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } for (int i = 0; i < 10; i++) { queue.offer("item" + i); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(10, stats.getRejectedOfferOperationCount()); } }; assertTrueEventually(task); } @Test public void testPollOperationCount() throws InterruptedException { IQueue queue = newQueue(); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } for (int i = 0; i < 10; i++) { queue.remove(); } for (int i = 0; i < 10; i++) { queue.take(); } for (int i = 0; i < 10; i++) { queue.poll(); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(30, stats.getPollOperationCount()); } }; assertTrueEventually(task); } @Test public void testEmptyPollOperationCount() { IQueue queue = newQueue(); for (int i = 0; i < 10; i++) { queue.poll(); } final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(10, stats.getEmptyPollOperationCount()); } }; assertTrueEventually(task); } @Test public void testOtherOperationCount() { IQueue queue = newQueue(); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } ArrayList<String> list = new ArrayList<String>(); queue.drainTo(list); queue.addAll(list); queue.removeAll(list); final LocalQueueStats stats = queue.getLocalQueueStats(); AssertTask task = new AssertTask() { @Override public void run() throws Exception { assertEquals(3, stats.getOtherOperationsCount()); } }; assertTrueEventually(task); } @Test public void testAge() { IQueue queue = newQueue(); queue.offer("maxAgeItem"); queue.offer("minAgeItem"); LocalQueueStats stats = queue.getLocalQueueStats(); long maxAge = stats.getMaxAge(); long minAge = stats.getMinAge(); long testAge = (maxAge + minAge) / 2; long avgAge = stats.getAvgAge(); assertEquals(testAge, avgAge); } @Test public void testEventOperationCount() { IQueue queue = newQueue(); TestListener listener = new TestListener(30); queue.addItemListener(listener, true); for (int i = 0; i < 30; i++) { queue.offer("item" + i); } for (int i = 0; i < 30; i++) { queue.poll(); } LocalQueueStats stats = queue.getLocalQueueStats(); assertOpenEventually(listener.addedLatch); assertOpenEventually(listener.removedLatch); assertEquals(60, stats.getEventOperationCount()); } private static class TestListener implements ItemListener { public final CountDownLatch addedLatch; public final CountDownLatch removedLatch; public TestListener(int latchCount) { addedLatch = new CountDownLatch(latchCount); removedLatch = new CountDownLatch(latchCount); } public void itemAdded(ItemEvent item) { addedLatch.countDown(); } public void itemRemoved(ItemEvent item) { removedLatch.countDown(); } } }
assertTrueEventually check added to rarely failing test testEventOperationCount
hazelcast/src/test/java/com/hazelcast/queue/QueueStatisticsTest.java
assertTrueEventually check added to rarely failing test testEventOperationCount
<ide><path>azelcast/src/test/java/com/hazelcast/queue/QueueStatisticsTest.java <ide> for (int i = 0; i < 30; i++) { <ide> queue.poll(); <ide> } <del> LocalQueueStats stats = queue.getLocalQueueStats(); <add> final LocalQueueStats stats = queue.getLocalQueueStats(); <ide> assertOpenEventually(listener.addedLatch); <ide> assertOpenEventually(listener.removedLatch); <del> assertEquals(60, stats.getEventOperationCount()); <add> assertTrueEventually(new AssertTask() { <add> @Override <add> public void run() throws Exception { <add> assertEquals(60, stats.getEventOperationCount()); <add> } <add> }); <ide> } <ide> <ide> private static class TestListener implements ItemListener {
Java
mit
1bb83270552fc582bf297bf08aa92b6f30ac1bc5
0
bladecoder/blade-ink
package com.bladecoder.ink.runtime; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import com.bladecoder.ink.runtime.CallStack.Element; import com.bladecoder.ink.runtime.SimpleJson.InnerWriter; import com.bladecoder.ink.runtime.SimpleJson.Writer; /** * All story state information is included in the StoryState class, including * global variables, read counts, the pointer to the current point in the story, * the call stack (for tunnels, functions, etc), and a few other smaller bits * and pieces. You can save the current state using the json serialisation * functions ToJson and LoadJson. */ public class StoryState { /** * The current version of the state save file JSON-based format. */ public static final int kInkSaveStateVersion = 9; public static final int kMinCompatibleLoadVersion = 8; public static final String kDefaultFlowName = "DEFAULT_FLOW"; // REMEMBER! REMEMBER! REMEMBER! // When adding state, update the Copy method and serialisation // REMEMBER! REMEMBER! REMEMBER! private List<String> currentErrors; private List<String> currentWarnings; private int currentTurnIndex; private boolean didSafeExit; private final Pointer divertedPointer = new Pointer(); private List<RTObject> evaluationStack; private Story story; private int storySeed; private int previousRandom; private HashMap<String, Integer> turnIndices; private VariablesState variablesState; private HashMap<String, Integer> visitCounts; private String currentText; private boolean outputStreamTextDirty = true; private boolean outputStreamTagsDirty = true; private List<String> currentTags; private StatePatch patch; private HashMap<String, Flow> namedFlows; private Flow currentFlow; StoryState(Story story) { this.story = story; currentFlow = new Flow(kDefaultFlowName, story); outputStreamDirty(); evaluationStack = new ArrayList<>(); variablesState = new VariablesState(getCallStack(), story.getListDefinitions()); visitCounts = new HashMap<>(); turnIndices = new HashMap<>(); currentTurnIndex = -1; // Seed the shuffle random numbers long timeSeed = System.currentTimeMillis(); storySeed = new Random(timeSeed).nextInt() % 100; previousRandom = 0; goToStart(); } int getCallStackDepth() { return getCallStack().getDepth(); } void addError(String message, boolean isWarning) { if (!isWarning) { if (currentErrors == null) currentErrors = new ArrayList<>(); currentErrors.add(message); } else { if (currentWarnings == null) currentWarnings = new ArrayList<>(); currentWarnings.add(message); } } // Warning: Any RTObject content referenced within the StoryState will // be re-referenced rather than cloned. This is generally okay though since // RTObjects are treated as immutable after they've been set up. // (e.g. we don't edit a Runtime.StringValue after it's been created an added.) // I wonder if there's a sensible way to enforce that..?? StoryState copyAndStartPatching() { StoryState copy = new StoryState(story); copy.patch = new StatePatch(patch); // Hijack the new default flow to become a copy of our current one // If the patch is applied, then this new flow will replace the old one in // _namedFlows copy.currentFlow.name = currentFlow.name; copy.currentFlow.callStack = new CallStack(currentFlow.callStack); copy.currentFlow.currentChoices.addAll(currentFlow.currentChoices); copy.currentFlow.outputStream.addAll(currentFlow.outputStream); copy.outputStreamDirty(); // The copy of the state has its own copy of the named flows dictionary, // except with the current flow replaced with the copy above // (Assuming we're in multi-flow mode at all. If we're not then // the above copy is simply the default flow copy and we're done) if (namedFlows != null) { copy.namedFlows = new HashMap<>(); for (Map.Entry<String, Flow> namedFlow : namedFlows.entrySet()) copy.namedFlows.put(namedFlow.getKey(), namedFlow.getValue()); copy.namedFlows.put(currentFlow.name, copy.currentFlow); } if (hasError()) { copy.currentErrors = new ArrayList<>(); copy.currentErrors.addAll(currentErrors); } if (hasWarning()) { copy.currentWarnings = new ArrayList<>(); copy.currentWarnings.addAll(currentWarnings); } // ref copy - exactly the same variables state! // we're expecting not to read it only while in patch mode // (though the callstack will be modified) copy.variablesState = variablesState; copy.variablesState.setCallStack(copy.getCallStack()); copy.variablesState.setPatch(copy.patch); copy.evaluationStack.addAll(evaluationStack); if (!divertedPointer.isNull()) copy.divertedPointer.assign(divertedPointer); copy.setPreviousPointer(getPreviousPointer()); // visit counts and turn indicies will be read only, not modified // while in patch mode copy.visitCounts = visitCounts; copy.turnIndices = turnIndices; copy.currentTurnIndex = currentTurnIndex; copy.storySeed = storySeed; copy.previousRandom = previousRandom; copy.setDidSafeExit(didSafeExit); return copy; } void popFromOutputStream(int count) { getOutputStream().subList(getOutputStream().size() - count, getOutputStream().size()).clear(); outputStreamDirty(); } String getCurrentText() { if (outputStreamTextDirty) { StringBuilder sb = new StringBuilder(); for (RTObject outputObj : getOutputStream()) { StringValue textContent = null; if (outputObj instanceof StringValue) textContent = (StringValue) outputObj; if (textContent != null) { sb.append(textContent.value); } } currentText = cleanOutputWhitespace(sb.toString()); outputStreamTextDirty = false; } return currentText; } /** * Cleans inline whitespace in the following way: - Removes all whitespace from * the start and end of line (including just before a \n) - Turns all * consecutive space and tab runs into single spaces (HTML style) */ String cleanOutputWhitespace(String str) { StringBuilder sb = new StringBuilder(str.length()); int currentWhitespaceStart = -1; int startOfLine = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); boolean isInlineWhitespace = c == ' ' || c == '\t'; if (isInlineWhitespace && currentWhitespaceStart == -1) currentWhitespaceStart = i; if (!isInlineWhitespace) { if (c != '\n' && currentWhitespaceStart > 0 && currentWhitespaceStart != startOfLine) { sb.append(' '); } currentWhitespaceStart = -1; } if (c == '\n') startOfLine = i + 1; if (!isInlineWhitespace) sb.append(c); } return sb.toString(); } /** * Ends the current ink flow, unwrapping the callstack but without affecting any * variables. Useful if the ink is (say) in the middle a nested tunnel, and you * want it to reset so that you can divert elsewhere using ChoosePathString(). * Otherwise, after finishing the content you diverted to, it would continue * where it left off. Calling this is equivalent to calling -&gt; END in ink. */ public void forceEnd() throws Exception { getCallStack().reset(); currentFlow.currentChoices.clear(); setCurrentPointer(Pointer.Null); setPreviousPointer(Pointer.Null); setDidSafeExit(true); } // Add the end of a function call, trim any whitespace from the end. // We always trim the start and end of the text that a function produces. // The start whitespace is discard as it is generated, and the end // whitespace is trimmed in one go here when we pop the function. void trimWhitespaceFromFunctionEnd() { assert (getCallStack().getCurrentElement().type == PushPopType.Function); int functionStartPoint = getCallStack().getCurrentElement().functionStartInOuputStream; // If the start point has become -1, it means that some non-whitespace // text has been pushed, so it's safe to go as far back as we're able. if (functionStartPoint == -1) { functionStartPoint = 0; } // Trim whitespace from END of function call for (int i = getOutputStream().size() - 1; i >= functionStartPoint; i--) { RTObject obj = getOutputStream().get(i); if (!(obj instanceof StringValue)) continue; StringValue txt = (StringValue) obj; if (obj instanceof ControlCommand) break; if (txt.isNewline() || txt.isInlineWhitespace()) { getOutputStream().remove(i); outputStreamDirty(); } else { break; } } } void popCallstack() throws Exception { popCallstack(null); } void popCallstack(PushPopType popType) throws Exception { // Add the end of a function call, trim any whitespace from the end. if (getCallStack().getCurrentElement().type == PushPopType.Function) trimWhitespaceFromFunctionEnd(); getCallStack().pop(popType); } Pointer getCurrentPointer() { return getCallStack().getCurrentElement().currentPointer; } List<String> getCurrentTags() { if (outputStreamTagsDirty) { currentTags = new ArrayList<>(); for (RTObject outputObj : getOutputStream()) { Tag tag = null; if (outputObj instanceof Tag) tag = (Tag) outputObj; if (tag != null) { currentTags.add(tag.getText()); } } outputStreamTagsDirty = false; } return currentTags; } public String getCurrentFlowName() { return currentFlow.name; } boolean getInExpressionEvaluation() { return getCallStack().getCurrentElement().inExpressionEvaluation; } Pointer getPreviousPointer() { return getCallStack().getcurrentThread().previousPointer; } void goToStart() { getCallStack().getCurrentElement().currentPointer.assign(Pointer.startOf(story.getMainContentContainer())); } void switchFlowInternal(String flowName) throws Exception { if (flowName == null) throw new Exception("Must pass a non-null string to Story.SwitchFlow"); if (namedFlows == null) { namedFlows = new HashMap<>(); namedFlows.put(kDefaultFlowName, currentFlow); } if (flowName.equals(currentFlow.name)) { return; } Flow flow = namedFlows.get(flowName); if (flow == null) { flow = new Flow(flowName, story); namedFlows.put(flowName, flow); } currentFlow = flow; variablesState.setCallStack(currentFlow.callStack); // Cause text to be regenerated from output stream if necessary outputStreamDirty(); } void switchToDefaultFlowInternal() throws Exception { if (namedFlows == null) return; switchFlowInternal(kDefaultFlowName); } void removeFlowInternal(String flowName) throws Exception { if (flowName == null) throw new Exception("Must pass a non-null string to Story.DestroyFlow"); if (flowName.equals(kDefaultFlowName)) throw new Exception("Cannot destroy default flow"); // If we're currently in the flow that's being removed, switch back to default if (currentFlow.name.equals(flowName)) { switchToDefaultFlowInternal(); } namedFlows.remove(flowName); } boolean hasError() { return currentErrors != null && currentErrors.size() > 0; } boolean inStringEvaluation() { for (int i = getOutputStream().size() - 1; i >= 0; i--) { ControlCommand cmd = getOutputStream().get(i) instanceof ControlCommand ? (ControlCommand) getOutputStream().get(i) : null; if (cmd != null && cmd.getCommandType() == ControlCommand.CommandType.BeginString) { return true; } } return false; } /** * Loads a previously saved state in JSON format. * * @param json The JSON String to load. */ public void loadJson(String json) throws Exception { HashMap<String, Object> jObject = SimpleJson.textToDictionary(json); loadJsonObj(jObject); } List<Choice> getCurrentChoices() { // If we can continue generating text content rather than choices, // then we reflect the choice list as being empty, since choices // should always come at the end. if (canContinue()) return new ArrayList<>(); return currentFlow.currentChoices; } List<Choice> getGeneratedChoices() { return currentFlow.currentChoices; } boolean canContinue() { return !getCurrentPointer().isNull() && !hasError(); } List<String> getCurrentErrors() { return currentErrors; } List<String> getCurrentWarnings() { return currentWarnings; } boolean hasWarning() { return currentWarnings != null && currentWarnings.size() > 0; } List<RTObject> getOutputStream() { return currentFlow.outputStream; } CallStack getCallStack() { return currentFlow.callStack; } VariablesState getVariablesState() { return variablesState; } List<RTObject> getEvaluationStack() { return evaluationStack; } int getStorySeed() { return storySeed; } void setStorySeed(int s) { storySeed = s; } int getPreviousRandom() { return previousRandom; } void setPreviousRandom(int i) { previousRandom = i; } int getCurrentTurnIndex() { return currentTurnIndex; } boolean outputStreamContainsContent() { for (RTObject content : getOutputStream()) { if (content instanceof StringValue) return true; } return false; } boolean outputStreamEndsInNewline() { if (getOutputStream().size() > 0) { for (int i = getOutputStream().size() - 1; i >= 0; i--) { RTObject obj = getOutputStream().get(i); if (obj instanceof ControlCommand) // e.g. BeginString break; StringValue text = getOutputStream().get(i) instanceof StringValue ? (StringValue) getOutputStream().get(i) : null; if (text != null) { if (text.isNewline()) return true; else if (text.isNonWhitespace()) break; } } } return false; } RTObject peekEvaluationStack() { return evaluationStack.get(evaluationStack.size() - 1); } RTObject popEvaluationStack() { RTObject obj = evaluationStack.get(evaluationStack.size() - 1); evaluationStack.remove(evaluationStack.size() - 1); return obj; } List<RTObject> popEvaluationStack(int numberOfObjects) throws Exception { if (numberOfObjects > evaluationStack.size()) { throw new Exception("trying to pop too many objects"); } List<RTObject> popped = new ArrayList<>( evaluationStack.subList(evaluationStack.size() - numberOfObjects, evaluationStack.size())); evaluationStack.subList(evaluationStack.size() - numberOfObjects, evaluationStack.size()).clear(); return popped; } void pushEvaluationStack(RTObject obj) { // Include metadata about the origin List for set values when // they're used, so that lower level functions can make use // of the origin list to get related items, or make comparisons // with the integer values etc. ListValue listValue = null; if (obj instanceof ListValue) listValue = (ListValue) obj; if (listValue != null) { // Update origin when list is has something to indicate the list // origin InkList rawList = listValue.getValue(); if (rawList.getOriginNames() != null) { if (rawList.getOrigins() == null) rawList.setOrigins(new ArrayList<ListDefinition>()); rawList.getOrigins().clear(); for (String n : rawList.getOriginNames()) { ListDefinition def = story.getListDefinitions().getListDefinition(n); if (!rawList.getOrigins().contains(def)) rawList.getOrigins().add(def); } } } evaluationStack.add(obj); } // Push to output stream, but split out newlines in text for consistency // in dealing with them later. void pushToOutputStream(RTObject obj) { StringValue text = obj instanceof StringValue ? (StringValue) obj : null; if (text != null) { List<StringValue> listText = trySplittingHeadTailWhitespace(text); if (listText != null) { for (StringValue textObj : listText) { pushToOutputStreamIndividual(textObj); } outputStreamDirty(); return; } } pushToOutputStreamIndividual(obj); } void pushToOutputStreamIndividual(RTObject obj) { Glue glue = obj instanceof Glue ? (Glue) obj : null; StringValue text = obj instanceof StringValue ? (StringValue) obj : null; boolean includeInOutput = true; // New glue, so chomp away any whitespace from the end of the stream if (glue != null) { trimNewlinesFromOutputStream(); includeInOutput = true; } // New text: do we really want to append it, if it's whitespace? // Two different reasons for whitespace to be thrown away: // - Function start/end trimming // - User defined glue: <> // We also need to know when to stop trimming, when there's non-whitespace. else if (text != null) { // Where does the current function call begin? int functionTrimIndex = -1; Element currEl = getCallStack().getCurrentElement(); if (currEl.type == PushPopType.Function) { functionTrimIndex = currEl.functionStartInOuputStream; } // Do 2 things: // - Find latest glue // - Check whether we're in the middle of string evaluation // If we're in string eval within the current function, we // don't want to trim back further than the length of the current string. int glueTrimIndex = -1; for (int i = getOutputStream().size() - 1; i >= 0; i--) { RTObject o = getOutputStream().get(i); ControlCommand c = o instanceof ControlCommand ? (ControlCommand) o : null; Glue g = o instanceof Glue ? (Glue) o : null; // Find latest glue if (g != null) { glueTrimIndex = i; break; } // Don't function-trim past the start of a string evaluation section else if (c != null && c.getCommandType() == ControlCommand.CommandType.BeginString) { if (i >= functionTrimIndex) { functionTrimIndex = -1; } break; } } // Where is the most agressive (earliest) trim point? int trimIndex = -1; if (glueTrimIndex != -1 && functionTrimIndex != -1) trimIndex = Math.min(functionTrimIndex, glueTrimIndex); else if (glueTrimIndex != -1) trimIndex = glueTrimIndex; else trimIndex = functionTrimIndex; // So, are we trimming then? if (trimIndex != -1) { // While trimming, we want to throw all newlines away, // whether due to glue or the start of a function if (text.isNewline()) { includeInOutput = false; } // Able to completely reset when normal text is pushed else if (text.isNonWhitespace()) { if (glueTrimIndex > -1) removeExistingGlue(); // Tell all functions in callstack that we have seen proper text, // so trimming whitespace at the start is done. if (functionTrimIndex > -1) { List<Element> callstackElements = getCallStack().getElements(); for (int i = callstackElements.size() - 1; i >= 0; i--) { Element el = callstackElements.get(i); if (el.type == PushPopType.Function) { el.functionStartInOuputStream = -1; } else { break; } } } } } // De-duplicate newlines, and don't ever lead with a newline else if (text.isNewline()) { if (outputStreamEndsInNewline() || !outputStreamContainsContent()) includeInOutput = false; } } if (includeInOutput) { getOutputStream().add(obj); outputStreamDirty(); } } // Only called when non-whitespace is appended void removeExistingGlue() { for (int i = getOutputStream().size() - 1; i >= 0; i--) { RTObject c = getOutputStream().get(i); if (c instanceof Glue) { getOutputStream().remove(i); } else if (c instanceof ControlCommand) { // e.g. // BeginString break; } } outputStreamDirty(); } void outputStreamDirty() { outputStreamTextDirty = true; outputStreamTagsDirty = true; } void resetErrors() { currentErrors = null; } void resetOutput(List<RTObject> objs) { getOutputStream().clear(); if (objs != null) getOutputStream().addAll(objs); outputStreamDirty(); } void resetOutput() { resetOutput(null); } // Don't make public since the method need to be wrapped in Story for visit // counting void setChosenPath(Path path, boolean incrementingTurnIndex) throws Exception { // Changing direction, assume we need to clear current set of choices currentFlow.currentChoices.clear(); final Pointer newPointer = new Pointer(story.pointerAtPath(path)); if (!newPointer.isNull() && newPointer.index == -1) newPointer.index = 0; setCurrentPointer(newPointer); if (incrementingTurnIndex) currentTurnIndex++; } void startFunctionEvaluationFromGame(Container funcContainer, Object[] arguments) throws Exception { getCallStack().push(PushPopType.FunctionEvaluationFromGame, evaluationStack.size()); getCallStack().getCurrentElement().currentPointer.assign(Pointer.startOf(funcContainer)); passArgumentsToEvaluationStack(arguments); } void passArgumentsToEvaluationStack(Object[] arguments) throws Exception { // Pass arguments onto the evaluation stack if (arguments != null) { for (int i = 0; i < arguments.length; i++) { if (!(arguments[i] instanceof Integer || arguments[i] instanceof Float || arguments[i] instanceof String)) { throw new Exception( "ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must be int, float or string. Argument was " + (arguments[i] == null ? "null" : arguments[i].getClass().getName())); } pushEvaluationStack(Value.create(arguments[i])); } } } boolean tryExitFunctionEvaluationFromGame() { if (getCallStack().getCurrentElement().type == PushPopType.FunctionEvaluationFromGame) { setCurrentPointer(Pointer.Null); didSafeExit = true; return true; } return false; } Object completeFunctionEvaluationFromGame() throws StoryException, Exception { if (getCallStack().getCurrentElement().type != PushPopType.FunctionEvaluationFromGame) { throw new StoryException("Expected external function evaluation to be complete. Stack trace: " + getCallStack().getCallStackTrace()); } int originalEvaluationStackHeight = getCallStack().getCurrentElement().evaluationStackHeightWhenPushed; // Do we have a returned value? // Potentially pop multiple values off the stack, in case we need // to clean up after ourselves (e.g. caller of EvaluateFunction may // have passed too many arguments, and we currently have no way to check // for that) RTObject returnedObj = null; while (evaluationStack.size() > originalEvaluationStackHeight) { RTObject poppedObj = popEvaluationStack(); if (returnedObj == null) returnedObj = poppedObj; } // Finally, pop the external function evaluation getCallStack().pop(PushPopType.FunctionEvaluationFromGame); // What did we get back? if (returnedObj != null) { if (returnedObj instanceof Void) return null; // Some kind of value, if not void Value<?> returnVal = null; if (returnedObj instanceof Value) returnVal = (Value<?>) returnedObj; // DivertTargets get returned as the string of components // (rather than a Path, which isn't public) if (returnVal.getValueType() == ValueType.DivertTarget) { return returnVal.getValueObject().toString(); } // Other types can just have their exact object type: // int, float, string. VariablePointers get returned as strings. return returnVal.getValueObject(); } return null; } void setCurrentPointer(Pointer value) { getCallStack().getCurrentElement().currentPointer.assign(value); } void setInExpressionEvaluation(boolean value) { getCallStack().getCurrentElement().inExpressionEvaluation = value; } void setPreviousPointer(Pointer value) { getCallStack().getcurrentThread().previousPointer.assign(value); } /** * Exports the current state to json format, in order to save the game. * * @return The save state in json format. */ public String toJson() throws Exception { SimpleJson.Writer writer = new SimpleJson.Writer(); writeJson(writer); return writer.toString(); } /** * Exports the current state to json format, in order to save the game. For this * overload you can pass in a custom stream, such as a FileStream. * * @throws Exception */ public void toJson(OutputStream stream) throws Exception { SimpleJson.Writer writer = new SimpleJson.Writer(stream); writeJson(writer); } void trimNewlinesFromOutputStream() { int removeWhitespaceFrom = -1; // Work back from the end, and try to find the point where // we need to start removing content. // - Simply work backwards to find the first newline in a String of // whitespace // e.g. This is the content \n \n\n // ^---------^ whitespace to remove // ^--- first while loop stops here int i = getOutputStream().size() - 1; while (i >= 0) { RTObject obj = getOutputStream().get(i); ControlCommand cmd = obj instanceof ControlCommand ? (ControlCommand) obj : null; StringValue txt = obj instanceof StringValue ? (StringValue) obj : null; if (cmd != null || (txt != null && txt.isNonWhitespace())) { break; } else if (txt != null && txt.isNewline()) { removeWhitespaceFrom = i; } i--; } // Remove the whitespace if (removeWhitespaceFrom >= 0) { i = removeWhitespaceFrom; while (i < getOutputStream().size()) { StringValue text = getOutputStream().get(i) instanceof StringValue ? (StringValue) getOutputStream().get(i) : null; if (text != null) { getOutputStream().remove(i); } else { i++; } } } outputStreamDirty(); } // At both the start and the end of the String, split out the new lines like // so: // // " \n \n \n the String \n is awesome \n \n " // ^-----------^ ^-------^ // // Excess newlines are converted into single newlines, and spaces discarded. // Outside spaces are significant and retained. "Interior" newlines within // the main String are ignored, since this is for the purpose of gluing // only. // // - If no splitting is necessary, null is returned. // - A newline on its own is returned in an list for consistency. List<StringValue> trySplittingHeadTailWhitespace(StringValue single) { String str = single.value; int headFirstNewlineIdx = -1; int headLastNewlineIdx = -1; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c == '\n') { if (headFirstNewlineIdx == -1) headFirstNewlineIdx = i; headLastNewlineIdx = i; } else if (c == ' ' || c == '\t') continue; else break; } int tailLastNewlineIdx = -1; int tailFirstNewlineIdx = -1; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c == '\n') { if (tailLastNewlineIdx == -1) tailLastNewlineIdx = i; tailFirstNewlineIdx = i; } else if (c == ' ' || c == '\t') continue; else break; } // No splitting to be done? if (headFirstNewlineIdx == -1 && tailLastNewlineIdx == -1) return null; List<StringValue> listTexts = new ArrayList<>(); int innerStrStart = 0; int innerStrEnd = str.length(); if (headFirstNewlineIdx != -1) { if (headFirstNewlineIdx > 0) { StringValue leadingSpaces = new StringValue(str.substring(0, headFirstNewlineIdx)); listTexts.add(leadingSpaces); } listTexts.add(new StringValue("\n")); innerStrStart = headLastNewlineIdx + 1; } if (tailLastNewlineIdx != -1) { innerStrEnd = tailFirstNewlineIdx; } if (innerStrEnd > innerStrStart) { String innerStrText = str.substring(innerStrStart, innerStrEnd); listTexts.add(new StringValue(innerStrText)); } if (tailLastNewlineIdx != -1 && tailFirstNewlineIdx > headLastNewlineIdx) { listTexts.add(new StringValue("\n")); if (tailLastNewlineIdx < str.length() - 1) { int numSpaces = (str.length() - tailLastNewlineIdx) - 1; StringValue trailingSpaces = new StringValue( str.substring(tailLastNewlineIdx + 1, numSpaces + tailLastNewlineIdx + 1)); listTexts.add(trailingSpaces); } } return listTexts; } /** * Gets the visit/read count of a particular Container at the given path. For a * knot or stitch, that path String will be in the form: * * knot knot.stitch * * @return The number of times the specific knot or stitch has been enountered * by the ink engine. * * @param pathString The dot-separated path String of the specific knot or * stitch. * @throws Exception * */ public int visitCountAtPathString(String pathString) throws Exception { Integer visitCountOut; if (patch != null) { Container container = story.contentAtPath(new Path(pathString)).getContainer(); if (container == null) throw new Exception("Content at path not found: " + pathString); visitCountOut = patch.getVisitCount(container); if (visitCountOut != null) return visitCountOut; } visitCountOut = visitCounts.get(pathString); if (visitCountOut != null) return visitCountOut; return 0; } int visitCountForContainer(Container container) throws Exception { if (!container.getVisitsShouldBeCounted()) { story.error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown."); return 0; } if (patch != null && patch.getVisitCount(container) != null) return patch.getVisitCount(container); String containerPathStr = container.getPath().toString(); if (visitCounts.containsKey(containerPathStr)) return visitCounts.get(containerPathStr); return 0; } void incrementVisitCountForContainer(Container container) throws Exception { if (patch != null) { int currCount = visitCountForContainer(container); currCount++; patch.setVisitCount(container, currCount); return; } Integer count = 0; String containerPathStr = container.getPath().toString(); if (visitCounts.containsKey(containerPathStr)) count = visitCounts.get(containerPathStr); count++; visitCounts.put(containerPathStr, count); } void recordTurnIndexVisitToContainer(Container container) { if (patch != null) { patch.setTurnIndex(container, currentTurnIndex); return; } String containerPathStr = container.getPath().toString(); turnIndices.put(containerPathStr, currentTurnIndex); } int turnsSinceForContainer(Container container) throws Exception { if (!container.getTurnIndexShouldBeCounted()) { story.error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown."); } int index = 0; if (patch != null && patch.getTurnIndex(container) != null) { index = patch.getTurnIndex(container); return currentTurnIndex - index; } String containerPathStr = container.getPath().toString(); if (turnIndices.containsKey(containerPathStr)) { index = turnIndices.get(containerPathStr); return currentTurnIndex - index; } else { return -1; } } public Pointer getDivertedPointer() { return divertedPointer; } public void setDivertedPointer(Pointer p) { divertedPointer.assign(p); } public boolean isDidSafeExit() { return didSafeExit; } public void setDidSafeExit(boolean didSafeExit) { this.didSafeExit = didSafeExit; } void restoreAfterPatch() { // VariablesState was being borrowed by the patched // state, so restore it with our own callstack. // _patch will be null normally, but if you're in the // middle of a save, it may contain a _patch for save purpsoes. variablesState.setCallStack(getCallStack()); variablesState.setPatch(patch); // usually null } void applyAnyPatch() { if (patch == null) return; variablesState.applyPatch(); for (Entry<Container, Integer> pathToCount : patch.getVisitCounts().entrySet()) applyCountChanges(pathToCount.getKey(), pathToCount.getValue(), true); for (Entry<Container, Integer> pathToIndex : patch.getTurnIndices().entrySet()) applyCountChanges(pathToIndex.getKey(), pathToIndex.getValue(), false); patch = null; } void applyCountChanges(Container container, int newCount, boolean isVisit) { HashMap<String, Integer> counts = isVisit ? visitCounts : turnIndices; counts.put(container.getPath().toString(), newCount); } void writeJson(SimpleJson.Writer writer) throws Exception { writer.writeObjectStart(); // Flows writer.writePropertyStart("flows"); writer.writeObjectStart(); // Multi-flow if (namedFlows != null) { for (Entry<String, Flow> namedFlow : namedFlows.entrySet()) { final Flow flow = namedFlow.getValue(); writer.writeProperty(namedFlow.getKey(), new InnerWriter() { @Override public void write(Writer w) throws Exception { flow.writeJson(w); } }); } } // Single flow else { writer.writeProperty(currentFlow.name, new InnerWriter() { @Override public void write(Writer w) throws Exception { currentFlow.writeJson(w); } }); } writer.writeObjectEnd(); writer.writePropertyEnd(); // end of flows writer.writeProperty("currentFlowName", currentFlow.name); writer.writeProperty("variablesState", new InnerWriter() { @Override public void write(Writer w) throws Exception { variablesState.writeJson(w); } }); writer.writeProperty("evalStack", new InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeListRuntimeObjs(w, evaluationStack); } }); if (!divertedPointer.isNull()) writer.writeProperty("currentDivertTarget", divertedPointer.getPath().getComponentsString()); writer.writeProperty("visitCounts", new InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeIntDictionary(w, visitCounts); } }); writer.writeProperty("turnIndices", new InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeIntDictionary(w, turnIndices); } }); writer.writeProperty("turnIdx", currentTurnIndex); writer.writeProperty("storySeed", storySeed); writer.writeProperty("previousRandom", previousRandom); writer.writeProperty("inkSaveVersion", kInkSaveStateVersion); // Not using this right now, but could do in future. writer.writeProperty("inkFormatVersion", Story.inkVersionCurrent); writer.writeObjectEnd(); } @SuppressWarnings("unchecked") void loadJsonObj(HashMap<String, Object> jObject) throws Exception { Object jSaveVersion = jObject.get("inkSaveVersion"); if (jSaveVersion == null) { throw new StoryException("ink save format incorrect, can't load."); } else if ((int) jSaveVersion < kMinCompatibleLoadVersion) { throw new StoryException("Ink save format isn't compatible with the current version (saw '" + jSaveVersion + "', but minimum is " + kMinCompatibleLoadVersion + "), so can't load."); } // Flows: Always exists in latest format (even if there's just one default) // but this dictionary doesn't exist in prev format Object flowsObj = jObject.get("flows"); if (flowsObj != null) { HashMap<String, Object> flowsObjDict = (HashMap<String, Object>) flowsObj; // Single default flow if (flowsObjDict.size() == 1) namedFlows = null; // Multi-flow, need to create flows dict else if (namedFlows == null) namedFlows = new HashMap<>(); // Multi-flow, already have a flows dict else namedFlows.clear(); // Load up each flow (there may only be one) for (Entry<String, Object> namedFlowObj : flowsObjDict.entrySet()) { String name = namedFlowObj.getKey(); HashMap<String, Object> flowObj = (HashMap<String, Object>) namedFlowObj.getValue(); // Load up this flow using JSON data Flow flow = new Flow(name, story, flowObj); if (flowsObjDict.size() == 1) { currentFlow = new Flow(name, story, flowObj); } else { namedFlows.put(name, flow); } } if (namedFlows != null && namedFlows.size() > 1) { String currFlowName = (String) jObject.get("currentFlowName"); currentFlow = namedFlows.get(currFlowName); } } // Old format: individually load up callstack, output stream, choices in // current/default flow else { namedFlows = null; currentFlow.name = kDefaultFlowName; currentFlow.callStack.setJsonToken((HashMap<String, Object>) jObject.get("callstackThreads"), story); currentFlow.outputStream = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("outputStream")); currentFlow.currentChoices = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("currentChoices")); Object jChoiceThreadsObj = jObject.get("choiceThreads"); currentFlow.loadFlowChoiceThreads((HashMap<String, Object>) jChoiceThreadsObj, story); } outputStreamDirty(); variablesState.setJsonToken((HashMap<String, Object>) jObject.get("variablesState")); variablesState.setCallStack(currentFlow.callStack); evaluationStack = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("evalStack")); Object currentDivertTargetPath = jObject.get("currentDivertTarget"); if (currentDivertTargetPath != null) { Path divertPath = new Path(currentDivertTargetPath.toString()); divertedPointer.assign(story.pointerAtPath(divertPath)); } visitCounts = Json.jObjectToIntHashMap((HashMap<String, Object>) jObject.get("visitCounts")); turnIndices = Json.jObjectToIntHashMap((HashMap<String, Object>) jObject.get("turnIndices")); currentTurnIndex = (int) jObject.get("turnIdx"); storySeed = (int) jObject.get("storySeed"); // Not optional, but bug in inkjs means it's actually missing in inkjs saves Object previousRandomObj = jObject.get("previousRandom"); if (previousRandomObj != null) { previousRandom = (int) previousRandomObj; } else { previousRandom = 0; } } }
src/main/java/com/bladecoder/ink/runtime/StoryState.java
package com.bladecoder.ink.runtime; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import com.bladecoder.ink.runtime.CallStack.Element; import com.bladecoder.ink.runtime.SimpleJson.InnerWriter; import com.bladecoder.ink.runtime.SimpleJson.Writer; /** * All story state information is included in the StoryState class, including * global variables, read counts, the pointer to the current point in the story, * the call stack (for tunnels, functions, etc), and a few other smaller bits * and pieces. You can save the current state using the json serialisation * functions ToJson and LoadJson. */ public class StoryState { /** * The current version of the state save file JSON-based format. */ public static final int kInkSaveStateVersion = 9; public static final int kMinCompatibleLoadVersion = 8; public static final String kDefaultFlowName = "DEFAULT_FLOW"; // REMEMBER! REMEMBER! REMEMBER! // When adding state, update the Copy method and serialisation // REMEMBER! REMEMBER! REMEMBER! private List<String> currentErrors; private List<String> currentWarnings; private int currentTurnIndex; private boolean didSafeExit; private final Pointer divertedPointer = new Pointer(); private List<RTObject> evaluationStack; private Story story; private int storySeed; private int previousRandom; private HashMap<String, Integer> turnIndices; private VariablesState variablesState; private HashMap<String, Integer> visitCounts; private String currentText; private boolean outputStreamTextDirty = true; private boolean outputStreamTagsDirty = true; private List<String> currentTags; private StatePatch patch; private HashMap<String, Flow> namedFlows; private Flow currentFlow; StoryState(Story story) { this.story = story; currentFlow = new Flow(kDefaultFlowName, story); outputStreamDirty(); evaluationStack = new ArrayList<>(); variablesState = new VariablesState(getCallStack(), story.getListDefinitions()); visitCounts = new HashMap<>(); turnIndices = new HashMap<>(); currentTurnIndex = -1; // Seed the shuffle random numbers long timeSeed = System.currentTimeMillis(); storySeed = new Random(timeSeed).nextInt() % 100; previousRandom = 0; goToStart(); } int getCallStackDepth() { return getCallStack().getDepth(); } void addError(String message, boolean isWarning) { if (!isWarning) { if (currentErrors == null) currentErrors = new ArrayList<>(); currentErrors.add(message); } else { if (currentWarnings == null) currentWarnings = new ArrayList<>(); currentWarnings.add(message); } } // Warning: Any RTObject content referenced within the StoryState will // be re-referenced rather than cloned. This is generally okay though since // RTObjects are treated as immutable after they've been set up. // (e.g. we don't edit a Runtime.StringValue after it's been created an added.) // I wonder if there's a sensible way to enforce that..?? StoryState copyAndStartPatching() { StoryState copy = new StoryState(story); copy.patch = new StatePatch(patch); // Hijack the new default flow to become a copy of our current one // If the patch is applied, then this new flow will replace the old one in // _namedFlows copy.currentFlow.name = currentFlow.name; copy.currentFlow.callStack = new CallStack(currentFlow.callStack); copy.currentFlow.currentChoices.addAll(currentFlow.currentChoices); copy.currentFlow.outputStream.addAll(currentFlow.outputStream); copy.outputStreamDirty(); // The copy of the state has its own copy of the named flows dictionary, // except with the current flow replaced with the copy above // (Assuming we're in multi-flow mode at all. If we're not then // the above copy is simply the default flow copy and we're done) if (namedFlows != null) { copy.namedFlows = new HashMap<>(); for (Map.Entry<String, Flow> namedFlow : namedFlows.entrySet()) copy.namedFlows.put(namedFlow.getKey(), namedFlow.getValue()); copy.namedFlows.put(currentFlow.name, copy.currentFlow); } if (hasError()) { copy.currentErrors = new ArrayList<>(); copy.currentErrors.addAll(currentErrors); } if (hasWarning()) { copy.currentWarnings = new ArrayList<>(); copy.currentWarnings.addAll(currentWarnings); } // ref copy - exactly the same variables state! // we're expecting not to read it only while in patch mode // (though the callstack will be modified) copy.variablesState = variablesState; copy.variablesState.setCallStack(copy.getCallStack()); copy.variablesState.setPatch(copy.patch); copy.evaluationStack.addAll(evaluationStack); if (!divertedPointer.isNull()) copy.divertedPointer.assign(divertedPointer); copy.setPreviousPointer(getPreviousPointer()); // visit counts and turn indicies will be read only, not modified // while in patch mode copy.visitCounts = visitCounts; copy.turnIndices = turnIndices; copy.currentTurnIndex = currentTurnIndex; copy.storySeed = storySeed; copy.previousRandom = previousRandom; copy.setDidSafeExit(didSafeExit); return copy; } void popFromOutputStream(int count) { getOutputStream().subList(getOutputStream().size() - count, getOutputStream().size()).clear(); outputStreamDirty(); } String getCurrentText() { if (outputStreamTextDirty) { StringBuilder sb = new StringBuilder(); for (RTObject outputObj : getOutputStream()) { StringValue textContent = null; if (outputObj instanceof StringValue) textContent = (StringValue) outputObj; if (textContent != null) { sb.append(textContent.value); } } currentText = cleanOutputWhitespace(sb.toString()); outputStreamTextDirty = false; } return currentText; } /** * Cleans inline whitespace in the following way: - Removes all whitespace from * the start and end of line (including just before a \n) - Turns all * consecutive space and tab runs into single spaces (HTML style) */ String cleanOutputWhitespace(String str) { StringBuilder sb = new StringBuilder(str.length()); int currentWhitespaceStart = -1; int startOfLine = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); boolean isInlineWhitespace = c == ' ' || c == '\t'; if (isInlineWhitespace && currentWhitespaceStart == -1) currentWhitespaceStart = i; if (!isInlineWhitespace) { if (c != '\n' && currentWhitespaceStart > 0 && currentWhitespaceStart != startOfLine) { sb.append(' '); } currentWhitespaceStart = -1; } if (c == '\n') startOfLine = i + 1; if (!isInlineWhitespace) sb.append(c); } return sb.toString(); } /** * Ends the current ink flow, unwrapping the callstack but without affecting any * variables. Useful if the ink is (say) in the middle a nested tunnel, and you * want it to reset so that you can divert elsewhere using ChoosePathString(). * Otherwise, after finishing the content you diverted to, it would continue * where it left off. Calling this is equivalent to calling -&gt; END in ink. */ public void forceEnd() throws Exception { getCallStack().reset(); currentFlow.currentChoices.clear(); setCurrentPointer(Pointer.Null); setPreviousPointer(Pointer.Null); setDidSafeExit(true); } // Add the end of a function call, trim any whitespace from the end. // We always trim the start and end of the text that a function produces. // The start whitespace is discard as it is generated, and the end // whitespace is trimmed in one go here when we pop the function. void trimWhitespaceFromFunctionEnd() { assert (getCallStack().getCurrentElement().type == PushPopType.Function); int functionStartPoint = getCallStack().getCurrentElement().functionStartInOuputStream; // If the start point has become -1, it means that some non-whitespace // text has been pushed, so it's safe to go as far back as we're able. if (functionStartPoint == -1) { functionStartPoint = 0; } // Trim whitespace from END of function call for (int i = getOutputStream().size() - 1; i >= functionStartPoint; i--) { RTObject obj = getOutputStream().get(i); if (!(obj instanceof StringValue)) continue; StringValue txt = (StringValue) obj; if (obj instanceof ControlCommand) break; if (txt.isNewline() || txt.isInlineWhitespace()) { getOutputStream().remove(i); outputStreamDirty(); } else { break; } } } void popCallstack() throws Exception { popCallstack(null); } void popCallstack(PushPopType popType) throws Exception { // Add the end of a function call, trim any whitespace from the end. if (getCallStack().getCurrentElement().type == PushPopType.Function) trimWhitespaceFromFunctionEnd(); getCallStack().pop(popType); } Pointer getCurrentPointer() { return getCallStack().getCurrentElement().currentPointer; } List<String> getCurrentTags() { if (outputStreamTagsDirty) { currentTags = new ArrayList<>(); for (RTObject outputObj : getOutputStream()) { Tag tag = null; if (outputObj instanceof Tag) tag = (Tag) outputObj; if (tag != null) { currentTags.add(tag.getText()); } } outputStreamTagsDirty = false; } return currentTags; } public String getCurrentFlowName() { return currentFlow.name; } boolean getInExpressionEvaluation() { return getCallStack().getCurrentElement().inExpressionEvaluation; } Pointer getPreviousPointer() { return getCallStack().getcurrentThread().previousPointer; } void goToStart() { getCallStack().getCurrentElement().currentPointer.assign(Pointer.startOf(story.getMainContentContainer())); } void switchFlowInternal(String flowName) throws Exception { if (flowName == null) throw new Exception("Must pass a non-null string to Story.SwitchFlow"); if (namedFlows == null) { namedFlows = new HashMap<>(); namedFlows.put(kDefaultFlowName, currentFlow); } if (flowName.equals(currentFlow.name)) { return; } Flow flow = namedFlows.get(flowName); if (flow == null) { flow = new Flow(flowName, story); namedFlows.put(flowName, flow); } currentFlow = flow; variablesState.setCallStack(currentFlow.callStack); // Cause text to be regenerated from output stream if necessary outputStreamDirty(); } void switchToDefaultFlowInternal() throws Exception { if (namedFlows == null) return; switchFlowInternal(kDefaultFlowName); } void removeFlowInternal(String flowName) throws Exception { if (flowName == null) throw new Exception("Must pass a non-null string to Story.DestroyFlow"); if (flowName.equals(kDefaultFlowName)) throw new Exception("Cannot destroy default flow"); // If we're currently in the flow that's being removed, switch back to default if (currentFlow.name.equals(flowName)) { switchToDefaultFlowInternal(); } namedFlows.remove(flowName); } boolean hasError() { return currentErrors != null && currentErrors.size() > 0; } boolean inStringEvaluation() { for (int i = getOutputStream().size() - 1; i >= 0; i--) { ControlCommand cmd = getOutputStream().get(i) instanceof ControlCommand ? (ControlCommand) getOutputStream().get(i) : null; if (cmd != null && cmd.getCommandType() == ControlCommand.CommandType.BeginString) { return true; } } return false; } /** * Loads a previously saved state in JSON format. * * @param json The JSON String to load. */ public void loadJson(String json) throws Exception { HashMap<String, Object> jObject = SimpleJson.textToDictionary(json); loadJsonObj(jObject); } List<Choice> getCurrentChoices() { // If we can continue generating text content rather than choices, // then we reflect the choice list as being empty, since choices // should always come at the end. if (canContinue()) return new ArrayList<>(); return currentFlow.currentChoices; } List<Choice> getGeneratedChoices() { return currentFlow.currentChoices; } boolean canContinue() { return !getCurrentPointer().isNull() && !hasError(); } List<String> getCurrentErrors() { return currentErrors; } List<String> getCurrentWarnings() { return currentWarnings; } boolean hasWarning() { return currentWarnings != null && currentWarnings.size() > 0; } List<RTObject> getOutputStream() { return currentFlow.outputStream; } CallStack getCallStack() { return currentFlow.callStack; } VariablesState getVariablesState() { return variablesState; } List<RTObject> getEvaluationStack() { return evaluationStack; } int getStorySeed() { return storySeed; } void setStorySeed(int s) { storySeed = s; } int getPreviousRandom() { return previousRandom; } void setPreviousRandom(int i) { previousRandom = i; } int getCurrentTurnIndex() { return currentTurnIndex; } boolean outputStreamContainsContent() { for (RTObject content : getOutputStream()) { if (content instanceof StringValue) return true; } return false; } boolean outputStreamEndsInNewline() { if (getOutputStream().size() > 0) { for (int i = getOutputStream().size() - 1; i >= 0; i--) { RTObject obj = getOutputStream().get(i); if (obj instanceof ControlCommand) // e.g. BeginString break; StringValue text = getOutputStream().get(i) instanceof StringValue ? (StringValue) getOutputStream().get(i) : null; if (text != null) { if (text.isNewline()) return true; else if (text.isNonWhitespace()) break; } } } return false; } RTObject peekEvaluationStack() { return evaluationStack.get(evaluationStack.size() - 1); } RTObject popEvaluationStack() { RTObject obj = evaluationStack.get(evaluationStack.size() - 1); evaluationStack.remove(evaluationStack.size() - 1); return obj; } List<RTObject> popEvaluationStack(int numberOfObjects) throws Exception { if (numberOfObjects > evaluationStack.size()) { throw new Exception("trying to pop too many objects"); } List<RTObject> popped = new ArrayList<>( evaluationStack.subList(evaluationStack.size() - numberOfObjects, evaluationStack.size())); evaluationStack.subList(evaluationStack.size() - numberOfObjects, evaluationStack.size()).clear(); return popped; } void pushEvaluationStack(RTObject obj) { // Include metadata about the origin List for set values when // they're used, so that lower level functions can make use // of the origin list to get related items, or make comparisons // with the integer values etc. ListValue listValue = null; if (obj instanceof ListValue) listValue = (ListValue) obj; if (listValue != null) { // Update origin when list is has something to indicate the list // origin InkList rawList = listValue.getValue(); if (rawList.getOriginNames() != null) { if (rawList.getOrigins() == null) rawList.setOrigins(new ArrayList<ListDefinition>()); rawList.getOrigins().clear(); for (String n : rawList.getOriginNames()) { ListDefinition def = story.getListDefinitions().getListDefinition(n); if (!rawList.getOrigins().contains(def)) rawList.getOrigins().add(def); } } } evaluationStack.add(obj); } // Push to output stream, but split out newlines in text for consistency // in dealing with them later. void pushToOutputStream(RTObject obj) { StringValue text = obj instanceof StringValue ? (StringValue) obj : null; if (text != null) { List<StringValue> listText = trySplittingHeadTailWhitespace(text); if (listText != null) { for (StringValue textObj : listText) { pushToOutputStreamIndividual(textObj); } outputStreamDirty(); return; } } pushToOutputStreamIndividual(obj); } void pushToOutputStreamIndividual(RTObject obj) { Glue glue = obj instanceof Glue ? (Glue) obj : null; StringValue text = obj instanceof StringValue ? (StringValue) obj : null; boolean includeInOutput = true; // New glue, so chomp away any whitespace from the end of the stream if (glue != null) { trimNewlinesFromOutputStream(); includeInOutput = true; } // New text: do we really want to append it, if it's whitespace? // Two different reasons for whitespace to be thrown away: // - Function start/end trimming // - User defined glue: <> // We also need to know when to stop trimming, when there's non-whitespace. else if (text != null) { // Where does the current function call begin? int functionTrimIndex = -1; Element currEl = getCallStack().getCurrentElement(); if (currEl.type == PushPopType.Function) { functionTrimIndex = currEl.functionStartInOuputStream; } // Do 2 things: // - Find latest glue // - Check whether we're in the middle of string evaluation // If we're in string eval within the current function, we // don't want to trim back further than the length of the current string. int glueTrimIndex = -1; for (int i = getOutputStream().size() - 1; i >= 0; i--) { RTObject o = getOutputStream().get(i); ControlCommand c = o instanceof ControlCommand ? (ControlCommand) o : null; Glue g = o instanceof Glue ? (Glue) o : null; // Find latest glue if (g != null) { glueTrimIndex = i; break; } // Don't function-trim past the start of a string evaluation section else if (c != null && c.getCommandType() == ControlCommand.CommandType.BeginString) { if (i >= functionTrimIndex) { functionTrimIndex = -1; } break; } } // Where is the most agressive (earliest) trim point? int trimIndex = -1; if (glueTrimIndex != -1 && functionTrimIndex != -1) trimIndex = Math.min(functionTrimIndex, glueTrimIndex); else if (glueTrimIndex != -1) trimIndex = glueTrimIndex; else trimIndex = functionTrimIndex; // So, are we trimming then? if (trimIndex != -1) { // While trimming, we want to throw all newlines away, // whether due to glue or the start of a function if (text.isNewline()) { includeInOutput = false; } // Able to completely reset when normal text is pushed else if (text.isNonWhitespace()) { if (glueTrimIndex > -1) removeExistingGlue(); // Tell all functions in callstack that we have seen proper text, // so trimming whitespace at the start is done. if (functionTrimIndex > -1) { List<Element> callstackElements = getCallStack().getElements(); for (int i = callstackElements.size() - 1; i >= 0; i--) { Element el = callstackElements.get(i); if (el.type == PushPopType.Function) { el.functionStartInOuputStream = -1; } else { break; } } } } } // De-duplicate newlines, and don't ever lead with a newline else if (text.isNewline()) { if (outputStreamEndsInNewline() || !outputStreamContainsContent()) includeInOutput = false; } } if (includeInOutput) { getOutputStream().add(obj); outputStreamDirty(); } } // Only called when non-whitespace is appended void removeExistingGlue() { for (int i = getOutputStream().size() - 1; i >= 0; i--) { RTObject c = getOutputStream().get(i); if (c instanceof Glue) { getOutputStream().remove(i); } else if (c instanceof ControlCommand) { // e.g. // BeginString break; } } outputStreamDirty(); } void outputStreamDirty() { outputStreamTextDirty = true; outputStreamTagsDirty = true; } void resetErrors() { currentErrors = null; } void resetOutput(List<RTObject> objs) { getOutputStream().clear(); if (objs != null) getOutputStream().addAll(objs); outputStreamDirty(); } void resetOutput() { resetOutput(null); } // Don't make public since the method need to be wrapped in Story for visit // counting void setChosenPath(Path path, boolean incrementingTurnIndex) throws Exception { // Changing direction, assume we need to clear current set of choices currentFlow.currentChoices.clear(); final Pointer newPointer = new Pointer(story.pointerAtPath(path)); if (!newPointer.isNull() && newPointer.index == -1) newPointer.index = 0; setCurrentPointer(newPointer); if (incrementingTurnIndex) currentTurnIndex++; } void startFunctionEvaluationFromGame(Container funcContainer, Object[] arguments) throws Exception { getCallStack().push(PushPopType.FunctionEvaluationFromGame, evaluationStack.size()); getCallStack().getCurrentElement().currentPointer.assign(Pointer.startOf(funcContainer)); passArgumentsToEvaluationStack(arguments); } void passArgumentsToEvaluationStack(Object[] arguments) throws Exception { // Pass arguments onto the evaluation stack if (arguments != null) { for (int i = 0; i < arguments.length; i++) { if (!(arguments[i] instanceof Integer || arguments[i] instanceof Float || arguments[i] instanceof String)) { throw new Exception( "ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must be int, float or string"); } pushEvaluationStack(Value.create(arguments[i])); } } } boolean tryExitFunctionEvaluationFromGame() { if (getCallStack().getCurrentElement().type == PushPopType.FunctionEvaluationFromGame) { setCurrentPointer(Pointer.Null); didSafeExit = true; return true; } return false; } Object completeFunctionEvaluationFromGame() throws StoryException, Exception { if (getCallStack().getCurrentElement().type != PushPopType.FunctionEvaluationFromGame) { throw new StoryException("Expected external function evaluation to be complete. Stack trace: " + getCallStack().getCallStackTrace()); } int originalEvaluationStackHeight = getCallStack().getCurrentElement().evaluationStackHeightWhenPushed; // Do we have a returned value? // Potentially pop multiple values off the stack, in case we need // to clean up after ourselves (e.g. caller of EvaluateFunction may // have passed too many arguments, and we currently have no way to check // for that) RTObject returnedObj = null; while (evaluationStack.size() > originalEvaluationStackHeight) { RTObject poppedObj = popEvaluationStack(); if (returnedObj == null) returnedObj = poppedObj; } // Finally, pop the external function evaluation getCallStack().pop(PushPopType.FunctionEvaluationFromGame); // What did we get back? if (returnedObj != null) { if (returnedObj instanceof Void) return null; // Some kind of value, if not void Value<?> returnVal = null; if (returnedObj instanceof Value) returnVal = (Value<?>) returnedObj; // DivertTargets get returned as the string of components // (rather than a Path, which isn't public) if (returnVal.getValueType() == ValueType.DivertTarget) { return returnVal.getValueObject().toString(); } // Other types can just have their exact object type: // int, float, string. VariablePointers get returned as strings. return returnVal.getValueObject(); } return null; } void setCurrentPointer(Pointer value) { getCallStack().getCurrentElement().currentPointer.assign(value); } void setInExpressionEvaluation(boolean value) { getCallStack().getCurrentElement().inExpressionEvaluation = value; } void setPreviousPointer(Pointer value) { getCallStack().getcurrentThread().previousPointer.assign(value); } /** * Exports the current state to json format, in order to save the game. * * @return The save state in json format. */ public String toJson() throws Exception { SimpleJson.Writer writer = new SimpleJson.Writer(); writeJson(writer); return writer.toString(); } /** * Exports the current state to json format, in order to save the game. For this * overload you can pass in a custom stream, such as a FileStream. * * @throws Exception */ public void toJson(OutputStream stream) throws Exception { SimpleJson.Writer writer = new SimpleJson.Writer(stream); writeJson(writer); } void trimNewlinesFromOutputStream() { int removeWhitespaceFrom = -1; // Work back from the end, and try to find the point where // we need to start removing content. // - Simply work backwards to find the first newline in a String of // whitespace // e.g. This is the content \n \n\n // ^---------^ whitespace to remove // ^--- first while loop stops here int i = getOutputStream().size() - 1; while (i >= 0) { RTObject obj = getOutputStream().get(i); ControlCommand cmd = obj instanceof ControlCommand ? (ControlCommand) obj : null; StringValue txt = obj instanceof StringValue ? (StringValue) obj : null; if (cmd != null || (txt != null && txt.isNonWhitespace())) { break; } else if (txt != null && txt.isNewline()) { removeWhitespaceFrom = i; } i--; } // Remove the whitespace if (removeWhitespaceFrom >= 0) { i = removeWhitespaceFrom; while (i < getOutputStream().size()) { StringValue text = getOutputStream().get(i) instanceof StringValue ? (StringValue) getOutputStream().get(i) : null; if (text != null) { getOutputStream().remove(i); } else { i++; } } } outputStreamDirty(); } // At both the start and the end of the String, split out the new lines like // so: // // " \n \n \n the String \n is awesome \n \n " // ^-----------^ ^-------^ // // Excess newlines are converted into single newlines, and spaces discarded. // Outside spaces are significant and retained. "Interior" newlines within // the main String are ignored, since this is for the purpose of gluing // only. // // - If no splitting is necessary, null is returned. // - A newline on its own is returned in an list for consistency. List<StringValue> trySplittingHeadTailWhitespace(StringValue single) { String str = single.value; int headFirstNewlineIdx = -1; int headLastNewlineIdx = -1; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c == '\n') { if (headFirstNewlineIdx == -1) headFirstNewlineIdx = i; headLastNewlineIdx = i; } else if (c == ' ' || c == '\t') continue; else break; } int tailLastNewlineIdx = -1; int tailFirstNewlineIdx = -1; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c == '\n') { if (tailLastNewlineIdx == -1) tailLastNewlineIdx = i; tailFirstNewlineIdx = i; } else if (c == ' ' || c == '\t') continue; else break; } // No splitting to be done? if (headFirstNewlineIdx == -1 && tailLastNewlineIdx == -1) return null; List<StringValue> listTexts = new ArrayList<>(); int innerStrStart = 0; int innerStrEnd = str.length(); if (headFirstNewlineIdx != -1) { if (headFirstNewlineIdx > 0) { StringValue leadingSpaces = new StringValue(str.substring(0, headFirstNewlineIdx)); listTexts.add(leadingSpaces); } listTexts.add(new StringValue("\n")); innerStrStart = headLastNewlineIdx + 1; } if (tailLastNewlineIdx != -1) { innerStrEnd = tailFirstNewlineIdx; } if (innerStrEnd > innerStrStart) { String innerStrText = str.substring(innerStrStart, innerStrEnd); listTexts.add(new StringValue(innerStrText)); } if (tailLastNewlineIdx != -1 && tailFirstNewlineIdx > headLastNewlineIdx) { listTexts.add(new StringValue("\n")); if (tailLastNewlineIdx < str.length() - 1) { int numSpaces = (str.length() - tailLastNewlineIdx) - 1; StringValue trailingSpaces = new StringValue( str.substring(tailLastNewlineIdx + 1, numSpaces + tailLastNewlineIdx + 1)); listTexts.add(trailingSpaces); } } return listTexts; } /** * Gets the visit/read count of a particular Container at the given path. For a * knot or stitch, that path String will be in the form: * * knot knot.stitch * * @return The number of times the specific knot or stitch has been enountered * by the ink engine. * * @param pathString The dot-separated path String of the specific knot or * stitch. * @throws Exception * */ public int visitCountAtPathString(String pathString) throws Exception { Integer visitCountOut; if (patch != null) { Container container = story.contentAtPath(new Path(pathString)).getContainer(); if (container == null) throw new Exception("Content at path not found: " + pathString); visitCountOut = patch.getVisitCount(container); if (visitCountOut != null) return visitCountOut; } visitCountOut = visitCounts.get(pathString); if (visitCountOut != null) return visitCountOut; return 0; } int visitCountForContainer(Container container) throws Exception { if (!container.getVisitsShouldBeCounted()) { story.error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown."); return 0; } if (patch != null && patch.getVisitCount(container) != null) return patch.getVisitCount(container); String containerPathStr = container.getPath().toString(); if (visitCounts.containsKey(containerPathStr)) return visitCounts.get(containerPathStr); return 0; } void incrementVisitCountForContainer(Container container) throws Exception { if (patch != null) { int currCount = visitCountForContainer(container); currCount++; patch.setVisitCount(container, currCount); return; } Integer count = 0; String containerPathStr = container.getPath().toString(); if (visitCounts.containsKey(containerPathStr)) count = visitCounts.get(containerPathStr); count++; visitCounts.put(containerPathStr, count); } void recordTurnIndexVisitToContainer(Container container) { if (patch != null) { patch.setTurnIndex(container, currentTurnIndex); return; } String containerPathStr = container.getPath().toString(); turnIndices.put(containerPathStr, currentTurnIndex); } int turnsSinceForContainer(Container container) throws Exception { if (!container.getTurnIndexShouldBeCounted()) { story.error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown."); } int index = 0; if (patch != null && patch.getTurnIndex(container) != null) { index = patch.getTurnIndex(container); return currentTurnIndex - index; } String containerPathStr = container.getPath().toString(); if (turnIndices.containsKey(containerPathStr)) { index = turnIndices.get(containerPathStr); return currentTurnIndex - index; } else { return -1; } } public Pointer getDivertedPointer() { return divertedPointer; } public void setDivertedPointer(Pointer p) { divertedPointer.assign(p); } public boolean isDidSafeExit() { return didSafeExit; } public void setDidSafeExit(boolean didSafeExit) { this.didSafeExit = didSafeExit; } void restoreAfterPatch() { // VariablesState was being borrowed by the patched // state, so restore it with our own callstack. // _patch will be null normally, but if you're in the // middle of a save, it may contain a _patch for save purpsoes. variablesState.setCallStack(getCallStack()); variablesState.setPatch(patch); // usually null } void applyAnyPatch() { if (patch == null) return; variablesState.applyPatch(); for (Entry<Container, Integer> pathToCount : patch.getVisitCounts().entrySet()) applyCountChanges(pathToCount.getKey(), pathToCount.getValue(), true); for (Entry<Container, Integer> pathToIndex : patch.getTurnIndices().entrySet()) applyCountChanges(pathToIndex.getKey(), pathToIndex.getValue(), false); patch = null; } void applyCountChanges(Container container, int newCount, boolean isVisit) { HashMap<String, Integer> counts = isVisit ? visitCounts : turnIndices; counts.put(container.getPath().toString(), newCount); } void writeJson(SimpleJson.Writer writer) throws Exception { writer.writeObjectStart(); // Flows writer.writePropertyStart("flows"); writer.writeObjectStart(); // Multi-flow if (namedFlows != null) { for (Entry<String, Flow> namedFlow : namedFlows.entrySet()) { final Flow flow = namedFlow.getValue(); writer.writeProperty(namedFlow.getKey(), new InnerWriter() { @Override public void write(Writer w) throws Exception { flow.writeJson(w); } }); } } // Single flow else { writer.writeProperty(currentFlow.name, new InnerWriter() { @Override public void write(Writer w) throws Exception { currentFlow.writeJson(w); } }); } writer.writeObjectEnd(); writer.writePropertyEnd(); // end of flows writer.writeProperty("currentFlowName", currentFlow.name); writer.writeProperty("variablesState", new InnerWriter() { @Override public void write(Writer w) throws Exception { variablesState.writeJson(w); } }); writer.writeProperty("evalStack", new InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeListRuntimeObjs(w, evaluationStack); } }); if (!divertedPointer.isNull()) writer.writeProperty("currentDivertTarget", divertedPointer.getPath().getComponentsString()); writer.writeProperty("visitCounts", new InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeIntDictionary(w, visitCounts); } }); writer.writeProperty("turnIndices", new InnerWriter() { @Override public void write(Writer w) throws Exception { Json.writeIntDictionary(w, turnIndices); } }); writer.writeProperty("turnIdx", currentTurnIndex); writer.writeProperty("storySeed", storySeed); writer.writeProperty("previousRandom", previousRandom); writer.writeProperty("inkSaveVersion", kInkSaveStateVersion); // Not using this right now, but could do in future. writer.writeProperty("inkFormatVersion", Story.inkVersionCurrent); writer.writeObjectEnd(); } @SuppressWarnings("unchecked") void loadJsonObj(HashMap<String, Object> jObject) throws Exception { Object jSaveVersion = jObject.get("inkSaveVersion"); if (jSaveVersion == null) { throw new StoryException("ink save format incorrect, can't load."); } else if ((int) jSaveVersion < kMinCompatibleLoadVersion) { throw new StoryException("Ink save format isn't compatible with the current version (saw '" + jSaveVersion + "', but minimum is " + kMinCompatibleLoadVersion + "), so can't load."); } // Flows: Always exists in latest format (even if there's just one default) // but this dictionary doesn't exist in prev format Object flowsObj = jObject.get("flows"); if (flowsObj != null) { HashMap<String, Object> flowsObjDict = (HashMap<String, Object>) flowsObj; // Single default flow if (flowsObjDict.size() == 1) namedFlows = null; // Multi-flow, need to create flows dict else if (namedFlows == null) namedFlows = new HashMap<>(); // Multi-flow, already have a flows dict else namedFlows.clear(); // Load up each flow (there may only be one) for (Entry<String, Object> namedFlowObj : flowsObjDict.entrySet()) { String name = namedFlowObj.getKey(); HashMap<String, Object> flowObj = (HashMap<String, Object>) namedFlowObj.getValue(); // Load up this flow using JSON data Flow flow = new Flow(name, story, flowObj); if (flowsObjDict.size() == 1) { currentFlow = new Flow(name, story, flowObj); } else { namedFlows.put(name, flow); } } if (namedFlows != null && namedFlows.size() > 1) { String currFlowName = (String) jObject.get("currentFlowName"); currentFlow = namedFlows.get(currFlowName); } } // Old format: individually load up callstack, output stream, choices in // current/default flow else { namedFlows = null; currentFlow.name = kDefaultFlowName; currentFlow.callStack.setJsonToken((HashMap<String, Object>) jObject.get("callstackThreads"), story); currentFlow.outputStream = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("outputStream")); currentFlow.currentChoices = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("currentChoices")); Object jChoiceThreadsObj = jObject.get("choiceThreads"); currentFlow.loadFlowChoiceThreads((HashMap<String, Object>) jChoiceThreadsObj, story); } outputStreamDirty(); variablesState.setJsonToken((HashMap<String, Object>) jObject.get("variablesState")); variablesState.setCallStack(currentFlow.callStack); evaluationStack = Json.jArrayToRuntimeObjList((List<Object>) jObject.get("evalStack")); Object currentDivertTargetPath = jObject.get("currentDivertTarget"); if (currentDivertTargetPath != null) { Path divertPath = new Path(currentDivertTargetPath.toString()); divertedPointer.assign(story.pointerAtPath(divertPath)); } visitCounts = Json.jObjectToIntHashMap((HashMap<String, Object>) jObject.get("visitCounts")); turnIndices = Json.jObjectToIntHashMap((HashMap<String, Object>) jObject.get("turnIndices")); currentTurnIndex = (int) jObject.get("turnIdx"); storySeed = (int) jObject.get("storySeed"); // Not optional, but bug in inkjs means it's actually missing in inkjs saves Object previousRandomObj = jObject.get("previousRandom"); if (previousRandomObj != null) { previousRandom = (int) previousRandomObj; } else { previousRandom = 0; } } }
Improves the helpfulness of the wrong type error message by displaying the input type
src/main/java/com/bladecoder/ink/runtime/StoryState.java
Improves the helpfulness of the wrong type error message by displaying the input type
<ide><path>rc/main/java/com/bladecoder/ink/runtime/StoryState.java <ide> if (!(arguments[i] instanceof Integer || arguments[i] instanceof Float <ide> || arguments[i] instanceof String)) { <ide> throw new Exception( <del> "ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must be int, float or string"); <add> "ink arguments when calling EvaluateFunction / ChoosePathStringWithParameters must be int, float or string. Argument was " <add> + (arguments[i] == null ? "null" : arguments[i].getClass().getName())); <add> <ide> } <ide> <ide> pushEvaluationStack(Value.create(arguments[i]));
Java
agpl-3.0
7240f86550e2362dcf5b432beaf3fc9d057becd6
0
GTAUN/wl-race
/** * WL Race Plugin * Copyright (C) 2013 MK124 * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package net.gtaun.wl.race.dialog; import java.util.List; import net.gtaun.shoebill.common.dialog.AbstractDialog; import net.gtaun.shoebill.common.dialog.MsgboxDialog; import net.gtaun.shoebill.exception.AlreadyExistException; import net.gtaun.shoebill.object.Player; import net.gtaun.util.event.EventManager; import net.gtaun.wl.common.dialog.WlInputDialog; import net.gtaun.wl.common.dialog.WlListDialog; import net.gtaun.wl.common.dialog.WlMsgboxDialog; import net.gtaun.wl.lang.LocalizedStringSet.PlayerStringSet; import net.gtaun.wl.race.impl.RaceServiceImpl; import net.gtaun.wl.race.racing.Racing; import net.gtaun.wl.race.racing.RacingManagerImpl; import net.gtaun.wl.race.track.Track; import net.gtaun.wl.race.track.Track.TrackStatus; import net.gtaun.wl.race.track.TrackCheckpoint; import net.gtaun.wl.race.track.TrackManagerImpl; import net.gtaun.wl.race.util.RacingUtils; import org.apache.commons.lang3.StringUtils; public class TrackEditDialog extends WlListDialog { private final PlayerStringSet stringSet; private final RaceServiceImpl raceService; private final Track track; public TrackEditDialog(Player player, EventManager eventManager, AbstractDialog parent, RaceServiceImpl service, Track track) { super(player, eventManager); setParentDialog(parent); this.raceService = service; this.track = track; stringSet = service.getLocalizedStringSet().getStringSet(player); setCaption(() -> stringSet.format("Dialog.TrackEditDialog.Caption", track.getName())); setClickOkHandler((d, i) -> player.playSound(1083)); } @Override public void show() { RacingManagerImpl racingManager = raceService.getRacingManager(); items.clear(); addItem(stringSet.format("Dialog.TrackEditDialog.Name", track.getName()), (i) -> { String caption = stringSet.get("Dialog.TrackEditNameDialog.Caption"); String message = stringSet.format("Dialog.TrackEditNameDialog.Text", track.getName()); TrackNamingDialog.create(player, rootEventManager, this, caption, message, raceService, (d, name) -> { try { TrackManagerImpl trackManager = raceService.getTrackManager(); trackManager.renameTrack(track, name); showParentDialog(); } catch (AlreadyExistException ex) { d.setAppendMessage(stringSet.format("Dialog.TrackEditNameDialog.AlreadyExistAppendMessage", name)); show(); } catch (IllegalArgumentException ex) { d.setAppendMessage(stringSet.format("Dialog.TrackEditNameDialog.IllegalFormatAppendMessage", name)); show(); } }).show(); }); addItem(() -> { String desc = track.getDesc(); if (StringUtils.isBlank(desc)) desc = stringSet.get("Common.Empty"); return stringSet.format("Dialog.TrackEditDialog.Desc", desc); }, (i) -> { String caption = stringSet.get("Dialog.TrackEditDescDialog.Caption"); String message = stringSet.format("Dialog.TrackEditDescDialog.Text", track.getName(), track.getDesc()); WlInputDialog.create(player, rootEventManager) .parentDialog(this) .caption(caption) .message(message) .onClickOk((d, text) -> { String desc = StringUtils.trimToEmpty(text); desc = StringUtils.replace(desc, "%", "#"); desc = StringUtils.replace(desc, "\t", " "); desc = StringUtils.replace(desc, "\n", " "); track.setDesc(desc); d.showParentDialog(); }) .build().show(); }); addItem(() -> stringSet.format("Dialog.TrackEditDialog.Checkpoints", track.getCheckpoints().size()), (i) -> show()); addItem(() -> stringSet.format("Dialog.TrackEditDialog.Length", track.getLength()/1000.0f), (i) -> show()); addItem(() -> stringSet.get("Dialog.TrackEditDialog.AddCheckpoint"), (i) -> { TrackCheckpoint checkpoint = track.createCheckpoint(player.getLocation()); TrackCheckpointEditDialog.create(player, eventManagerNode, null, raceService, checkpoint, true).show(); }); addItem(() -> stringSet.get("Dialog.TrackEditDialog.Setting"), (i) -> { TrackSettingDialog.create(player, rootEventManager, this, raceService, track).show(); }); addItem(() -> stringSet.get("Dialog.TrackEditDialog.Delete"), (i) -> { String caption = stringSet.get("Dialog.TrackDeleteConfirmDialog.Caption"); String message = stringSet.format("Dialog.TrackDeleteConfirmDialog.Text", track.getName()); WlInputDialog.create(player, rootEventManager) .parentDialog(this) .caption(caption) .message(message) .onClickOk((d, text) -> { if (!track.getName().equals(text)) { d.showParentDialog(); return; } raceService.stopEditingTrack(player); TrackManagerImpl trackManager = raceService.getTrackManager(); trackManager.deleteTrack(track); String msgboxCaption = stringSet.get("Dialog.TrackDeleteCompleteDialog.Caption"); String msgboxMessage = stringSet.format("Dialog.TrackDeleteCompleteDialog.Text", track.getName()); WlMsgboxDialog.create(player, rootEventManager) .parentDialog(this) .caption(msgboxCaption) .message(msgboxMessage) .onClickOk((dialog) -> { player.playSound(1083); dialog.showParentDialog(); }) .build().show(); }) .build().show(); }); addItem(stringSet.get("Dialog.TrackEditDialog.StopEditing"), (i) -> { raceService.stopEditingTrack(player); }); addItem(stringSet.get("Dialog.TrackEditDialog.FinishEditing"), () -> { if (track.getCheckpoints().size() < 2) return false; return true; }, (i) -> { String caption = stringSet.get("Dialog.TrackFinishEditingConfirmDialog.Caption"); String message = stringSet.format("Dialog.TrackFinishEditingConfirmDialog.Text", track.getName()); MsgboxDialog.create(player, rootEventManager) .caption(caption) .message(message) .onClickOk((d) -> { player.playSound(1083); raceService.stopEditingTrack(player); track.setStatus(TrackStatus.COMPLETED); showParentDialog(); }) .build().show();; }); addItem(stringSet.get("Dialog.TrackEditDialog.Test"), () -> { if (track.getCheckpoints().isEmpty()) return false; return true; }, (i) -> { Runnable startNewRacing = () -> { Racing racing = racingManager.createRacing(track, player, RacingUtils.getDefaultName(player, track)); racing.teleToStartingPoint(player); racing.beginCountdown(); }; List<TrackCheckpoint> checkpoints = track.getCheckpoints(); if (checkpoints.isEmpty()) return; if (racingManager.isPlayerInRacing(player)) { Racing racing = racingManager.getPlayerRacing(player); NewRacingConfirmDialog.create(player, rootEventManager, this, raceService, racing, () -> { startNewRacing.run(); }).show(); } else startNewRacing.run(); }); addItem("-", (i) -> show()); List<TrackCheckpoint> checkpoints = track.getCheckpoints(); for (int i=0; i<checkpoints.size(); i++) { TrackCheckpoint checkpoint = checkpoints.get(i); float distance = player.getLocation().distance(checkpoint.getLocation()); String item = stringSet.format("Dialog.TrackEditDialog.Checkpoint", i+1, distance); addItem(item, (listItem) -> { TrackCheckpointEditDialog.create(player, eventManagerNode, this, raceService, checkpoint, false).show(); }); } super.show(); } }
src/main/java/net/gtaun/wl/race/dialog/TrackEditDialog.java
/** * WL Race Plugin * Copyright (C) 2013 MK124 * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package net.gtaun.wl.race.dialog; import java.util.List; import net.gtaun.shoebill.common.dialog.AbstractDialog; import net.gtaun.shoebill.common.dialog.MsgboxDialog; import net.gtaun.shoebill.exception.AlreadyExistException; import net.gtaun.shoebill.object.Player; import net.gtaun.util.event.EventManager; import net.gtaun.wl.common.dialog.WlInputDialog; import net.gtaun.wl.common.dialog.WlListDialog; import net.gtaun.wl.common.dialog.WlMsgboxDialog; import net.gtaun.wl.lang.LocalizedStringSet.PlayerStringSet; import net.gtaun.wl.race.impl.RaceServiceImpl; import net.gtaun.wl.race.racing.Racing; import net.gtaun.wl.race.racing.RacingManagerImpl; import net.gtaun.wl.race.track.Track; import net.gtaun.wl.race.track.Track.TrackStatus; import net.gtaun.wl.race.track.TrackCheckpoint; import net.gtaun.wl.race.track.TrackManagerImpl; import net.gtaun.wl.race.util.RacingUtils; import org.apache.commons.lang3.StringUtils; public class TrackEditDialog extends WlListDialog { private final PlayerStringSet stringSet; private final RaceServiceImpl raceService; private final Track track; public TrackEditDialog(Player player, EventManager eventManager, AbstractDialog parent, RaceServiceImpl service, Track track) { super(player, eventManager); setParentDialog(parent); this.raceService = service; this.track = track; stringSet = service.getLocalizedStringSet().getStringSet(player); setCaption(() -> stringSet.format("Dialog.TrackEditDialog.Caption", track.getName())); setClickOkHandler((d, i) -> player.playSound(1083)); } @Override public void show() { RacingManagerImpl racingManager = raceService.getRacingManager(); items.clear(); addItem(stringSet.format("Dialog.TrackEditDialog.Name", track.getName()), (i) -> { String caption = stringSet.get("Dialog.TrackEditNameDialog.Caption"); String message = stringSet.format("Dialog.TrackEditNameDialog.Text", track.getName()); TrackNamingDialog.create(player, rootEventManager, this, caption, message, raceService, (d, name) -> { try { TrackManagerImpl trackManager = raceService.getTrackManager(); trackManager.renameTrack(track, name); showParentDialog(); } catch (AlreadyExistException ex) { d.setAppendMessage(stringSet.format("Dialog.TrackEditNameDialog.AlreadyExistAppendMessage", name)); show(); } catch (IllegalArgumentException ex) { d.setAppendMessage(stringSet.format("Dialog.TrackEditNameDialog.IllegalFormatAppendMessage", name)); show(); } }).show(); }); addItem(() -> { String desc = track.getDesc(); if (StringUtils.isBlank(desc)) desc = stringSet.get("Common.Empty"); return stringSet.format("Dialog.TrackEditDialog.Desc", desc); }, (i) -> { String caption = stringSet.get("Dialog.TrackEditDescDialog.Caption"); String message = stringSet.format("Dialog.TrackEditDescDialog.Text", track.getName(), track.getDesc()); WlInputDialog.create(player, rootEventManager) .parentDialog(this) .caption(caption) .message(message) .onClickOk((d, text) -> { String desc = StringUtils.trimToEmpty(text); desc = StringUtils.replace(desc, "%", "#"); desc = StringUtils.replace(desc, "\t", " "); desc = StringUtils.replace(desc, "\n", " "); track.setDesc(desc); d.showParentDialog(); }) .build().show(); }); addItem(() -> stringSet.format("Dialog.TrackEditDialog.Checkpoints", track.getCheckpoints().size()), (i) -> show()); addItem(() -> stringSet.format("Dialog.TrackEditDialog.Length", track.getLength()/1000.0f), (i) -> show()); addItem(() -> stringSet.get("Dialog.TrackEditDialog.AddCheckpoint"), (i) -> { TrackCheckpoint checkpoint = track.createCheckpoint(player.getLocation()); TrackCheckpointEditDialog.create(player, eventManagerNode, null, raceService, checkpoint, true).show(); }); addItem(() -> stringSet.get("Dialog.TrackEditDialog.Setting"), (i) -> { TrackSettingDialog.create(player, rootEventManager, this, raceService, track).show(); }); addItem(() -> stringSet.get("Dialog.TrackEditDialog.Delete"), (i) -> { String caption = stringSet.get("Dialog.TrackDeleteConfirmDialog.Caption"); String message = stringSet.format("Dialog.TrackDeleteConfirmDialog.Text", track.getName()); WlInputDialog.create(player, rootEventManager) .parentDialog(this) .caption(caption) .message(message) .onClickOk((d, text) -> { if (!track.equals(text)) { d.showParentDialog(); return; } raceService.stopEditingTrack(player); TrackManagerImpl trackManager = raceService.getTrackManager(); trackManager.deleteTrack(track); String msgboxCaption = stringSet.get("Dialog.TrackDeleteCompleteDialog.Caption"); String msgboxMessage = stringSet.format("Dialog.TrackDeleteCompleteDialog.Text", track.getName()); WlMsgboxDialog.create(player, rootEventManager) .parentDialog(this) .caption(msgboxCaption) .message(msgboxMessage) .onClickOk((dialog) -> { player.playSound(1083); dialog.showParentDialog(); }) .build().show(); }) .build().show(); }); addItem(stringSet.get("Dialog.TrackEditDialog.StopEditing"), (i) -> { raceService.stopEditingTrack(player); }); addItem(stringSet.get("Dialog.TrackEditDialog.FinishEditing"), () -> { if (track.getCheckpoints().size() < 2) return false; return true; }, (i) -> { String caption = stringSet.get("Dialog.TrackFinishEditingConfirmDialog.Caption"); String message = stringSet.format("Dialog.TrackFinishEditingConfirmDialog.Text", track.getName()); MsgboxDialog.create(player, rootEventManager) .caption(caption) .message(message) .onClickOk((d) -> { player.playSound(1083); raceService.stopEditingTrack(player); track.setStatus(TrackStatus.COMPLETED); showParentDialog(); }) .build().show();; }); addItem(stringSet.get("Dialog.TrackEditDialog.Test"), () -> { if (track.getCheckpoints().isEmpty()) return false; return true; }, (i) -> { Runnable startNewRacing = () -> { Racing racing = racingManager.createRacing(track, player, RacingUtils.getDefaultName(player, track)); racing.teleToStartingPoint(player); racing.beginCountdown(); }; List<TrackCheckpoint> checkpoints = track.getCheckpoints(); if (checkpoints.isEmpty()) return; if (racingManager.isPlayerInRacing(player)) { Racing racing = racingManager.getPlayerRacing(player); NewRacingConfirmDialog.create(player, rootEventManager, this, raceService, racing, () -> { startNewRacing.run(); }).show(); } else startNewRacing.run(); }); addItem("-", (i) -> show()); List<TrackCheckpoint> checkpoints = track.getCheckpoints(); for (int i=0; i<checkpoints.size(); i++) { TrackCheckpoint checkpoint = checkpoints.get(i); float distance = player.getLocation().distance(checkpoint.getLocation()); String item = stringSet.format("Dialog.TrackEditDialog.Checkpoint", i+1, distance); addItem(item, (listItem) -> { TrackCheckpointEditDialog.create(player, eventManagerNode, this, raceService, checkpoint, false).show(); }); } super.show(); } }
Bug fixed
src/main/java/net/gtaun/wl/race/dialog/TrackEditDialog.java
Bug fixed
<ide><path>rc/main/java/net/gtaun/wl/race/dialog/TrackEditDialog.java <ide> public class TrackEditDialog extends WlListDialog <ide> { <ide> private final PlayerStringSet stringSet; <del> <add> <ide> private final RaceServiceImpl raceService; <ide> private final Track track; <del> <add> <ide> <ide> public TrackEditDialog(Player player, EventManager eventManager, AbstractDialog parent, RaceServiceImpl service, Track track) <ide> { <ide> super(player, eventManager); <ide> setParentDialog(parent); <del> <add> <ide> this.raceService = service; <ide> this.track = track; <del> <add> <ide> stringSet = service.getLocalizedStringSet().getStringSet(player); <ide> setCaption(() -> stringSet.format("Dialog.TrackEditDialog.Caption", track.getName())); <del> <add> <ide> setClickOkHandler((d, i) -> player.playSound(1083)); <ide> } <del> <add> <ide> @Override <ide> public void show() <ide> { <ide> RacingManagerImpl racingManager = raceService.getRacingManager(); <del> <add> <ide> items.clear(); <ide> addItem(stringSet.format("Dialog.TrackEditDialog.Name", track.getName()), (i) -> <ide> { <ide> } <ide> }).show(); <ide> }); <del> <add> <ide> addItem(() -> <ide> { <ide> String desc = track.getDesc(); <ide> desc = StringUtils.replace(desc, "%", "#"); <ide> desc = StringUtils.replace(desc, "\t", " "); <ide> desc = StringUtils.replace(desc, "\n", " "); <del> <add> <ide> track.setDesc(desc); <ide> d.showParentDialog(); <ide> }) <ide> .build().show(); <ide> }); <del> <add> <ide> addItem(() -> stringSet.format("Dialog.TrackEditDialog.Checkpoints", track.getCheckpoints().size()), (i) -> show()); <ide> addItem(() -> stringSet.format("Dialog.TrackEditDialog.Length", track.getLength()/1000.0f), (i) -> show()); <del> <add> <ide> addItem(() -> stringSet.get("Dialog.TrackEditDialog.AddCheckpoint"), (i) -> <ide> { <ide> TrackCheckpoint checkpoint = track.createCheckpoint(player.getLocation()); <ide> TrackCheckpointEditDialog.create(player, eventManagerNode, null, raceService, checkpoint, true).show(); <ide> }); <del> <add> <ide> addItem(() -> stringSet.get("Dialog.TrackEditDialog.Setting"), (i) -> <ide> { <ide> TrackSettingDialog.create(player, rootEventManager, this, raceService, track).show(); <ide> }); <del> <add> <ide> addItem(() -> stringSet.get("Dialog.TrackEditDialog.Delete"), (i) -> <ide> { <ide> String caption = stringSet.get("Dialog.TrackDeleteConfirmDialog.Caption"); <ide> .message(message) <ide> .onClickOk((d, text) -> <ide> { <del> if (!track.equals(text)) <add> if (!track.getName().equals(text)) <ide> { <ide> d.showParentDialog(); <ide> return; <ide> } <del> <add> <ide> raceService.stopEditingTrack(player); <del> <add> <ide> TrackManagerImpl trackManager = raceService.getTrackManager(); <ide> trackManager.deleteTrack(track); <del> <add> <ide> String msgboxCaption = stringSet.get("Dialog.TrackDeleteCompleteDialog.Caption"); <ide> String msgboxMessage = stringSet.format("Dialog.TrackDeleteCompleteDialog.Text", track.getName()); <ide> WlMsgboxDialog.create(player, rootEventManager) <ide> }) <ide> .build().show(); <ide> }); <del> <add> <ide> addItem(stringSet.get("Dialog.TrackEditDialog.StopEditing"), (i) -> <ide> { <ide> raceService.stopEditingTrack(player); <ide> }); <del> <add> <ide> addItem(stringSet.get("Dialog.TrackEditDialog.FinishEditing"), () -> <ide> { <ide> if (track.getCheckpoints().size() < 2) return false; <ide> { <ide> String caption = stringSet.get("Dialog.TrackFinishEditingConfirmDialog.Caption"); <ide> String message = stringSet.format("Dialog.TrackFinishEditingConfirmDialog.Text", track.getName()); <del> <add> <ide> MsgboxDialog.create(player, rootEventManager) <ide> .caption(caption) <ide> .message(message) <ide> .onClickOk((d) -> <ide> { <ide> player.playSound(1083); <del> <add> <ide> raceService.stopEditingTrack(player); <ide> track.setStatus(TrackStatus.COMPLETED); <del> <add> <ide> showParentDialog(); <ide> }) <ide> .build().show();; <ide> }); <del> <add> <ide> addItem(stringSet.get("Dialog.TrackEditDialog.Test"), () -> <ide> { <ide> if (track.getCheckpoints().isEmpty()) return false; <ide> racing.teleToStartingPoint(player); <ide> racing.beginCountdown(); <ide> }; <del> <add> <ide> List<TrackCheckpoint> checkpoints = track.getCheckpoints(); <ide> if (checkpoints.isEmpty()) return; <del> <add> <ide> if (racingManager.isPlayerInRacing(player)) <ide> { <ide> Racing racing = racingManager.getPlayerRacing(player); <ide> } <ide> else startNewRacing.run(); <ide> }); <del> <add> <ide> addItem("-", (i) -> show()); <del> <add> <ide> List<TrackCheckpoint> checkpoints = track.getCheckpoints(); <ide> for (int i=0; i<checkpoints.size(); i++) <ide> { <ide> TrackCheckpointEditDialog.create(player, eventManagerNode, this, raceService, checkpoint, false).show(); <ide> }); <ide> } <del> <add> <ide> super.show(); <ide> } <ide> }
Java
apache-2.0
b1eda5ac0163e58f278b86ee7988fee724061369
0
claudiu-stanciu/kylo,claudiu-stanciu/kylo,Teradata/kylo,claudiu-stanciu/kylo,claudiu-stanciu/kylo,Teradata/kylo,claudiu-stanciu/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo
/** * */ package com.thinkbiganalytics.metadata.jpa.sla; /*- * #%L * thinkbig-operational-metadata-jpa * %% * Copyright (C) 2017 ThinkBig Analytics * %% * 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. * #L% */ import com.thinkbiganalytics.metadata.api.MetadataAccess; import com.thinkbiganalytics.metadata.sla.api.AssessmentResult; import com.thinkbiganalytics.metadata.sla.api.Metric; import com.thinkbiganalytics.metadata.sla.api.MetricAssessment; import com.thinkbiganalytics.metadata.sla.api.Obligation; import com.thinkbiganalytics.metadata.sla.api.ObligationAssessment; import com.thinkbiganalytics.metadata.sla.api.ObligationGroup; import com.thinkbiganalytics.metadata.sla.api.ObligationGroup.Condition; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement.ID; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment; import com.thinkbiganalytics.metadata.sla.spi.AssessorNotFoundException; import com.thinkbiganalytics.metadata.sla.spi.MetricAssessmentBuilder; import com.thinkbiganalytics.metadata.sla.spi.MetricAssessor; import com.thinkbiganalytics.metadata.sla.spi.ObligationAssessmentBuilder; import com.thinkbiganalytics.metadata.sla.spi.ObligationAssessor; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; /** * A service level agreement assessor that will assess service level agreements checking the obligations and metrics and validating if the agreement is violated or not */ public class JpaServiceLevelAssessor implements ServiceLevelAssessor { private static final Logger log = LoggerFactory.getLogger(JpaServiceLevelAssessor.class); @Inject MetadataAccess metadataAccess; @Inject private JpaServiceLevelAssessmentProvider assessmentProvider; @Inject private ServiceLevelAgreementProvider agreementProvider; private ObligationAssessor<? extends Obligation> defaultObligationAssessor; private Set<ObligationAssessor<? extends Obligation>> obligationAssessors; private Set<MetricAssessor<? extends Metric, ? extends Serializable>> metricAssessors; public JpaServiceLevelAssessor() { this.obligationAssessors = Collections.synchronizedSet(new HashSet<ObligationAssessor<? extends Obligation>>()); this.metricAssessors = Collections.synchronizedSet(new HashSet<MetricAssessor<? extends Metric, ? extends Serializable>>()); this.defaultObligationAssessor = new DefaultObligationAssessor(); } /* * (non-Javadoc) * * @see com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor# * registerObligationAssessor(com.thinkbiganalytics.metadata.sla.spi. * ObligationAssessor) */ @Override public ObligationAssessor<? extends Obligation> registerObligationAssessor(ObligationAssessor<? extends Obligation> assessor) { this.obligationAssessors.add(assessor); return assessor; } /* * (non-Javadoc) * * @see com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor# * registerMetricAssessor(com.thinkbiganalytics.metadata.sla.spi. * MetricAssessor) */ @Override public MetricAssessor<? extends Metric, ? extends Serializable> registerMetricAssessor(MetricAssessor<? extends Metric, ? extends Serializable> assessor) { this.metricAssessors.add(assessor); return assessor; } private List<Comparable<? extends Serializable>> sanitizeComparablesArray(Comparable<? extends Serializable>... comparables) { List<Comparable<? extends Serializable>> list = new ArrayList<>(); if (comparables != null) { for (Comparable<? extends Serializable> comparable : comparables) { list.add(sanitizeComparable(comparable)); } } return list; } private Comparable<? extends Serializable> sanitizeComparable(Comparable<? extends Serializable> comparable) { if (comparable != null && (comparable instanceof Date)) { return ((Date) comparable).getTime(); } else { return comparable; } } /** * Needs to be wrapped in metadataAccess.read */ public ServiceLevelAssessment assess(ID id) { ServiceLevelAgreement sla = agreementProvider.getAgreement(id); if (sla == null) { //TODO add explicit NotFoundException throw new RuntimeException("Failed to get sla node for " + id); } return assess(sla); } @Override public ServiceLevelAssessment findLatestAssessment(ServiceLevelAgreement sla) { return this.metadataAccess.read(() -> assessmentProvider.findLatestAssessment(sla.getId()), MetadataAccess.SERVICE); } /** * Assess the SLA (coming from JCR) * * @param sla the SLA to be assessed */ public ServiceLevelAssessment assess(ServiceLevelAgreement sla) { log.info("Assessing SLA: {}", sla.getName()); ServiceLevelAssessment assessment = null; ServiceLevelAgreement serviceLevelAgreement = sla; assessment = this.metadataAccess.commit(() -> { AssessmentResult combinedResult = AssessmentResult.SUCCESS; try { //create the new Assessment JpaServiceLevelAssessment slaAssessment = new JpaServiceLevelAssessment(); slaAssessment.setId(JpaServiceLevelAssessment.SlaAssessmentId.create()); slaAssessment.setAgreement(serviceLevelAgreement); List<ObligationGroup> groups = sla.getObligationGroups(); for (ObligationGroup group : groups) { Condition condition = group.getCondition(); AssessmentResult groupResult = AssessmentResult.SUCCESS; Set<ObligationAssessment> obligationAssessments = new HashSet<>(); log.debug("Assessing obligation group {} with {} obligations", group, group.getObligations().size()); for (Obligation ob : group.getObligations()) { ObligationAssessment obAssessment = assess(ob, slaAssessment); obligationAssessments.add(obAssessment); // slaAssessment.add(obAssessment); groupResult = groupResult.max(obAssessment.getResult()); } slaAssessment.setObligationAssessments(obligationAssessments); // Short-circuit required or sufficient if necessary. switch (condition) { case REQUIRED: if (groupResult == AssessmentResult.FAILURE) { return completeAssessment(slaAssessment, groupResult); } break; case SUFFICIENT: if (groupResult != AssessmentResult.FAILURE) { return completeAssessment(slaAssessment, groupResult); } break; default: } // Required condition but non-failure, sufficient condition but non-success, or optional condition: // continue assessing groups and retain the best of the group results. combinedResult = combinedResult.max(groupResult); } return completeAssessment(slaAssessment, combinedResult); } finally { log.debug("Completed assessment of SLA {}: {}", sla.getName(), combinedResult); } }, MetadataAccess.SERVICE); return assessment; } private ObligationAssessment assess(Obligation ob, JpaServiceLevelAssessment serviceLevelAssessment) { ObligationAssessmentBuilderImpl builder = new ObligationAssessmentBuilderImpl(ob, serviceLevelAssessment); @SuppressWarnings("unchecked") ObligationAssessor<Obligation> assessor = (ObligationAssessor<Obligation>) findAssessor(ob); log.debug("Assessing obligation \"{}\" with assessor: {}", assessor); assessor.assess(ob, builder); return builder.build(); } private ServiceLevelAssessment completeAssessment(JpaServiceLevelAssessment slaAssessment, AssessmentResult result) { slaAssessment.setResult(result); String slaName = slaAssessment.getAgreement() != null ? slaAssessment.getAgreement().getName() : ""; if (result == AssessmentResult.SUCCESS) { slaAssessment.setMessage("SLA assessment requirements were met for '" + slaName + "'"); } else { slaAssessment.setMessage("At least one of the SLA obligations for '" + slaName + "' resulted in the status: " + result); } //save it assessmentProvider.save(slaAssessment); return slaAssessment; } protected ObligationAssessor<? extends Obligation> findAssessor(Obligation obligation) { synchronized (this.obligationAssessors) { for (ObligationAssessor<? extends Obligation> assessor : this.obligationAssessors) { if (assessor.accepts(obligation)) { return assessor; } } } return this.defaultObligationAssessor; } @SuppressWarnings("unchecked") protected <M extends Metric> MetricAssessor<M, ?> findAssessor(M metric) { synchronized (this.metricAssessors) { for (MetricAssessor<? extends Metric, ? extends Serializable> accessor : this.metricAssessors) { if (accessor.accepts(metric)) { return (MetricAssessor<M, ?>) accessor; } } } throw new AssessorNotFoundException(metric); } private class ObligationAssessmentBuilderImpl implements ObligationAssessmentBuilder { private Obligation obligation; private String message = ""; private AssessmentResult result = AssessmentResult.SUCCESS; private Comparator<ObligationAssessment> comparator; private List<Comparable<? extends Serializable>> comparables; private ServiceLevelAssessment serviceLevelAssessment; private JpaObligationAssessment assessment; public ObligationAssessmentBuilderImpl(Obligation obligation, JpaServiceLevelAssessment serviceLevelAssessment) { this.obligation = obligation; this.assessment = new JpaObligationAssessment(); this.assessment.setObligation(obligation); this.serviceLevelAssessment = serviceLevelAssessment; serviceLevelAssessment.getObligationAssessments().add(this.assessment); this.assessment.setServiceLevelAssessment(serviceLevelAssessment); } @Override public ObligationAssessmentBuilder obligation(Obligation ob) { this.obligation = ob; return this; } @Override public ObligationAssessmentBuilder result(AssessmentResult result) { this.result = result; return this; } @Override public ObligationAssessmentBuilder message(String descr) { this.message = descr; return this; } @Override public ObligationAssessmentBuilder comparator(Comparator<ObligationAssessment> comp) { this.comparator = comp; return this; } @Override @SuppressWarnings("unchecked") public ObligationAssessmentBuilder compareWith(final Comparable<? extends Serializable> value, @SuppressWarnings("unchecked") final Comparable<? extends Serializable>... otherValues) { this.comparables = new ArrayList<Comparable<? extends Serializable>>(Arrays.asList(sanitizeComparable(value))); this.comparables.addAll(sanitizeComparablesArray(otherValues)); return this; } @Override public <M extends Metric> MetricAssessment<?> assess(M metric) { MetricAssessor<M, ?> assessor = findAssessor(metric); MetricAssessmentBuilderImpl builder = new MetricAssessmentBuilderImpl(metric, this.assessment); assessor.assess(metric, builder); MetricAssessment<?> metricAssmt = builder.build(); return metricAssmt; } protected ObligationAssessment build() { this.assessment.setObligation(this.obligation); this.assessment.setMessage(this.message); this.assessment.setResult(this.result); if (this.comparator != null) { this.assessment.setComparator(this.comparator); } if (this.comparables != null) { this.assessment.setComparables(this.comparables); } this.serviceLevelAssessment.getObligationAssessments().add(this.assessment); return this.assessment; } } private class MetricAssessmentBuilderImpl<D extends Serializable> implements MetricAssessmentBuilder<D> { private Metric metric; private String message = ""; private AssessmentResult result = AssessmentResult.SUCCESS; private D data; private Comparator<MetricAssessment<D>> comparator; private List<Comparable<? extends Serializable>> comparables; private JpaObligationAssessment obligationAssessment; public MetricAssessmentBuilderImpl(Metric metric, JpaObligationAssessment obligationAssessment) { this.obligationAssessment = obligationAssessment; this.metric = metric; } /** * not used **/ public MetricAssessmentBuilderImpl(Metric metric) { this.metric = metric; } /** * not used **/ @Override public MetricAssessmentBuilder<D> metric(Metric metric) { this.metric = metric; return this; } @Override public MetricAssessmentBuilder<D> message(String descr) { this.message = descr; return this; } @Override public MetricAssessmentBuilder<D> result(AssessmentResult result) { this.result = result; return this; } @Override public MetricAssessmentBuilder<D> data(D data) { this.data = data; return this; } @Override public MetricAssessmentBuilder<D> comparitor(Comparator<MetricAssessment<D>> comp) { this.comparator = comp; return this; } @Override @SuppressWarnings("unchecked") public MetricAssessmentBuilder<D> compareWith(Comparable<? extends Serializable> value, Comparable<? extends Serializable>... otherValues) { this.comparables = new ArrayList<Comparable<? extends Serializable>>(Arrays.asList(sanitizeComparable(value))); this.comparables.addAll(sanitizeComparablesArray(otherValues)); return this; } protected MetricAssessment build() { JpaMetricAssessment<D> assessment = new JpaMetricAssessment<>(); assessment.setMetric(this.metric); assessment.setMessage(this.message); assessment.setResult(this.result); assessment.setMetricDescription(this.metric.getDescription()); //assessment.setData(this.data); if (this.comparator != null) { assessment.setComparator(this.comparator); } if (this.comparables != null) { assessment.setComparables(this.comparables); } obligationAssessment.getMetricAssessments().add(assessment); assessment.setObligationAssessment(obligationAssessment); return assessment; } } protected class DefaultObligationAssessor implements ObligationAssessor<Obligation> { @Override public boolean accepts(Obligation obligation) { // Accepts any obligations return true; } @Override public void assess(Obligation obligation, ObligationAssessmentBuilder builder) { log.debug("Assessing obligation '{}' with {} metrics", obligation, obligation.getMetrics().size()); Set<MetricAssessment> metricAssessments = new HashSet<MetricAssessment>(); ObligationAssessmentBuilderImpl obligationAssessmentBuilder = (ObligationAssessmentBuilderImpl) builder; AssessmentResult result = AssessmentResult.SUCCESS; for (Metric metric : obligation.getMetrics()) { log.debug("Assessing obligation metric '{}'", metric); MetricAssessment assessment = obligationAssessmentBuilder.assess(metric); metricAssessments.add(assessment); } for (MetricAssessment ma : metricAssessments) { result = result.max(ma.getResult()); } String message = "The obligation requirements were met"; if (result != AssessmentResult.SUCCESS) { message = "At least one metric assessment resulted in the status: " + result; } log.debug("Assessment outcome '{}'", message); builder .result(result) .message(message) .obligation(obligation); } } }
core/operational-metadata/operational-metadata-jpa/src/main/java/com/thinkbiganalytics/metadata/jpa/sla/JpaServiceLevelAssessor.java
/** * */ package com.thinkbiganalytics.metadata.jpa.sla; /*- * #%L * thinkbig-operational-metadata-jpa * %% * Copyright (C) 2017 ThinkBig Analytics * %% * 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. * #L% */ import com.thinkbiganalytics.metadata.api.MetadataAccess; import com.thinkbiganalytics.metadata.sla.api.AssessmentResult; import com.thinkbiganalytics.metadata.sla.api.Metric; import com.thinkbiganalytics.metadata.sla.api.MetricAssessment; import com.thinkbiganalytics.metadata.sla.api.Obligation; import com.thinkbiganalytics.metadata.sla.api.ObligationAssessment; import com.thinkbiganalytics.metadata.sla.api.ObligationGroup; import com.thinkbiganalytics.metadata.sla.api.ObligationGroup.Condition; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement.ID; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment; import com.thinkbiganalytics.metadata.sla.spi.AssessorNotFoundException; import com.thinkbiganalytics.metadata.sla.spi.MetricAssessmentBuilder; import com.thinkbiganalytics.metadata.sla.spi.MetricAssessor; import com.thinkbiganalytics.metadata.sla.spi.ObligationAssessmentBuilder; import com.thinkbiganalytics.metadata.sla.spi.ObligationAssessor; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider; import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; /** * A service level agreement assessor that will assess service level agreements checking the obligations and metrics and validating if the agreement is violated or not */ public class JpaServiceLevelAssessor implements ServiceLevelAssessor { private static final Logger log = LoggerFactory.getLogger(JpaServiceLevelAssessor.class); @Inject MetadataAccess metadataAccess; @Inject private JpaServiceLevelAssessmentProvider assessmentProvider; @Inject private ServiceLevelAgreementProvider agreementProvider; private ObligationAssessor<? extends Obligation> defaultObligationAssessor; private Set<ObligationAssessor<? extends Obligation>> obligationAssessors; private Set<MetricAssessor<? extends Metric, ? extends Serializable>> metricAssessors; public JpaServiceLevelAssessor() { this.obligationAssessors = Collections.synchronizedSet(new HashSet<ObligationAssessor<? extends Obligation>>()); this.metricAssessors = Collections.synchronizedSet(new HashSet<MetricAssessor<? extends Metric, ? extends Serializable>>()); this.defaultObligationAssessor = new DefaultObligationAssessor(); } /* * (non-Javadoc) * * @see com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor# * registerObligationAssessor(com.thinkbiganalytics.metadata.sla.spi. * ObligationAssessor) */ @Override public ObligationAssessor<? extends Obligation> registerObligationAssessor(ObligationAssessor<? extends Obligation> assessor) { this.obligationAssessors.add(assessor); return assessor; } /* * (non-Javadoc) * * @see com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor# * registerMetricAssessor(com.thinkbiganalytics.metadata.sla.spi. * MetricAssessor) */ @Override public MetricAssessor<? extends Metric, ? extends Serializable> registerMetricAssessor(MetricAssessor<? extends Metric, ? extends Serializable> assessor) { this.metricAssessors.add(assessor); return assessor; } private List<Comparable<? extends Serializable>> sanitizeComparablesArray(Comparable<? extends Serializable>... comparables) { List<Comparable<? extends Serializable>> list = new ArrayList<>(); if (comparables != null) { for (Comparable<? extends Serializable> comparable : comparables) { list.add(sanitizeComparable(comparable)); } } return list; } private Comparable<? extends Serializable> sanitizeComparable(Comparable<? extends Serializable> comparable) { if (comparable != null && (comparable instanceof Date)) { return ((Date) comparable).getTime(); } else { return comparable; } } /** * Needs to be wrapped in metadataAccess.read */ public ServiceLevelAssessment assess(ID id) { ServiceLevelAgreement sla = agreementProvider.getAgreement(id); if (sla == null) { //TODO add explicit NotFoundException throw new RuntimeException("Failed to get sla node for " + id); } return assess(sla); } @Override public ServiceLevelAssessment findLatestAssessment(ServiceLevelAgreement sla) { return this.metadataAccess.read(() -> assessmentProvider.findLatestAssessment(sla.getId()), MetadataAccess.SERVICE); } /** * Assess the SLA (coming from JCR) * * @param sla the SLA to be assessed */ public ServiceLevelAssessment assess(ServiceLevelAgreement sla) { log.info("Assessing SLA: {}", sla.getName()); ServiceLevelAssessment assessment = null; ServiceLevelAgreement serviceLevelAgreement = sla; assessment = this.metadataAccess.commit(() -> { AssessmentResult combinedResult = AssessmentResult.SUCCESS; try { //create the new Assessment JpaServiceLevelAssessment slaAssessment = new JpaServiceLevelAssessment(); slaAssessment.setId(JpaServiceLevelAssessment.SlaAssessmentId.create()); slaAssessment.setAgreement(serviceLevelAgreement); List<ObligationGroup> groups = sla.getObligationGroups(); for (ObligationGroup group : groups) { Condition condition = group.getCondition(); AssessmentResult groupResult = AssessmentResult.SUCCESS; Set<ObligationAssessment> obligationAssessments = new HashSet<>(); log.debug("Assessing obligation group {} with {} obligations", group, group.getObligations().size()); for (Obligation ob : group.getObligations()) { ObligationAssessment obAssessment = assess(ob, slaAssessment); obligationAssessments.add(obAssessment); // slaAssessment.add(obAssessment); groupResult = groupResult.max(obAssessment.getResult()); } slaAssessment.setObligationAssessments(obligationAssessments); // Short-circuit required or sufficient if necessary. switch (condition) { case REQUIRED: if (groupResult == AssessmentResult.FAILURE) { return completeAssessment(slaAssessment, groupResult); } break; case SUFFICIENT: if (groupResult != AssessmentResult.FAILURE) { return completeAssessment(slaAssessment, groupResult); } break; default: } // Required condition but non-failure, sufficient condition but non-success, or optional condition: // continue assessing groups and retain the best of the group results. combinedResult = combinedResult.max(groupResult); } return completeAssessment(slaAssessment, combinedResult); } finally { log.debug("Completed assessment of SLA {}: {}", sla.getName(), combinedResult); } }, MetadataAccess.SERVICE); return assessment; } private ObligationAssessment assess(Obligation ob, JpaServiceLevelAssessment serviceLevelAssessment) { ObligationAssessmentBuilderImpl builder = new ObligationAssessmentBuilderImpl(ob, serviceLevelAssessment); @SuppressWarnings("unchecked") ObligationAssessor<Obligation> assessor = (ObligationAssessor<Obligation>) findAssessor(ob); log.debug("Assessing obligation \"{}\" with assessor: {}", assessor); assessor.assess(ob, builder); return builder.build(); } private ServiceLevelAssessment completeAssessment(JpaServiceLevelAssessment slaAssessment, AssessmentResult result) { slaAssessment.setResult(result); String slaName = slaAssessment.getAgreement() != null ? slaAssessment.getAgreement().getName() : ""; if (result == AssessmentResult.SUCCESS) { slaAssessment.setMessage("SLA assessment requirements were met for '" + slaName + "'"); } else { slaAssessment.setMessage("At least one of the SLA obligations for '" + slaName + "' resulted in the status: " + result); } //save it //only save if chanaged, otherwise log it? if (slaAssessment.getServiceLevelAgreementId() != null) { ServiceLevelAssessment previous = this.assessmentProvider.findLatestAssessmentNotEqualTo(slaAssessment.getServiceLevelAgreementId(), slaAssessment.getId()); } assessmentProvider.save(slaAssessment); return slaAssessment; } protected ObligationAssessor<? extends Obligation> findAssessor(Obligation obligation) { synchronized (this.obligationAssessors) { for (ObligationAssessor<? extends Obligation> assessor : this.obligationAssessors) { if (assessor.accepts(obligation)) { return assessor; } } } return this.defaultObligationAssessor; } @SuppressWarnings("unchecked") protected <M extends Metric> MetricAssessor<M, ?> findAssessor(M metric) { synchronized (this.metricAssessors) { for (MetricAssessor<? extends Metric, ? extends Serializable> accessor : this.metricAssessors) { if (accessor.accepts(metric)) { return (MetricAssessor<M, ?>) accessor; } } } throw new AssessorNotFoundException(metric); } private class ObligationAssessmentBuilderImpl implements ObligationAssessmentBuilder { private Obligation obligation; private String message = ""; private AssessmentResult result = AssessmentResult.SUCCESS; private Comparator<ObligationAssessment> comparator; private List<Comparable<? extends Serializable>> comparables; private ServiceLevelAssessment serviceLevelAssessment; private JpaObligationAssessment assessment; public ObligationAssessmentBuilderImpl(Obligation obligation, JpaServiceLevelAssessment serviceLevelAssessment) { this.obligation = obligation; this.assessment = new JpaObligationAssessment(); this.assessment.setObligation(obligation); this.serviceLevelAssessment = serviceLevelAssessment; serviceLevelAssessment.getObligationAssessments().add(this.assessment); this.assessment.setServiceLevelAssessment(serviceLevelAssessment); } @Override public ObligationAssessmentBuilder obligation(Obligation ob) { this.obligation = ob; return this; } @Override public ObligationAssessmentBuilder result(AssessmentResult result) { this.result = result; return this; } @Override public ObligationAssessmentBuilder message(String descr) { this.message = descr; return this; } @Override public ObligationAssessmentBuilder comparator(Comparator<ObligationAssessment> comp) { this.comparator = comp; return this; } @Override @SuppressWarnings("unchecked") public ObligationAssessmentBuilder compareWith(final Comparable<? extends Serializable> value, @SuppressWarnings("unchecked") final Comparable<? extends Serializable>... otherValues) { this.comparables = new ArrayList<Comparable<? extends Serializable>>(Arrays.asList(sanitizeComparable(value))); this.comparables.addAll(sanitizeComparablesArray(otherValues)); return this; } @Override public <M extends Metric> MetricAssessment<?> assess(M metric) { MetricAssessor<M, ?> assessor = findAssessor(metric); MetricAssessmentBuilderImpl builder = new MetricAssessmentBuilderImpl(metric, this.assessment); assessor.assess(metric, builder); MetricAssessment<?> metricAssmt = builder.build(); return metricAssmt; } protected ObligationAssessment build() { this.assessment.setObligation(this.obligation); this.assessment.setMessage(this.message); this.assessment.setResult(this.result); if (this.comparator != null) { this.assessment.setComparator(this.comparator); } if (this.comparables != null) { this.assessment.setComparables(this.comparables); } this.serviceLevelAssessment.getObligationAssessments().add(this.assessment); return this.assessment; } } private class MetricAssessmentBuilderImpl<D extends Serializable> implements MetricAssessmentBuilder<D> { private Metric metric; private String message = ""; private AssessmentResult result = AssessmentResult.SUCCESS; private D data; private Comparator<MetricAssessment<D>> comparator; private List<Comparable<? extends Serializable>> comparables; private JpaObligationAssessment obligationAssessment; public MetricAssessmentBuilderImpl(Metric metric, JpaObligationAssessment obligationAssessment) { this.obligationAssessment = obligationAssessment; this.metric = metric; } /** * not used **/ public MetricAssessmentBuilderImpl(Metric metric) { this.metric = metric; } /** * not used **/ @Override public MetricAssessmentBuilder<D> metric(Metric metric) { this.metric = metric; return this; } @Override public MetricAssessmentBuilder<D> message(String descr) { this.message = descr; return this; } @Override public MetricAssessmentBuilder<D> result(AssessmentResult result) { this.result = result; return this; } @Override public MetricAssessmentBuilder<D> data(D data) { this.data = data; return this; } @Override public MetricAssessmentBuilder<D> comparitor(Comparator<MetricAssessment<D>> comp) { this.comparator = comp; return this; } @Override @SuppressWarnings("unchecked") public MetricAssessmentBuilder<D> compareWith(Comparable<? extends Serializable> value, Comparable<? extends Serializable>... otherValues) { this.comparables = new ArrayList<Comparable<? extends Serializable>>(Arrays.asList(sanitizeComparable(value))); this.comparables.addAll(sanitizeComparablesArray(otherValues)); return this; } protected MetricAssessment build() { JpaMetricAssessment<D> assessment = new JpaMetricAssessment<>(); assessment.setMetric(this.metric); assessment.setMessage(this.message); assessment.setResult(this.result); assessment.setMetricDescription(this.metric.getDescription()); //assessment.setData(this.data); if (this.comparator != null) { assessment.setComparator(this.comparator); } if (this.comparables != null) { assessment.setComparables(this.comparables); } obligationAssessment.getMetricAssessments().add(assessment); assessment.setObligationAssessment(obligationAssessment); return assessment; } } protected class DefaultObligationAssessor implements ObligationAssessor<Obligation> { @Override public boolean accepts(Obligation obligation) { // Accepts any obligations return true; } @Override public void assess(Obligation obligation, ObligationAssessmentBuilder builder) { log.debug("Assessing obligation '{}' with {} metrics", obligation, obligation.getMetrics().size()); Set<MetricAssessment> metricAssessments = new HashSet<MetricAssessment>(); ObligationAssessmentBuilderImpl obligationAssessmentBuilder = (ObligationAssessmentBuilderImpl) builder; AssessmentResult result = AssessmentResult.SUCCESS; for (Metric metric : obligation.getMetrics()) { log.debug("Assessing obligation metric '{}'", metric); MetricAssessment assessment = obligationAssessmentBuilder.assess(metric); metricAssessments.add(assessment); } for (MetricAssessment ma : metricAssessments) { result = result.max(ma.getResult()); } String message = "The obligation requirements were met"; if (result != AssessmentResult.SUCCESS) { message = "At least one metric assessment resulted in the status: " + result; } log.debug("Assessment outcome '{}'", message); builder .result(result) .message(message) .obligation(obligation); } } }
revert commit.
core/operational-metadata/operational-metadata-jpa/src/main/java/com/thinkbiganalytics/metadata/jpa/sla/JpaServiceLevelAssessor.java
revert commit.
<ide><path>ore/operational-metadata/operational-metadata-jpa/src/main/java/com/thinkbiganalytics/metadata/jpa/sla/JpaServiceLevelAssessor.java <ide> } <ide> <ide> //save it <del> //only save if chanaged, otherwise log it? <del> if (slaAssessment.getServiceLevelAgreementId() != null) { <del> ServiceLevelAssessment previous = this.assessmentProvider.findLatestAssessmentNotEqualTo(slaAssessment.getServiceLevelAgreementId(), slaAssessment.getId()); <del> <del> } <ide> assessmentProvider.save(slaAssessment); <ide> return slaAssessment; <ide> }
Java
mit
error: pathspec '15.ThreeSum.java' did not match any file(s) known to git
0129b0ed5a2c103028a92ed93b0055dc5f42d185
1
xliiauo/CTCI,xliiauo/CTCI,xliiauo/CTCI
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; // 311/48ms/11.70% class ThreeSum { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<>(); Set<Integer> targets = new HashSet<>(); for (int target = 0; target < nums.length; target++) { if (!targets.contains(nums[target])) { Set<Integer> set = new HashSet<>(); List<Integer> previousList = new ArrayList<>(); for (int i = target + 1; i < nums.length; i++) { if (set.contains(-nums[target] - nums[i])) { List<Integer> innerList = new ArrayList<>(); innerList.add(nums[target]); innerList.add(-nums[target] - nums[i]); innerList.add(nums[i]); if (!innerList.equals(previousList)) { list.add(innerList); previousList = innerList; } } else { set.add(nums[i]); } } targets.add(nums[target]); } } return list; } public static void main(String[] args) { System.out.println(new ThreeSum().threeSum(new int[] {4, 0, -1, -1, -1, 2, 2, 2, 2, 0, 0, 0, -4})); } }
15.ThreeSum.java
Add solution 15 Java
15.ThreeSum.java
Add solution 15 Java
<ide><path>5.ThreeSum.java <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.HashSet; <add>import java.util.List; <add>import java.util.Set; <add> <add>// 311/48ms/11.70% <add>class ThreeSum { <add> public List<List<Integer>> threeSum(int[] nums) { <add> Arrays.sort(nums); <add> List<List<Integer>> list = new ArrayList<>(); <add> Set<Integer> targets = new HashSet<>(); <add> <add> for (int target = 0; target < nums.length; target++) { <add> if (!targets.contains(nums[target])) { <add> Set<Integer> set = new HashSet<>(); <add> List<Integer> previousList = new ArrayList<>(); <add> <add> for (int i = target + 1; i < nums.length; i++) { <add> if (set.contains(-nums[target] - nums[i])) { <add> List<Integer> innerList = new ArrayList<>(); <add> innerList.add(nums[target]); <add> innerList.add(-nums[target] - nums[i]); <add> innerList.add(nums[i]); <add> <add> if (!innerList.equals(previousList)) { <add> list.add(innerList); <add> previousList = innerList; <add> } <add> } else { <add> set.add(nums[i]); <add> } <add> } <add> targets.add(nums[target]); <add> } <add> } <add> return list; <add> } <add> <add> public static void main(String[] args) { <add> System.out.println(new ThreeSum().threeSum(new int[] {4, 0, -1, -1, -1, 2, 2, 2, 2, 0, 0, 0, -4})); <add> } <add>}
Java
apache-2.0
4ae9e1c59394f95604b1674f7738e7b3d00f6857
0
GabrielBrascher/cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,argv0/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,argv0/cloudstack,wido/cloudstack,argv0/cloudstack,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,argv0/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,mufaddalq/cloudstack-datera-driver,cinderella/incubator-cloudstack,argv0/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,argv0/cloudstack,wido/cloudstack
/** * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. * * It 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 any later version. * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.cloud.storage.download; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.concurrent.ConcurrentHashMap; import javax.ejb.Local; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.Command; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DownloadCommand; import com.cloud.agent.api.storage.DownloadProgressCommand; import com.cloud.agent.api.storage.DownloadProgressCommand.RequestType; import com.cloud.async.AsyncInstanceCreateStatus; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.event.EventTypes; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.Type; import com.cloud.storage.StoragePoolHostVO; import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.template.TemplateConstants; import com.cloud.storage.template.TemplateInfo; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; import com.cloud.vm.dao.SecondaryStorageVmDao; /** * @author chiradeep * */ @Local(value={DownloadMonitor.class}) public class DownloadMonitorImpl implements DownloadMonitor { static final Logger s_logger = Logger.getLogger(DownloadMonitorImpl.class); private static final String DEFAULT_HTTP_COPY_PORT = "80"; private String _hyperVisorType; @Inject VMTemplateHostDao _vmTemplateHostDao; @Inject VMTemplatePoolDao _vmTemplatePoolDao; @Inject StoragePoolHostDao _poolHostDao; @Inject SecondaryStorageVmDao _secStorageVmDao; @Inject HostDao _serverDao = null; @Inject private final DataCenterDao _dcDao = null; @Inject VMTemplateDao _templateDao = null; @Inject private final EventDao _eventDao = null; @Inject private AgentManager _agentMgr; @Inject ConfigurationDao _configDao; private String _name; private Boolean _sslCopy = new Boolean(false); private String _copyAuthPasswd; Timer _timer; final Map<VMTemplateHostVO, DownloadListener> _listenerMap = new ConcurrentHashMap<VMTemplateHostVO, DownloadListener>(); public long send(Long hostId, Command cmd, Listener listener) { return _agentMgr.gatherStats(hostId, cmd, listener); } public void logEvent(long accountId, String evtType, String description, String level) { EventVO event = new EventVO(); event.setUserId(1); event.setAccountId(accountId); event.setType(evtType); event.setDescription(description); event.setLevel(level); _eventDao.persist(event); } @Override public boolean configure(String name, Map<String, Object> params) { _name = name; final Map<String, String> configs = _configDao.getConfiguration("ManagementServer", params); _sslCopy = Boolean.parseBoolean(configs.get("secstorage.encrypt.copy")); String cert = configs.get("secstorage.secure.copy.cert"); if ("realhostip.com".equalsIgnoreCase(cert)) { s_logger.warn("Only realhostip.com ssl cert is supported, ignoring self-signed and other certs"); } _hyperVisorType = _configDao.getValue("hypervisor.type"); _copyAuthPasswd = configs.get("secstorage.copy.password"); _agentMgr.registerForHostEvents(new DownloadListener(this), true, false, false); return true; } @Override public String getName() { return _name; } @Override public boolean start() { _timer = new Timer(); return true; } @Override public boolean stop() { return true; } public boolean isTemplateUpdateable(Long templateId) { List<VMTemplateHostVO> downloadsInProgress = _vmTemplateHostDao.listByTemplateStatus(templateId, VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS); return (downloadsInProgress.size() == 0); } public boolean isTemplateUpdateable(Long templateId, Long datacenterId) { List<VMTemplateHostVO> downloadsInProgress = _vmTemplateHostDao.listByTemplateStatus(templateId, datacenterId, VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS); return (downloadsInProgress.size() == 0); } public void copyTemplate(VMTemplateVO template, HostVO sourceServer, HostVO destServer) throws InvalidParameterValueException, StorageUnavailableException{ boolean downloadJobExists = false; VMTemplateHostVO destTmpltHost = null; VMTemplateHostVO srcTmpltHost = null; srcTmpltHost = _vmTemplateHostDao.findByHostTemplate(sourceServer.getId(), template.getId()); if (srcTmpltHost == null) { throw new InvalidParameterValueException("Template " + template.getName() + " not associated with " + sourceServer.getName()); } String url = generateCopyUrl(sourceServer, srcTmpltHost); if (url == null) { s_logger.warn("Unable to start/resume copy of template " + template.getUniqueName() + " to " + destServer.getName() + ", no secondary storage vm in running state in source zone"); throw new StorageUnavailableException("No secondary VM in running state in zone " + sourceServer.getDataCenterId()); } destTmpltHost = _vmTemplateHostDao.findByHostTemplate(destServer.getId(), template.getId()); if (destTmpltHost == null) { destTmpltHost = new VMTemplateHostVO(destServer.getId(), template.getId(), new Date(), 0, VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, "jobid0000", null, url); destTmpltHost.setCopy(true); _vmTemplateHostDao.persist(destTmpltHost); } else if ((destTmpltHost.getJobId() != null) && (destTmpltHost.getJobId().length() > 2)) { downloadJobExists = true; } Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes(); if(destTmpltHost != null) { start(); DownloadCommand dcmd = new DownloadCommand(url, template.getUniqueName(), template.getFormat(), template.isRequiresHvm(), template.getAccountId(), template.getId(), template.getDisplayText(), template.getChecksum(), TemplateConstants.DEFAULT_HTTP_AUTH_USER, _copyAuthPasswd, maxTemplateSizeInBytes); DownloadListener dl = downloadJobExists?_listenerMap.get(destTmpltHost):null; if (dl == null) { dl = new DownloadListener(destServer, template, _timer, _vmTemplateHostDao, destTmpltHost.getId(), this, dcmd); } if (downloadJobExists) { dcmd = new DownloadProgressCommand(dcmd, destTmpltHost.getJobId(), RequestType.GET_OR_RESTART); dl.setCurrState(destTmpltHost.getDownloadState()); } _listenerMap.put(destTmpltHost, dl); long result = send(destServer.getId(), dcmd, dl); if (result == -1) { s_logger.warn("Unable to start /resume COPY of template " + template.getUniqueName() + " to " + destServer.getName()); dl.setDisconnected(); dl.scheduleStatusCheck(RequestType.GET_OR_RESTART); } } } private String generateCopyUrl(String ipAddress, String path){ String hostname = ipAddress; String scheme = "http"; if (_sslCopy) { hostname = ipAddress.replace(".", "-"); hostname = hostname + ".realhostip.com"; scheme = "https"; } return scheme + "://" + hostname + "/copy/" + path; } private String generateCopyUrl(HostVO sourceServer, VMTemplateHostVO srcTmpltHost) { List<SecondaryStorageVmVO> ssVms = _secStorageVmDao.getSecStorageVmListInStates(sourceServer.getDataCenterId(), State.Running); if (ssVms.size() > 0) { SecondaryStorageVmVO ssVm = ssVms.get(0); if (ssVm.getPublicIpAddress() == null) { s_logger.warn("A running secondary storage vm has a null public ip?"); return null; } return generateCopyUrl(ssVm.getPublicIpAddress(), srcTmpltHost.getInstallPath()); } /*No secondary storage vm yet*/ if (_hyperVisorType.equalsIgnoreCase("KVM")) { return "file://" + sourceServer.getParent() + "/" + srcTmpltHost.getInstallPath(); } return null; } private void downloadTemplateToStorage(VMTemplateVO template, HostVO sserver) { boolean downloadJobExists = false; VMTemplateHostVO vmTemplateHost = null; vmTemplateHost = _vmTemplateHostDao.findByHostTemplate(sserver.getId(), template.getId()); if (vmTemplateHost == null) { vmTemplateHost = new VMTemplateHostVO(sserver.getId(), template.getId(), new Date(), 0, VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, "jobid0000", null, template.getUrl()); _vmTemplateHostDao.persist(vmTemplateHost); } else if ((vmTemplateHost.getJobId() != null) && (vmTemplateHost.getJobId().length() > 2)) { downloadJobExists = true; } Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes(); if(vmTemplateHost != null) { start(); DownloadCommand dcmd = new DownloadCommand(template, maxTemplateSizeInBytes); dcmd.setUrl(vmTemplateHost.getDownloadUrl()); if (vmTemplateHost.isCopy()) { dcmd.setCreds(TemplateConstants.DEFAULT_HTTP_AUTH_USER, _copyAuthPasswd); } DownloadListener dl = new DownloadListener(sserver, template, _timer, _vmTemplateHostDao, vmTemplateHost.getId(), this, dcmd); if (downloadJobExists) { dcmd = new DownloadProgressCommand(dcmd, vmTemplateHost.getJobId(), RequestType.GET_OR_RESTART); dl.setCurrState(vmTemplateHost.getDownloadState()); } _listenerMap.put(vmTemplateHost, dl); long result = send(sserver.getId(), dcmd, dl); if (result == -1) { s_logger.warn("Unable to start /resume download of template " + template.getUniqueName() + " to " + sserver.getName()); dl.setDisconnected(); dl.scheduleStatusCheck(RequestType.GET_OR_RESTART); } } } @Override public boolean downloadTemplateToStorage(Long templateId, Long zoneId) { if (isTemplateUpdateable(templateId)) { List<DataCenterVO> dcs = new ArrayList<DataCenterVO>(); if (zoneId == null) { dcs.addAll(_dcDao.listAllIncludingRemoved()); } else { dcs.add(_dcDao.findById(zoneId)); } for (DataCenterVO dc: dcs) { initiateTemplateDownload(templateId, dc.getId()); } return true; } else { return false; } } private void initiateTemplateDownload(Long templateId, Long dataCenterId) { VMTemplateVO template = _templateDao.findById(templateId); if (template != null && (template.getUrl() != null)) { //find all storage hosts and tell them to initiate download List<HostVO> storageServers = _serverDao.listByTypeDataCenter(Host.Type.SecondaryStorage, dataCenterId); for (HostVO sserver: storageServers) { downloadTemplateToStorage(template, sserver); } } } public void handleDownloadEvent(HostVO host, VMTemplateVO template, Status dnldStatus) { if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) || (dnldStatus==Status.ABANDONED)){ VMTemplateHostVO vmTemplateHost = new VMTemplateHostVO(host.getId(), template.getId()); DownloadListener oldListener = _listenerMap.get(vmTemplateHost); if (oldListener != null) { _listenerMap.remove(vmTemplateHost); } } if (dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { logEvent(template.getAccountId(), EventTypes.EVENT_TEMPLATE_DOWNLOAD_SUCCESS, template.getName() + " successfully downloaded to storage server " + host.getName(), EventVO.LEVEL_INFO); } if (dnldStatus == Status.DOWNLOAD_ERROR) { logEvent(template.getAccountId(), EventTypes.EVENT_TEMPLATE_DOWNLOAD_FAILED, template.getName() + " failed to download to storage server " + host.getName(), EventVO.LEVEL_ERROR); } if (dnldStatus == Status.ABANDONED) { logEvent(template.getAccountId(), EventTypes.EVENT_TEMPLATE_DOWNLOAD_FAILED, template.getName() + " :aborted download to storage server " + host.getName(), EventVO.LEVEL_WARN); } VMTemplateHostVO vmTemplateHost = _vmTemplateHostDao.findByHostTemplate(host.getId(), template.getId()); if (dnldStatus == Status.DOWNLOADED) { long size = -1; if(vmTemplateHost!=null){ size = vmTemplateHost.getSize(); } else{ s_logger.warn("Failed to get size for template" + template.getName()); } String eventParams = "id=" + template.getId() + "\ndcId="+host.getDataCenterId()+"\nsize="+size; EventVO event = new EventVO(); event.setUserId(1L); event.setAccountId(template.getAccountId()); if((template.getFormat()).equals(ImageFormat.ISO)){ event.setType(EventTypes.EVENT_ISO_CREATE); event.setDescription("Successfully created ISO " + template.getName()); } else{ event.setType(EventTypes.EVENT_TEMPLATE_CREATE); event.setDescription("Successfully created template " + template.getName()); } event.setParameters(eventParams); event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); } if (vmTemplateHost != null) { Long poolId = vmTemplateHost.getPoolId(); if (poolId != null) { VMTemplateStoragePoolVO vmTemplatePool = _vmTemplatePoolDao.findByPoolTemplate(poolId, template.getId()); StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(poolId, host.getId()); if (vmTemplatePool != null && poolHost != null) { vmTemplatePool.setDownloadPercent(vmTemplateHost.getDownloadPercent()); vmTemplatePool.setDownloadState(vmTemplateHost.getDownloadState()); vmTemplatePool.setErrorString(vmTemplateHost.getErrorString()); String localPath = poolHost.getLocalPath(); String installPath = vmTemplateHost.getInstallPath(); if (installPath != null) { if (!installPath.startsWith("/")) { installPath = "/" + installPath; } if (!(localPath == null) && !installPath.startsWith(localPath)) { localPath = localPath.replaceAll("/\\p{Alnum}+/*$", ""); //remove instance if necessary } if (!(localPath == null) && installPath.startsWith(localPath)) { installPath = installPath.substring(localPath.length()); } } vmTemplatePool.setInstallPath(installPath); vmTemplatePool.setLastUpdated(vmTemplateHost.getLastUpdated()); vmTemplatePool.setJobId(vmTemplateHost.getJobId()); vmTemplatePool.setLocalDownloadPath(vmTemplateHost.getLocalDownloadPath()); _vmTemplatePoolDao.update(vmTemplatePool.getId(),vmTemplatePool); } } } } @Override public void handleTemplateSync(long sserverId, Map<String, TemplateInfo> templateInfo) { HostVO storageHost = _serverDao.findById(sserverId); if (storageHost == null) { s_logger.warn("Huh? Agent id " + sserverId + " does not correspond to a row in hosts table?"); return; } Set<VMTemplateVO> toBeDownloaded = new HashSet<VMTemplateVO>(); List<VMTemplateVO> allTemplates = _templateDao.listAllInZone(storageHost.getDataCenterId()); VMTemplateVO rtngTmplt = _templateDao.findRoutingTemplate(); VMTemplateVO defaultBuiltin = _templateDao.findDefaultBuiltinTemplate(); if (rtngTmplt != null && !allTemplates.contains(rtngTmplt)) allTemplates.add(rtngTmplt); if (defaultBuiltin != null && !allTemplates.contains(defaultBuiltin)) { allTemplates.add(defaultBuiltin); } for (Iterator<VMTemplateVO> i = allTemplates.iterator();i.hasNext();) { if (i.next().getName().startsWith("xs-tools")) { i.remove(); } } toBeDownloaded.addAll(allTemplates); for (VMTemplateVO tmplt: allTemplates) { String uniqueName = tmplt.getUniqueName(); VMTemplateHostVO tmpltHost = _vmTemplateHostDao.findByHostTemplate(sserverId, tmplt.getId()); if (templateInfo.containsKey(uniqueName)) { toBeDownloaded.remove(tmplt); if (tmpltHost != null) { s_logger.info("Template Sync found " + uniqueName + " already in the template host table"); if (tmpltHost.getDownloadState() != Status.DOWNLOADED) { tmpltHost.setErrorString(""); } tmpltHost.setDownloadPercent(100); tmpltHost.setDownloadState(Status.DOWNLOADED); tmpltHost.setInstallPath(templateInfo.get(uniqueName).getInstallPath()); tmpltHost.setSize(templateInfo.get(uniqueName).getSize()); tmpltHost.setLastUpdated(new Date()); _vmTemplateHostDao.update(tmpltHost.getId(), tmpltHost); } else { tmpltHost = new VMTemplateHostVO(sserverId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, templateInfo.get(uniqueName).getInstallPath(), tmplt.getUrl()); tmpltHost.setSize(templateInfo.get(uniqueName).getSize()); _vmTemplateHostDao.persist(tmpltHost); } templateInfo.remove(uniqueName); continue; } if (tmpltHost != null && tmpltHost.getDownloadState() != Status.DOWNLOADED) { s_logger.info("Template Sync did not find " + uniqueName + " ready on server " + sserverId + ", will request download to start/resume shortly"); } else if (tmpltHost == null) { s_logger.info("Template Sync did not find " + uniqueName + " on the server " + sserverId + ", will request download shortly"); VMTemplateHostVO templtHost = new VMTemplateHostVO(sserverId, tmplt.getId(), new Date(), 0, Status.NOT_DOWNLOADED, null, null, null, null, tmplt.getUrl()); _vmTemplateHostDao.persist(templtHost); } } if (toBeDownloaded.size() > 0) { HostVO sserver = _serverDao.findById(sserverId); if (sserver == null) { throw new CloudRuntimeException("Unable to find host from id"); } for (VMTemplateVO tmplt: toBeDownloaded) { s_logger.debug("Template " + tmplt.getName() + " needs to be downloaded to " + sserver.getName()); downloadTemplateToStorage(tmplt, sserver); } } for (String uniqueName: templateInfo.keySet()) { TemplateInfo tInfo = templateInfo.get(uniqueName); DeleteTemplateCommand dtCommand = new DeleteTemplateCommand(tInfo.getInstallPath()); long result = send(sserverId, dtCommand, null); if (result == -1 ){ String description = "Failed to delete " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " which isn't in the database"; logEvent(1L, EventTypes.EVENT_TEMPLATE_DELETE, description , EventVO.LEVEL_ERROR); s_logger.error(description); return; } String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " since it isn't in the database, result=" + result; logEvent(1L, EventTypes.EVENT_TEMPLATE_DELETE, description, EventVO.LEVEL_INFO); s_logger.info(description); } } @Override public void cancelAllDownloads(Long templateId) { List<VMTemplateHostVO> downloadsInProgress = _vmTemplateHostDao.listByTemplateStates(templateId, VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS, VMTemplateHostVO.Status.NOT_DOWNLOADED); if (downloadsInProgress.size() > 0){ for (VMTemplateHostVO vmthvo: downloadsInProgress) { DownloadListener dl = _listenerMap.get(vmthvo); if (dl != null) { dl.abandon(); s_logger.info("Stopping download of template " + templateId + " to storage server " + vmthvo.getHostId()); } } } } private Long getMaxTemplateSizeInBytes() { try { return Long.parseLong(_configDao.getValue("max.template.iso.size")) * 1024L * 1024L * 1024L; } catch (NumberFormatException e) { return null; } } }
server/src/com/cloud/storage/download/DownloadMonitorImpl.java
/** * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. * * This software is licensed under the GNU General Public License v3 or later. * * It 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 any later version. * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.cloud.storage.download; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.concurrent.ConcurrentHashMap; import javax.ejb.Local; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.Command; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DownloadCommand; import com.cloud.agent.api.storage.DownloadProgressCommand; import com.cloud.agent.api.storage.DownloadProgressCommand.RequestType; import com.cloud.async.AsyncInstanceCreateStatus; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.event.EventTypes; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.Type; import com.cloud.storage.StoragePoolHostVO; import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.template.TemplateConstants; import com.cloud.storage.template.TemplateInfo; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.State; import com.cloud.vm.dao.SecondaryStorageVmDao; /** * @author chiradeep * */ @Local(value={DownloadMonitor.class}) public class DownloadMonitorImpl implements DownloadMonitor { static final Logger s_logger = Logger.getLogger(DownloadMonitorImpl.class); private static final String DEFAULT_HTTP_COPY_PORT = "80"; private String _hyperVisorType; @Inject VMTemplateHostDao _vmTemplateHostDao; @Inject VMTemplatePoolDao _vmTemplatePoolDao; @Inject StoragePoolHostDao _poolHostDao; @Inject SecondaryStorageVmDao _secStorageVmDao; @Inject HostDao _serverDao = null; @Inject private final DataCenterDao _dcDao = null; @Inject VMTemplateDao _templateDao = null; @Inject private final EventDao _eventDao = null; @Inject private AgentManager _agentMgr; @Inject ConfigurationDao _configDao; private String _name; private Boolean _sslCopy = new Boolean(false); private String _copyAuthPasswd; Timer _timer; final Map<VMTemplateHostVO, DownloadListener> _listenerMap = new ConcurrentHashMap<VMTemplateHostVO, DownloadListener>(); public long send(Long hostId, Command cmd, Listener listener) { return _agentMgr.gatherStats(hostId, cmd, listener); } public void logEvent(long accountId, String evtType, String description, String level) { EventVO event = new EventVO(); event.setUserId(1); event.setAccountId(accountId); event.setType(evtType); event.setDescription(description); event.setLevel(level); _eventDao.persist(event); } @Override public boolean configure(String name, Map<String, Object> params) { _name = name; final Map<String, String> configs = _configDao.getConfiguration("ManagementServer", params); _sslCopy = Boolean.parseBoolean(configs.get("secstorage.encrypt.copy")); String cert = configs.get("secstorage.secure.copy.cert"); if ("realhostip.com".equalsIgnoreCase(cert)) { s_logger.warn("Only realhostip.com ssl cert is supported, ignoring self-signed and other certs"); } _hyperVisorType = _configDao.getValue("hypervisor.type"); _copyAuthPasswd = configs.get("secstorage.copy.password"); _agentMgr.registerForHostEvents(new DownloadListener(this), true, false, false); return true; } @Override public String getName() { return _name; } @Override public boolean start() { _timer = new Timer(); return true; } @Override public boolean stop() { return true; } public boolean isTemplateUpdateable(Long templateId) { List<VMTemplateHostVO> downloadsInProgress = _vmTemplateHostDao.listByTemplateStatus(templateId, VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS); return (downloadsInProgress.size() == 0); } public boolean isTemplateUpdateable(Long templateId, Long datacenterId) { List<VMTemplateHostVO> downloadsInProgress = _vmTemplateHostDao.listByTemplateStatus(templateId, datacenterId, VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS); return (downloadsInProgress.size() == 0); } public void copyTemplate(VMTemplateVO template, HostVO sourceServer, HostVO destServer) throws InvalidParameterValueException, StorageUnavailableException{ boolean downloadJobExists = false; VMTemplateHostVO destTmpltHost = null; VMTemplateHostVO srcTmpltHost = null; srcTmpltHost = _vmTemplateHostDao.findByHostTemplate(sourceServer.getId(), template.getId()); if (srcTmpltHost == null) { throw new InvalidParameterValueException("Template " + template.getName() + " not associated with " + sourceServer.getName()); } String url = generateCopyUrl(sourceServer, srcTmpltHost); if (url == null) { s_logger.warn("Unable to start/resume copy of template " + template.getUniqueName() + " to " + destServer.getName() + ", no secondary storage vm in running state in source zone"); throw new StorageUnavailableException("No secondary VM in running state in zone " + sourceServer.getDataCenterId()); } destTmpltHost = _vmTemplateHostDao.findByHostTemplate(destServer.getId(), template.getId()); if (destTmpltHost == null) { destTmpltHost = new VMTemplateHostVO(destServer.getId(), template.getId(), new Date(), 0, VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, "jobid0000", null, url); destTmpltHost.setCopy(true); _vmTemplateHostDao.persist(destTmpltHost); } else if ((destTmpltHost.getJobId() != null) && (destTmpltHost.getJobId().length() > 2)) { downloadJobExists = true; } Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes(); if(destTmpltHost != null) { start(); DownloadCommand dcmd = new DownloadCommand(url, template.getUniqueName(), template.getFormat(), template.isRequiresHvm(), template.getAccountId(), template.getId(), template.getDisplayText(), template.getChecksum(), TemplateConstants.DEFAULT_HTTP_AUTH_USER, _copyAuthPasswd, maxTemplateSizeInBytes); DownloadListener dl = downloadJobExists?_listenerMap.get(destTmpltHost):null; if (dl == null) { dl = new DownloadListener(destServer, template, _timer, _vmTemplateHostDao, destTmpltHost.getId(), this, dcmd); } if (downloadJobExists) { dcmd = new DownloadProgressCommand(dcmd, destTmpltHost.getJobId(), RequestType.GET_OR_RESTART); dl.setCurrState(destTmpltHost.getDownloadState()); } _listenerMap.put(destTmpltHost, dl); long result = send(destServer.getId(), dcmd, dl); if (result == -1) { s_logger.warn("Unable to start /resume COPY of template " + template.getUniqueName() + " to " + destServer.getName()); dl.setDisconnected(); dl.scheduleStatusCheck(RequestType.GET_OR_RESTART); } } } private String generateCopyUrl(String ipAddress, String path){ String hostname = ipAddress; String scheme = "http"; if (_sslCopy) { hostname = ipAddress.replace(".", "-"); hostname = hostname + ".realhostip.com"; scheme = "https"; } return scheme + "://" + hostname + "/copy/" + path; } private String generateCopyUrl(HostVO sourceServer, VMTemplateHostVO srcTmpltHost) { List<SecondaryStorageVmVO> ssVms = _secStorageVmDao.getSecStorageVmListInStates(sourceServer.getDataCenterId(), State.Running); if (ssVms.size() > 0) { SecondaryStorageVmVO ssVm = ssVms.get(0); if (ssVm.getPublicIpAddress() == null) { s_logger.warn("A running secondary storage vm has a null public ip?"); return null; } return generateCopyUrl(ssVm.getPublicIpAddress(), srcTmpltHost.getInstallPath()); } /*No secondary storage vm yet*/ if (_hyperVisorType.equalsIgnoreCase("KVM")) { return "file://" + sourceServer.getParent() + "/" + srcTmpltHost.getInstallPath(); } return null; } private void downloadTemplateToStorage(VMTemplateVO template, HostVO sserver) { boolean downloadJobExists = false; VMTemplateHostVO vmTemplateHost = null; vmTemplateHost = _vmTemplateHostDao.findByHostTemplate(sserver.getId(), template.getId()); if (vmTemplateHost == null) { vmTemplateHost = new VMTemplateHostVO(sserver.getId(), template.getId(), new Date(), 0, VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED, null, null, "jobid0000", null, template.getUrl()); _vmTemplateHostDao.persist(vmTemplateHost); } else if ((vmTemplateHost.getJobId() != null) && (vmTemplateHost.getJobId().length() > 2)) { downloadJobExists = true; } Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes(); if(vmTemplateHost != null) { start(); DownloadCommand dcmd = new DownloadCommand(template, maxTemplateSizeInBytes); dcmd.setUrl(vmTemplateHost.getDownloadUrl()); if (vmTemplateHost.isCopy()) { dcmd.setCreds(TemplateConstants.DEFAULT_HTTP_AUTH_USER, _copyAuthPasswd); } DownloadListener dl = new DownloadListener(sserver, template, _timer, _vmTemplateHostDao, vmTemplateHost.getId(), this, dcmd); if (downloadJobExists) { dcmd = new DownloadProgressCommand(dcmd, vmTemplateHost.getJobId(), RequestType.GET_OR_RESTART); dl.setCurrState(vmTemplateHost.getDownloadState()); } _listenerMap.put(vmTemplateHost, dl); long result = send(sserver.getId(), dcmd, dl); if (result == -1) { s_logger.warn("Unable to start /resume download of template " + template.getUniqueName() + " to " + sserver.getName()); dl.setDisconnected(); dl.scheduleStatusCheck(RequestType.GET_OR_RESTART); } } } @Override public boolean downloadTemplateToStorage(Long templateId, Long zoneId) { if (isTemplateUpdateable(templateId)) { List<DataCenterVO> dcs = new ArrayList<DataCenterVO>(); if (zoneId == null) { dcs.addAll(_dcDao.listAllIncludingRemoved()); } else { dcs.add(_dcDao.findById(zoneId)); } for (DataCenterVO dc: dcs) { initiateTemplateDownload(templateId, dc.getId()); } return true; } else { return false; } } private void initiateTemplateDownload(Long templateId, Long dataCenterId) { VMTemplateVO template = _templateDao.findById(templateId); if (template != null && (template.getUrl() != null)) { //find all storage hosts and tell them to initiate download List<HostVO> storageServers = _serverDao.listByTypeDataCenter(Host.Type.SecondaryStorage, dataCenterId); for (HostVO sserver: storageServers) { downloadTemplateToStorage(template, sserver); } } } public void handleDownloadEvent(HostVO host, VMTemplateVO template, Status dnldStatus) { if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) || (dnldStatus==Status.ABANDONED)){ VMTemplateHostVO vmTemplateHost = new VMTemplateHostVO(host.getId(), template.getId()); DownloadListener oldListener = _listenerMap.get(vmTemplateHost); if (oldListener != null) { _listenerMap.remove(vmTemplateHost); } } if (dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED) { logEvent(template.getAccountId(), EventTypes.EVENT_TEMPLATE_DOWNLOAD_SUCCESS, template.getName() + " successfully downloaded to storage server " + host.getName(), EventVO.LEVEL_INFO); } if (dnldStatus == Status.DOWNLOAD_ERROR) { logEvent(template.getAccountId(), EventTypes.EVENT_TEMPLATE_DOWNLOAD_FAILED, template.getName() + " failed to download to storage server " + host.getName(), EventVO.LEVEL_ERROR); } if (dnldStatus == Status.ABANDONED) { logEvent(template.getAccountId(), EventTypes.EVENT_TEMPLATE_DOWNLOAD_FAILED, template.getName() + " :aborted download to storage server " + host.getName(), EventVO.LEVEL_WARN); } VMTemplateHostVO vmTemplateHost = _vmTemplateHostDao.findByHostTemplate(host.getId(), template.getId()); if (dnldStatus == Status.DOWNLOADED) { long size = -1; if(vmTemplateHost!=null){ size = vmTemplateHost.getSize(); } else{ s_logger.warn("Failed to get size for template" + template.getName()); } String eventParams = "id=" + template.getId() + "\ndcId="+host.getDataCenterId()+"\nsize="+size; EventVO event = new EventVO(); event.setUserId(1L); event.setAccountId(template.getAccountId()); if((template.getFormat()).equals(ImageFormat.ISO)){ event.setType(EventTypes.EVENT_ISO_CREATE); event.setDescription("Successfully created ISO " + template.getName()); } else{ event.setType(EventTypes.EVENT_TEMPLATE_CREATE); event.setDescription("Successfully created template " + template.getName()); } event.setParameters(eventParams); event.setLevel(EventVO.LEVEL_INFO); _eventDao.persist(event); } if (vmTemplateHost != null) { Long poolId = vmTemplateHost.getPoolId(); if (poolId != null) { VMTemplateStoragePoolVO vmTemplatePool = _vmTemplatePoolDao.findByPoolTemplate(poolId, template.getId()); StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(poolId, host.getId()); if (vmTemplatePool != null && poolHost != null) { vmTemplatePool.setDownloadPercent(vmTemplateHost.getDownloadPercent()); vmTemplatePool.setDownloadState(vmTemplateHost.getDownloadState()); vmTemplatePool.setErrorString(vmTemplateHost.getErrorString()); String localPath = poolHost.getLocalPath(); String installPath = vmTemplateHost.getInstallPath(); if (installPath != null) { if (!installPath.startsWith("/")) { installPath = "/" + installPath; } if (!(localPath == null) && !installPath.startsWith(localPath)) { localPath = localPath.replaceAll("/\\p{Alnum}+/*$", ""); //remove instance if necessary } if (!(localPath == null) && installPath.startsWith(localPath)) { installPath = installPath.substring(localPath.length()); } } vmTemplatePool.setInstallPath(installPath); vmTemplatePool.setLastUpdated(vmTemplateHost.getLastUpdated()); vmTemplatePool.setJobId(vmTemplateHost.getJobId()); vmTemplatePool.setLocalDownloadPath(vmTemplateHost.getLocalDownloadPath()); _vmTemplatePoolDao.update(vmTemplatePool.getId(),vmTemplatePool); } } } } @Override public void handleTemplateSync(long sserverId, Map<String, TemplateInfo> templateInfo) { HostVO storageHost = _serverDao.findById(sserverId); if (storageHost == null) { s_logger.warn("Huh? Agent id " + sserverId + " does not correspond to a row in hosts table?"); return; } Set<VMTemplateVO> toBeDownloaded = new HashSet<VMTemplateVO>(); List<VMTemplateVO> allTemplates = _templateDao.listAllInZone(storageHost.getDataCenterId()); VMTemplateVO rtngTmplt = _templateDao.findRoutingTemplate(); VMTemplateVO defaultBuiltin = _templateDao.findDefaultBuiltinTemplate(); if (rtngTmplt != null && !allTemplates.contains(rtngTmplt)) allTemplates.add(rtngTmplt); if (defaultBuiltin != null && !allTemplates.contains(defaultBuiltin)) { allTemplates.add(defaultBuiltin); } for (Iterator<VMTemplateVO> i = allTemplates.iterator();i.hasNext();) { if (i.next().getName().startsWith("xs-tools")) { i.remove(); } } toBeDownloaded.addAll(allTemplates); for (VMTemplateVO tmplt: allTemplates) { String uniqueName = tmplt.getUniqueName(); VMTemplateHostVO tmpltHost = _vmTemplateHostDao.findByHostTemplate(sserverId, tmplt.getId()); if (templateInfo.containsKey(uniqueName)) { toBeDownloaded.remove(tmplt); if (tmpltHost != null) { s_logger.info("Template Sync found " + uniqueName + " already in the template host table"); if (tmpltHost.getDownloadState() != Status.DOWNLOADED) { tmpltHost.setErrorString(""); } tmpltHost.setDownloadPercent(100); tmpltHost.setDownloadState(Status.DOWNLOADED); tmpltHost.setInstallPath(templateInfo.get(uniqueName).getInstallPath()); tmpltHost.setSize(templateInfo.get(uniqueName).getSize()); tmpltHost.setLastUpdated(new Date()); _vmTemplateHostDao.update(tmpltHost.getId(), tmpltHost); } else { tmpltHost = new VMTemplateHostVO(sserverId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, templateInfo.get(uniqueName).getInstallPath(), tmplt.getUrl()); tmpltHost.setSize(templateInfo.get(uniqueName).getSize()); _vmTemplateHostDao.persist(tmpltHost); } templateInfo.remove(uniqueName); continue; } if (tmpltHost != null && tmpltHost.getDownloadState() != Status.DOWNLOADED) { s_logger.info("Template Sync did not find " + uniqueName + " ready on server " + sserverId + ", will request download to start/resume shortly"); } else if (tmpltHost == null) { s_logger.info("Template Sync did not find " + uniqueName + " on the server " + sserverId + ", will request download shortly"); VMTemplateHostVO templtHost = new VMTemplateHostVO(sserverId, tmplt.getId(), new Date(), 0, Status.NOT_DOWNLOADED, null, null, null, null, tmplt.getUrl()); _vmTemplateHostDao.persist(templtHost); } } if (toBeDownloaded.size() > 0) { HostVO sserver = _serverDao.findById(sserverId); if (sserver == null) { throw new CloudRuntimeException("Unable to find host from id"); } for (VMTemplateVO tmplt: toBeDownloaded) { s_logger.debug("Template " + tmplt.getName() + " needs to be downloaded to " + sserver.getName()); downloadTemplateToStorage(tmplt, sserver); } } for (String uniqueName: templateInfo.keySet()) { TemplateInfo tInfo = templateInfo.get(uniqueName); DeleteTemplateCommand dtCommand = new DeleteTemplateCommand(tInfo.getInstallPath()); long result = send(sserverId, dtCommand, null); String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " since it isn't in the database, result=" + result; logEvent(1L, EventTypes.EVENT_TEMPLATE_DELETE, description, EventVO.LEVEL_INFO); s_logger.info("Deleted template " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " since it isn't in the database, result=" + result); } } @Override public void cancelAllDownloads(Long templateId) { List<VMTemplateHostVO> downloadsInProgress = _vmTemplateHostDao.listByTemplateStates(templateId, VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS, VMTemplateHostVO.Status.NOT_DOWNLOADED); if (downloadsInProgress.size() > 0){ for (VMTemplateHostVO vmthvo: downloadsInProgress) { DownloadListener dl = _listenerMap.get(vmthvo); if (dl != null) { dl.abandon(); s_logger.info("Stopping download of template " + templateId + " to storage server " + vmthvo.getHostId()); } } } } private Long getMaxTemplateSizeInBytes() { try { return Long.parseLong(_configDao.getValue("max.template.iso.size")) * 1024L * 1024L * 1024L; } catch (NumberFormatException e) { return null; } } }
bug 4144: : send an Alert when template sync deletes a template from the secondary storage due to no record of the template in the db. status 4144: resolved fixed
server/src/com/cloud/storage/download/DownloadMonitorImpl.java
bug 4144: : send an Alert when template sync deletes a template from the secondary storage due to no record of the template in the db. status 4144: resolved fixed
<ide><path>erver/src/com/cloud/storage/download/DownloadMonitorImpl.java <ide> TemplateInfo tInfo = templateInfo.get(uniqueName); <ide> DeleteTemplateCommand dtCommand = new DeleteTemplateCommand(tInfo.getInstallPath()); <ide> long result = send(sserverId, dtCommand, null); <add> if (result == -1 ){ <add> String description = "Failed to delete " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " which isn't in the database"; <add> logEvent(1L, EventTypes.EVENT_TEMPLATE_DELETE, description , EventVO.LEVEL_ERROR); <add> s_logger.error(description); <add> return; <add> } <ide> String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " since it isn't in the database, result=" + result; <ide> logEvent(1L, EventTypes.EVENT_TEMPLATE_DELETE, description, EventVO.LEVEL_INFO); <del> s_logger.info("Deleted template " + tInfo.getTemplateName() + " on secondary storage " + sserverId + " since it isn't in the database, result=" + result); <add> s_logger.info(description); <ide> <ide> } <ide>
Java
unlicense
error: pathspec 'src/test/java/laboratory/jdk/java/lang/ThreadTest.java' did not match any file(s) known to git
ccd9b505aaace547d56f3173f2f15ae15c55a24f
1
noritersand/laboratory,noritersand/laboratory,noritersand/laboratory
package laboratory.jdk.java.lang; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @since 2017-07-05 * @author fixalot */ public class ThreadTest { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(ThreadTest.class); public static void main(String[] args) { Thread thread = new Thread() { public void run() { logger.debug("i'm thread!"); } }; thread.start(); } @Test public void createThread() { logger.debug("i'm createThread!"); // XXX 이 줄이 없으면 쓰레드 내의 logger 작동하지 않음. 이상하드아 Thread thread = new Thread() { public void run() { logger.debug("i'm run!"); } }; thread.start(); } }
src/test/java/laboratory/jdk/java/lang/ThreadTest.java
Signed-off-by: noritersand <[email protected]>
src/test/java/laboratory/jdk/java/lang/ThreadTest.java
<ide><path>rc/test/java/laboratory/jdk/java/lang/ThreadTest.java <add>package laboratory.jdk.java.lang; <add> <add>import org.junit.Test; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add> <add>/** <add> * @since 2017-07-05 <add> * @author fixalot <add> */ <add>public class ThreadTest { <add> @SuppressWarnings("unused") <add> private static final Logger logger = LoggerFactory.getLogger(ThreadTest.class); <add> <add> public static void main(String[] args) { <add> Thread thread = new Thread() { <add> public void run() { <add> logger.debug("i'm thread!"); <add> } <add> }; <add> thread.start(); <add> } <add> <add> @Test <add> public void createThread() { <add> logger.debug("i'm createThread!"); // XXX 이 줄이 없으면 쓰레드 내의 logger 작동하지 않음. 이상하드아 <add> Thread thread = new Thread() { <add> public void run() { <add> logger.debug("i'm run!"); <add> } <add> }; <add> thread.start(); <add> } <add>}
Java
apache-2.0
9b9762454b3537ffe4cd709b9b62e3bd52f8c5a2
0
Addepar/buck,Addepar/buck,kageiit/buck,JoelMarcey/buck,zpao/buck,romanoid/buck,SeleniumHQ/buck,romanoid/buck,romanoid/buck,kageiit/buck,JoelMarcey/buck,JoelMarcey/buck,nguyentruongtho/buck,rmaz/buck,facebook/buck,JoelMarcey/buck,romanoid/buck,rmaz/buck,JoelMarcey/buck,SeleniumHQ/buck,JoelMarcey/buck,Addepar/buck,SeleniumHQ/buck,SeleniumHQ/buck,zpao/buck,romanoid/buck,rmaz/buck,Addepar/buck,romanoid/buck,rmaz/buck,SeleniumHQ/buck,facebook/buck,SeleniumHQ/buck,SeleniumHQ/buck,SeleniumHQ/buck,kageiit/buck,Addepar/buck,romanoid/buck,facebook/buck,Addepar/buck,rmaz/buck,JoelMarcey/buck,Addepar/buck,romanoid/buck,rmaz/buck,nguyentruongtho/buck,zpao/buck,JoelMarcey/buck,rmaz/buck,romanoid/buck,JoelMarcey/buck,Addepar/buck,rmaz/buck,romanoid/buck,rmaz/buck,facebook/buck,rmaz/buck,facebook/buck,nguyentruongtho/buck,Addepar/buck,zpao/buck,kageiit/buck,SeleniumHQ/buck,Addepar/buck,SeleniumHQ/buck,zpao/buck,Addepar/buck,Addepar/buck,nguyentruongtho/buck,rmaz/buck,JoelMarcey/buck,nguyentruongtho/buck,JoelMarcey/buck,SeleniumHQ/buck,nguyentruongtho/buck,SeleniumHQ/buck,rmaz/buck,JoelMarcey/buck,romanoid/buck,rmaz/buck,kageiit/buck,Addepar/buck,kageiit/buck,zpao/buck,romanoid/buck,SeleniumHQ/buck,romanoid/buck,facebook/buck,kageiit/buck,facebook/buck,zpao/buck,JoelMarcey/buck,nguyentruongtho/buck
/* * Copyright 2015-present Facebook, 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.facebook.buck.intellij.ideabuck.lang; import com.intellij.openapi.fileTypes.ExactFileNameMatcher; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import org.jetbrains.annotations.NotNull; public class BuckFileTypeFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) { fileTypeConsumer.consume( BuckFileType.INSTANCE, new ExactFileNameMatcher(BuckFileType.DEFAULT_FILENAME), new ExtensionFileNameMatcher(BuckFileType.DEFAULT_FILENAME), new ExtensionFileNameMatcher(BuckFileType.DEFAULT_EXTENSION)); } }
tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/lang/BuckFileTypeFactory.java
/* * Copyright 2015-present Facebook, 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.facebook.buck.intellij.ideabuck.lang; import com.intellij.openapi.fileTypes.ExactFileNameMatcher; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import org.jetbrains.annotations.NotNull; public class BuckFileTypeFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) { fileTypeConsumer.consume( BuckFileType.INSTANCE, new ExactFileNameMatcher(BuckFileType.DEFAULT_FILENAME), new ExtensionFileNameMatcher(BuckFileType.DEFAULT_EXTENSION)); } }
Associate *.BUCK files with ideabuck plugin, fixing integration tests Summary: Integration tests contain test.BUCK files as testdata, tests were failing because files weren't being associated with the plugin automatically. We could change the testdata but we might as well just support BUCK as a file extension. Reviewed By: mkillianey fbshipit-source-id: ee038ed9cd
tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/lang/BuckFileTypeFactory.java
Associate *.BUCK files with ideabuck plugin, fixing integration tests
<ide><path>ools/ideabuck/src/com/facebook/buck/intellij/ideabuck/lang/BuckFileTypeFactory.java <ide> fileTypeConsumer.consume( <ide> BuckFileType.INSTANCE, <ide> new ExactFileNameMatcher(BuckFileType.DEFAULT_FILENAME), <add> new ExtensionFileNameMatcher(BuckFileType.DEFAULT_FILENAME), <ide> new ExtensionFileNameMatcher(BuckFileType.DEFAULT_EXTENSION)); <ide> } <ide> }
Java
apache-2.0
6d69276ee8a564e501f8eafe4646b25430c6fa01
0
ysc/word,ysc/word
/** * * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, [email protected] * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.apdplat.word.vector; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 计算词和词的相似性 * @author 杨尚川 */ public class Distance { private static final Logger LOGGER = LoggerFactory.getLogger(Distance.class); public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, IOException{ String model = "target/vector.txt"; String encoding = "gbk"; if(args.length == 1){ model = args[0]; } if(args.length == 2){ model = args[0]; encoding = args[1]; } Map<String, String> map = new HashMap<>(); LOGGER.info("开始初始化模型"); try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(model),"utf-8"))){ String line = null; while((line = reader.readLine()) != null){ String[] attr = line.split(" : "); if(attr==null || attr.length != 2){ LOGGER.error("错误数据:"+line); continue; } String key = attr[0]; String value = attr[1]; value = value.substring(1, value.length()-1); map.put(key, value); } } LOGGER.info("模型初始化完成"); LOGGER.info("输入要查询的词或(exit)命令离开:"); try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){ String line = null; while((line = reader.readLine()) != null){ if("exit".equals(line)){ return; } String value = map.get(line); if(value == null){ LOGGER.info("没有对应的词:"+line); }else{ LOGGER.info(line+":"); LOGGER.info("----------------------------------------------------------"); List<String> list = distance(map, value, 15); for(String element : list){ LOGGER.info("\t"+element); } LOGGER.info("----------------------------------------------------------"); } } } } private static List<String> distance(Map<String, String> map, String words, int limit){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("计算词向量:" + words); LOGGER.debug("限制结果数目:" + limit); } Map<String, Float> wordVec = new HashMap<>(); String[] ws = words.split(", "); for(String w : ws){ String[] attr = w.split(" "); String k = attr[0]; float v = Float.parseFloat(attr[1]); wordVec.put(k, v); } Map<String, Float> result = new HashMap<>(); float max=0; for(String key : map.keySet()){ //词向量 String value = map.get(key); String[] elements = value.split(", "); Map<String, Float> vec = new HashMap<>(); for(String element : elements){ String[] attr = element.split(" "); String k = attr[0]; float v = Float.parseFloat(attr[1]); vec.put(k, v); } //计算距离 float score=0; int times=0; for(String out : wordVec.keySet()){ for(String in : vec.keySet()){ if(out.equals(in)){ //有交集 score += wordVec.get(out) * vec.get(in); times++; } } } //忽略没有交集的词 if(score > 0){ score *= times; result.put(key, score); if(score > max){ max = score; } } } if(max == 0){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("没有相似词"); } return Collections.emptyList(); } if(LOGGER.isDebugEnabled()) { LOGGER.debug("最大分值:" + max); LOGGER.debug("相似词数:" + result.size()); } //分值归一化 for(String key : result.keySet()){ float value = result.get(key); value /= max; result.put(key, value); } //按分值排序 List<Entry<String, Float>> list = result.entrySet().parallelStream().sorted((a,b)->b.getValue().compareTo(a.getValue())).collect(Collectors.toList()); //限制结果数目 if(limit > list.size()){ limit = list.size(); } //转换为字符串 List<String> retValue = new ArrayList<>(limit); for(int i=0; i< limit; i++){ retValue.add(list.get(i).getKey()+" "+list.get(i).getValue()); } return retValue; } }
src/main/java/org/apdplat/word/vector/Distance.java
/** * * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, [email protected] * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.apdplat.word.vector; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apdplat.word.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 计算词和词的相似性 * @author 杨尚川 */ public class Distance { private static final Logger LOGGER = LoggerFactory.getLogger(Distance.class); public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, IOException{ String model = "target/vector.txt"; String encoding = "gbk"; if(args.length == 1){ model = args[0]; } if(args.length == 2){ model = args[0]; encoding = args[1]; } Map<String, String> map = new HashMap<>(); LOGGER.info("开始初始化模型"); try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(model),"utf-8"))){ String line = null; while((line = reader.readLine()) != null){ String[] attr = line.split(" : "); if(attr==null || attr.length != 2){ LOGGER.error("错误数据:"+line); continue; } String key = attr[0]; String value = attr[1]; value = value.substring(1, value.length()-1); map.put(key, value); } } LOGGER.info("模型初始化完成"); LOGGER.info("输入要查询的词或(exit)命令离开:"); try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){ String line = null; while((line = reader.readLine()) != null){ if("exit".equals(line)){ return; } String value = map.get(line); if(value == null){ LOGGER.info("没有对应的词:"+line); }else{ LOGGER.info(line+":"); LOGGER.info("----------------------------------------------------------"); List<String> list = distance(map, value, 15); for(String element : list){ LOGGER.info("\t"+element); } LOGGER.info("----------------------------------------------------------"); } } } } private static List<String> distance(Map<String, String> map, String words, int limit){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("计算词向量:" + words); LOGGER.debug("限制结果数目:" + limit); } Map<String, Float> wordVec = new HashMap<>(); String[] ws = words.split(", "); for(String w : ws){ String[] attr = w.split(" "); String k = attr[0]; float v = Float.parseFloat(attr[1]); wordVec.put(k, v); } Map<String, Float> result = new HashMap<>(); float max=0; for(String key : map.keySet()){ //词向量 String value = map.get(key); String[] elements = value.split(", "); Map<String, Float> vec = new HashMap<>(); for(String element : elements){ String[] attr = element.split(" "); String k = attr[0]; float v = Float.parseFloat(attr[1]); vec.put(k, v); } //计算距离 float score=0; int times=0; for(String out : wordVec.keySet()){ for(String in : vec.keySet()){ if(out.equals(in)){ //有交集 score += wordVec.get(out) * vec.get(in); times++; } } } //忽略没有交集的词 if(score > 0){ score *= times; result.put(key, score); if(score > max){ max = score; } } } if(max == 0){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("没有相似词"); } return Collections.emptyList(); } if(LOGGER.isDebugEnabled()) { LOGGER.debug("最大分值:" + max); LOGGER.debug("相似词数:" + result.size()); } //分值归一化 for(String key : result.keySet()){ float value = result.get(key); value /= max; result.put(key, value); } //排序 List<Entry<String, Float>> list = Utils.getSortedMapByValue(result); //限制结果数目 if(limit > list.size()){ limit = list.size(); } //转换为字符串 List<String> retValue = new ArrayList<>(limit); for(int i=0; i< limit; i++){ retValue.add(list.get(i).getKey()+" "+list.get(i).getValue()); } return retValue; } }
按分值排序
src/main/java/org/apdplat/word/vector/Distance.java
按分值排序
<ide><path>rc/main/java/org/apdplat/word/vector/Distance.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Map.Entry; <del>import org.apdplat.word.util.Utils; <add>import java.util.stream.Collectors; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> value /= max; <ide> result.put(key, value); <ide> } <del> //排序 <del> List<Entry<String, Float>> list = Utils.getSortedMapByValue(result); <add> //按分值排序 <add> List<Entry<String, Float>> list = result.entrySet().parallelStream().sorted((a,b)->b.getValue().compareTo(a.getValue())).collect(Collectors.toList()); <ide> //限制结果数目 <ide> if(limit > list.size()){ <ide> limit = list.size();
Java
mpl-2.0
50cec01e07aeecd3659c6ba457e239c0c000c3a2
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.jhv.data.guielements.model; import java.util.List; import javax.swing.table.AbstractTableModel; import org.helioviewer.jhv.data.datatype.event.JHVEventParameter; /** * The model for parameter table panel. * * @author Bram Bourgoignie ([email protected]) * */ public class ParameterTableModel extends AbstractTableModel { /** The parameters in this model */ private final List<JHVEventParameter> parameters; /** UID */ private static final long serialVersionUID = 1963880595668739342L; /** * Creates a parameter model for the given parameters. * * @param parameters * the parameters */ public ParameterTableModel(List<JHVEventParameter> parameters) { super(); this.parameters = parameters; } @Override public int getRowCount() { return parameters.size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex < parameters.size()) { if (columnIndex == 0) { return parameters.get(rowIndex).getParameterDisplayName(); } else if (columnIndex == 1) { return parameters.get(rowIndex).getParameterValue(); } else { return null; } } else { return null; } } @Override public String getColumnName(int column) { if (column == 0) { return "Parameter Name"; } else if (column == 1) { return "Value"; } else { return super.getColumnName(column); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 1; } }
src/jhv-data/src/org/helioviewer/jhv/data/guielements/model/ParameterTableModel.java
package org.helioviewer.jhv.data.guielements.model; import java.util.List; import javax.swing.table.AbstractTableModel; import org.helioviewer.jhv.data.datatype.event.JHVEventParameter; /** * The model for parameter table panel. * * @author Bram Bourgoignie ([email protected]) * */ public class ParameterTableModel extends AbstractTableModel { /** The parameters in this model */ private final List<JHVEventParameter> parameters; /** UID */ private static final long serialVersionUID = 1963880595668739342L; /** * Creates a parameter model for the given parameters. * * @param parameters * the parameters */ public ParameterTableModel(List<JHVEventParameter> parameters) { super(); this.parameters = parameters; } @Override public int getRowCount() { return parameters.size(); } @Override public int getColumnCount() { return 2; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex < parameters.size()) { if (columnIndex == 0) { return parameters.get(rowIndex).getParameterDisplayName(); } else if (columnIndex == 1) { return parameters.get(rowIndex).getParameterValue(); } else { return null; } } else { return null; } } @Override public String getColumnName(int column) { if (column == 0) { return "Parameter Name"; } else if (column == 1) { return "Value"; } else { return super.getColumnName(column); } } }
Make cell scrollable and copy text git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@2893 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/jhv-data/src/org/helioviewer/jhv/data/guielements/model/ParameterTableModel.java
Make cell scrollable and copy text
<ide><path>rc/jhv-data/src/org/helioviewer/jhv/data/guielements/model/ParameterTableModel.java <ide> } <ide> } <ide> <add> @Override <add> public boolean isCellEditable(int rowIndex, int columnIndex) { <add> return columnIndex == 1; <add> } <ide> }
Java
apache-2.0
171d48d7c176305f414f5867a44ea24ad523cd01
0
DataONEorg/annotator
package org.dataone.annotator.matcher.esor; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.dataone.annotator.matcher.ConceptItem; import org.dataone.annotator.matcher.ConceptMatcher; import org.dataone.annotator.matcher.QueryItem; import org.json.JSONArray; import org.json.JSONObject; public class EsorService implements ConceptMatcher { private static Log log = LogFactory.getLog(EsorService.class); //private static final String REST_URL = "http://127.0.0.1:9100/search"; //temporary server for testing private static final String REST_URL = "http://dataonetwc.tw.rpi.edu/linkipedia/search"; @Override public List<ConceptItem> getConcepts(String fullText) throws Exception { //merge two results with different escape condition String query = parseTerm(fullText); String escapedSpaceQuery = escapeToSpace(query); String escapedCommaQuery = escapeToComma(query); if(escapedSpaceQuery == escapedCommaQuery){ return lookupEsor(escapedSpaceQuery); }else{ List<ConceptItem> res_escapedSpace = lookupEsor(escapedSpaceQuery); List<ConceptItem> res_escapedComma = lookupEsor(escapedCommaQuery); return mergeRes(res_escapedSpace, res_escapedComma); } //return lookupEsor(fullText); } @Override public List<ConceptItem> getConcepts(Map<String, String> queryItems) throws Exception { StringBuffer sb = new StringBuffer(); for (String value: queryItems.values()) { sb.append(value); sb.append(" "); } //return lookupEsor(sb.toString()); return getConcepts(sb.toString()); } private static List<ConceptItem> lookupEsor(String query) throws Exception { HttpClient client = HttpClients.createDefault(); // remove quotes for now // see: https://github.com/DataONEorg/sem-prov-design/issues/134 //query = query.replaceAll("\"", ""); String uriStr = REST_URL + "?query=" + URLEncoder.encode(query, "UTF-8"); //System.out.println(uriStr); HttpGet method = new HttpGet(uriStr); method.setHeader("Accept", "application/json"); HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); if (2 != code / 100) { throw new Exception("response code " + code + " for resource at " + uriStr); } InputStream body = response.getEntity().getContent(); String jsonStr = IOUtils.toString(body, "UTF-8"); System.out.println(jsonStr); JSONObject json = new JSONObject(jsonStr); //String query = json.getString("query"); JSONArray results = json.getJSONArray("results"); //analysis the result and return ArrayList<ConceptItem> concepts = new ArrayList<ConceptItem>(); for(int i = 0; i < results.length(); i++){ JSONObject r = results.getJSONObject(i); String url = r.getString("url"); String score = r.getString("score"); System.out.println("url=" + url + ", score=" + score); //returned result may be empty if(url.length()>0) { ConceptItem c = new ConceptItem(new URI(url.substring(1, url.length() - 1)), Double.parseDouble(score)); concepts.add(c); }else{ //System.out.println("NA"); } } return concepts; } //escape input query private String parseTerm(String str) throws Exception{ if(str.contains("(")){ str = str.substring(0, str.indexOf("(")); } str = str.replaceAll("\\s+$", ""); str = replaceFromSlashToSpace(replaceFromDotToSpace(replaceFromDashToSpace(str))); str = str.replace("%", " percent"); str = insertSpaceBeforeCapital(str); str = URLEncoder.encode(str, "UTF-8").replaceAll("\\+", "%20"); return str; } private String replaceFromDotToSpace(String str) { return str.replace(".", " "); } private String replaceFromSlashToSpace(String str){ return str.replace("/", " "); } private String insertSpaceBeforeCapital(String str){ char[] charArr = str.toCharArray(); StringBuilder sb = new StringBuilder(); for(int i = 0 ; i < charArr.length; i++){ if(i>0 && charArr[i] >= 'A' && charArr[i] <= 'Z' && charArr[i-1] >= 'a'&& charArr[i-1] <= 'z') sb.append(" "); sb.append(charArr[i]); } return sb.toString(); } private String replaceFromDashToSpace(String original){ return original.replace("_", " "); } private String escapeToSpace(String original){ return original.replace(" ", "%20"); } private String escapeToComma(String original){ return original.replace("%20", ","); } private List<ConceptItem> mergeRes(List<ConceptItem> res_escapedSpace, List<ConceptItem> res_escapedComma) { if(res_escapedSpace.size()==0) return res_escapedComma; if(res_escapedComma.size()==0) return res_escapedSpace; int indexS = 0; int indexC = 0; while(indexS < res_escapedSpace.size()){ if(indexC < res_escapedComma.size() && res_escapedComma.get(indexC).getWeight() >= res_escapedSpace.get(indexS).getWeight()){ res_escapedSpace.add(indexS, res_escapedComma.get(indexC)); indexS++; indexC++; }else{ indexS++; } } for(int i = indexC; i < res_escapedComma.size(); i++ ){ res_escapedSpace.add(res_escapedComma.get(i)); } return res_escapedSpace; } }
src/main/java/org/dataone/annotator/matcher/esor/EsorService.java
package org.dataone.annotator.matcher.esor; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.dataone.annotator.matcher.ConceptItem; import org.dataone.annotator.matcher.ConceptMatcher; import org.dataone.annotator.matcher.QueryItem; import org.json.JSONArray; import org.json.JSONObject; public class EsorService implements ConceptMatcher { private static Log log = LogFactory.getLog(EsorService.class); //private static final String REST_URL = "http://127.0.0.1:9100/search"; //temporary server for testing private static final String REST_URL = "http://dataonetwc.tw.rpi.edu/linkipedia/search"; @Override public List<ConceptItem> getConcepts(String fullText) throws Exception { return lookupEsor(fullText); } @Override public List<ConceptItem> getConcepts(Map<String, String> queryItems) throws Exception { StringBuffer sb = new StringBuffer(); for (String value: queryItems.values()) { sb.append(value); sb.append(" "); } return lookupEsor(sb.toString()); } private static List<ConceptItem> lookupEsor(String query) throws Exception { HttpClient client = HttpClients.createDefault(); // remove quotes for now // see: https://github.com/DataONEorg/sem-prov-design/issues/134 query = query.replaceAll("\"", ""); String uriStr = REST_URL + "?query=" + URLEncoder.encode(query, "UTF-8"); //System.out.println(uriStr); HttpGet method = new HttpGet(uriStr); method.setHeader("Accept", "application/json"); HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); if (2 != code / 100) { throw new Exception("response code " + code + " for resource at " + uriStr); } InputStream body = response.getEntity().getContent(); String jsonStr = IOUtils.toString(body, "UTF-8"); System.out.println(jsonStr); JSONObject json = new JSONObject(jsonStr); //String query = json.getString("query"); JSONArray results = json.getJSONArray("results"); //analysis the result and return ArrayList<ConceptItem> concepts = new ArrayList<ConceptItem>(); for(int i = 0; i < results.length(); i++){ JSONObject r = results.getJSONObject(i); String url = r.getString("url"); String score = r.getString("score"); System.out.println("url=" + url + ", score=" + score); //returned result may be empty if(url.length()>0) { ConceptItem c = new ConceptItem(new URI(url.substring(1, url.length() - 1)), Double.parseDouble(score)); concepts.add(c); }else{ System.out.println("NA"); } } return concepts; } }
fixed the problem of escaping speical charactors, see https://github.com/DataONEorg/sem-prov-design/issues/134
src/main/java/org/dataone/annotator/matcher/esor/EsorService.java
fixed the problem of escaping speical charactors, see https://github.com/DataONEorg/sem-prov-design/issues/134
<ide><path>rc/main/java/org/dataone/annotator/matcher/esor/EsorService.java <ide> <ide> @Override <ide> public List<ConceptItem> getConcepts(String fullText) throws Exception { <del> return lookupEsor(fullText); <add> //merge two results with different escape condition <add> String query = parseTerm(fullText); <add> String escapedSpaceQuery = escapeToSpace(query); <add> String escapedCommaQuery = escapeToComma(query); <add> <add> if(escapedSpaceQuery == escapedCommaQuery){ <add> return lookupEsor(escapedSpaceQuery); <add> }else{ <add> List<ConceptItem> res_escapedSpace = lookupEsor(escapedSpaceQuery); <add> List<ConceptItem> res_escapedComma = lookupEsor(escapedCommaQuery); <add> return mergeRes(res_escapedSpace, res_escapedComma); <add> } <add> <add> //return lookupEsor(fullText); <ide> } <ide> <ide> @Override <ide> sb.append(value); <ide> sb.append(" "); <ide> } <del> return lookupEsor(sb.toString()); <add> //return lookupEsor(sb.toString()); <add> return getConcepts(sb.toString()); <ide> } <ide> <ide> private static List<ConceptItem> lookupEsor(String query) throws Exception { <ide> HttpClient client = HttpClients.createDefault(); <ide> // remove quotes for now <ide> // see: https://github.com/DataONEorg/sem-prov-design/issues/134 <del> query = query.replaceAll("\"", ""); <add> //query = query.replaceAll("\"", ""); <ide> String uriStr = REST_URL + "?query=" + URLEncoder.encode(query, "UTF-8"); <ide> //System.out.println(uriStr); <ide> <ide> ConceptItem c = new ConceptItem(new URI(url.substring(1, url.length() - 1)), Double.parseDouble(score)); <ide> concepts.add(c); <ide> }else{ <del> System.out.println("NA"); <add> //System.out.println("NA"); <ide> } <del> <add> <ide> } <ide> <ide> return concepts; <ide> } <add> <add> <add> //escape input query <add> private String parseTerm(String str) throws Exception{ <add> <add> if(str.contains("(")){ <add> str = str.substring(0, str.indexOf("(")); <add> } <add> <add> str = str.replaceAll("\\s+$", ""); <add> <add> str = replaceFromSlashToSpace(replaceFromDotToSpace(replaceFromDashToSpace(str))); <add> str = str.replace("%", " percent"); <add> str = insertSpaceBeforeCapital(str); <add> str = URLEncoder.encode(str, "UTF-8").replaceAll("\\+", "%20"); <add> return str; <add> } <add> <add> private String replaceFromDotToSpace(String str) { <add> return str.replace(".", " "); <add> } <add> <add> private String replaceFromSlashToSpace(String str){ <add> return str.replace("/", " "); <add> } <add> <add> private String insertSpaceBeforeCapital(String str){ <add> char[] charArr = str.toCharArray(); <add> StringBuilder sb = new StringBuilder(); <add> for(int i = 0 ; i < charArr.length; i++){ <add> if(i>0 && charArr[i] >= 'A' && charArr[i] <= 'Z' && charArr[i-1] >= 'a'&& charArr[i-1] <= 'z') <add> sb.append(" "); <add> sb.append(charArr[i]); <add> } <add> return sb.toString(); <add> } <add> <add> private String replaceFromDashToSpace(String original){ <add> return original.replace("_", " "); <add> } <add> <add> private String escapeToSpace(String original){ <add> return original.replace(" ", "%20"); <add> } <add> <add> private String escapeToComma(String original){ <add> return original.replace("%20", ","); <add> } <add> <add> private List<ConceptItem> mergeRes(List<ConceptItem> res_escapedSpace, List<ConceptItem> res_escapedComma) { <add> if(res_escapedSpace.size()==0) return res_escapedComma; <add> if(res_escapedComma.size()==0) return res_escapedSpace; <add> <add> int indexS = 0; <add> int indexC = 0; <add> while(indexS < res_escapedSpace.size()){ <add> if(indexC < res_escapedComma.size() && res_escapedComma.get(indexC).getWeight() >= res_escapedSpace.get(indexS).getWeight()){ <add> res_escapedSpace.add(indexS, res_escapedComma.get(indexC)); <add> indexS++; <add> indexC++; <add> }else{ <add> indexS++; <add> } <add> } <add> <add> for(int i = indexC; i < res_escapedComma.size(); i++ ){ <add> res_escapedSpace.add(res_escapedComma.get(i)); <add> } <add> <add> return res_escapedSpace; <add> } <ide> }
JavaScript
bsd-3-clause
f2c8f55c943362947394637af7750a44e0cdcae9
0
vivo-project/VIVO,vivo-project/VIVO,vivo-project/VIVO,vivo-project/VIVO
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ $(document).ready(function(){ var globalMapBuilt = false; var countryMapBuilt = false; var localMapBuilt = false; var researchAreas = { "type": "FeatureCollection", "features": []}; $.extend(this, urlsBase); $.extend(this, i18nStrings); $.extend(this, geoResearcherCount); getGeoJsonForMaps(); $('a#globalLink').click(function() { buildGlobalMap(); $(this).addClass("selected"); $('a#countryLink').removeClass("selected"); $('a#nyLink').removeClass("selected"); }); $('a#countryLink').click(function() { buildCountryMap(); $(this).addClass("selected"); $('a#globalLink').removeClass("selected"); $('a#nyLink').removeClass("selected"); }); $('a#localLink').click(function() { buildLocalMap(); $(this).addClass("selected"); $('a#countryLink').removeClass("selected"); $('a#globalLink').removeClass("selected"); }); function getLatLong(country) { var lat = []; latLongJson.map(function (json) { if ( json.name == country) { lat.push(json.data["longitude"]); lat.push(json.data["latitude"]); } }); if (lat.length == 0) { lat.push(0.0); lat.push(0.0); } return(lat); } function getMapType(country) { var mt = ""; latLongJson.map(function (json) { if ( json.name == country) { mt = json.data["mapType"]; } }); return(mt); } function getGeoClass(country) { var gc = ""; latLongJson.map(function (json) { if ( json.name == country) { gc = json.data["geoClass"]; } }); return(gc); } function onEachFeature(feature, layer) { var popupContent = ""; var uri = ""; if (feature.properties && feature.properties.popupContent) { popupContent += feature.properties.popupContent; } if (feature.properties && feature.properties.html) { if ( feature.properties.html == "1") { popupContent += ": " + feature.properties.html + " " + i18nStrings.researcherString; } else { popupContent += ": " + feature.properties.html + " " + i18nStrings.researchersString; } } layer.on('mouseover', function(e) { e.target.bindPopup(popupContent,{closeButton:false}).openPopup(); }); layer.on('mouseout', function(e) { e.target.closePopup(); }); if (feature.properties && feature.properties.uri) { uri += feature.properties.uri; layer.on('click', function(e) { document.location.href = urlsBase + "/individual?uri=" + uri + "&#map"; }); } } function getDivIcon(feature) { var htmlContent = ""; var myIcon; if (feature.properties && feature.properties.html) { htmlContent += feature.properties.html; } if ( htmlContent > 99 ) { myIcon = L.divIcon({className: 'divIconCountPlus', html: htmlContent}); } else { myIcon = L.divIcon({className: 'divIconCount', html: htmlContent}); } return myIcon; } function getMarkerRadius(feature) { var radiusContent; if (feature.properties && feature.properties.radius) { radiusContent = feature.properties.radius; } return radiusContent; } function getMarkerFillColor(feature) { var geoClass = ""; var fillColor; if (feature.properties && feature.properties.radius) { geoClass = feature.properties.geoClass; } if ( geoClass == "region") { fillColor = "#abf7f8"; } else { fillColor = "#fdf9cd" } return fillColor; } function checkGlobalCoordinates(feature, layer) { var theLatLng = new L.LatLng(feature.geometry.coordinates[0],feature.geometry.coordinates[1]); var mt = feature.properties.mapType; if ( !theLatLng.equals([0,0]) && mt == "global" ) { return true; } return false; } function checkCountryCoordinates(feature, layer) { var theLatLng = new L.LatLng(feature.geometry.coordinates[0],feature.geometry.coordinates[1]); var mt = feature.properties.mapType; if ( !theLatLng.equals([0,0]) && mt == "country" ) { return true; } return false; } function checkLocalCoordinates(feature, layer) { var theLatLng = new L.LatLng(feature.geometry.coordinates[0],feature.geometry.coordinates[1]); var mt = feature.properties.mapType; if ( !theLatLng.equals([0,0]) && mt == "local" ) { return true; } return false; } function buildGlobalMap() { $('div#mapGlobal').show(); $('div#mapCountry').hide(); $('div#mapLocal').hide(); if ( !globalMapBuilt ) { var mapGlobal = L.map('mapGlobal').setView([25.25, 23.20], 2); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 12, minZoom: 1, boxZoom: false, doubleClickZoom: false, attribution: 'Tiles &copy; <a href="http://www.esri.com/">Esri</a>' }).addTo(mapGlobal); L.geoJson(researchAreas, { filter: checkGlobalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: getMarkerRadius(feature), fillColor: getMarkerFillColor(feature), color: "none", weight: 1, opacity: 0.8, fillOpacity: 0.8 }); } }).addTo(mapGlobal); L.geoJson(researchAreas, { filter: checkGlobalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.marker(latlng, { icon: getDivIcon(feature) }); } }).addTo(mapGlobal); globalMapBuilt = true; } getResearcherCount("global"); appendLegendToLeafletContainer(); } function buildCountryMap() { $('div#mapGlobal').hide(); $('div#mapLocal').hide(); $('div#mapCountry').show(); if ( !countryMapBuilt ) { // CHANGE THE setView COORDINATES SO THAT THE COUNTRY YOU WANT TO // DISPLAY IS CENTERED CORRECTLY. THE COORDINATES BELOW CENTERS THE MAP ON THE U.S. var mapCountry = L.map('mapCountry').setView([46.0, -97.0], 3); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 30, minZoom: 1, boxZoom: false, zIndex: 1, doubleClickZoom: false, attribution: 'Tiles &copy; <a href="http://www.esri.com/">Esri</a>' }).addTo(mapCountry); L.geoJson(researchAreas, { filter: checkCountryCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: getMarkerRadius(feature), fillColor: "#fdf9cd", //fdf38a", color: "none", weight: 1, opacity: 0.8, fillOpacity: 0.8 }); } }).addTo(mapCountry); L.geoJson(researchAreas, { filter: checkCountryCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.marker(latlng, { icon: getDivIcon(feature) }); } }).addTo(mapCountry); countryMapBuilt = true; } getResearcherCount("country"); } function buildLocalMap() { $('div#mapGlobal').hide(); $('div#mapCountry').hide(); $('div#mapLocal').show(); if ( !localMapBuilt ) { // CHANGE THE setView COORDINATES SO THAT THE LOCAL AREA (E.G. A STATE OR PROVINCE) YOU WANT TO // DISPLAY IS CENTERED CORRECTLY. THE COORDINATES BELOW CENTERS THE MAP ON NEW YORK STATE. var mapLocal = L.map('mapLocal').setView([42.83, -75.50], 7); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 12, minZoom: 1, boxZoom: false, doubleClickZoom: false, attribution: 'Tiles &copy; <a href="http://www.esri.com/">Esri</a>' }).addTo(mapLocal); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places_Alternate/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 12, minZoom: 1, boxZoom: false, doubleClickZoom: false }).addTo(mapLocal); L.geoJson(researchAreas, { filter: checkLocalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: getMarkerRadius(feature) + 3, fillColor: "#fdf9cd", color: "none", weight: 1, opacity: 0.8, fillOpacity: 0.8 }); } }).addTo(mapLocal); L.geoJson(researchAreas, { filter: checkLocalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.marker(latlng, { icon: getDivIcon(feature) }); } }).addTo(mapLocal); localMapBuilt = true; } getResearcherCount("local"); } function getGeoJsonForMaps() { $.ajax({ url: urlsBase + "/homePageAjax", dataType: "json", data: { action: "getGeoFocusLocations", }, complete: function(xhr, status) { var results = $.parseJSON(xhr.responseText); if ( results.length == 0 ) { var html = i18nStrings.currentlyNoResearchers; $('section#home-geo-focus div#timeIndicatorGeo span').html(html); $('section#home-geo-focus').css("height","175px"); $('section#home-geo-focus div#timeIndicator').css("margin-top","50px"); $('section#home-geo-focus div#mapGlobal').hide(); $('section#home-geo-focus div#mapCountry').hide(); $('section#home-geo-focus div#mapLocal').hide(); } else { $.each(results, function() { var locale = this.properties.popupContent; this.geometry.coordinates = getLatLong(locale); this.properties.mapType = getMapType(locale); this.properties.geoClass = getGeoClass(locale); researchAreas["features"].push(this); }); buildGlobalMap(); $('div#timeIndicatorGeo').hide(); } } }); } function getResearcherCount(area) { var researcherCount = this.geoResearcherCount; var areaCount = 0; var text = ""; if ( area == "global" ) { text = " " + i18nStrings.countriesAndRegions; } else if ( area == "country" ) { text = " " + i18nStrings.stateString; } else { text = " " + i18nStrings.statewideLocations; } $.each(researchAreas.features, function() { if ( this.properties.mapType == area ) { areaCount = areaCount + 1; } }); if ( areaCount == 1 && text == " states.") { text = " " + i18nStrings.stateString; } if ( researcherCount == 1 ) { researcherText = " " + i18nStrings.researcherString + " " + i18nStrings.inString; } else { researcherText = " " + i18nStrings.researchersString } $('div#researcherTotal').html("<font style='font-size:1.05em;color:#167093'>" + researcherCount + "</font> " + researcherText + " <font style='font-size:1.05em;color:#167093'>" + areaCount + "</font>" + text); } function appendLegendToLeafletContainer() { var htmlString = "<div class='leaflet-bottom leaflet-left' style='padding:0 0 8px 12px'><ul><li>" + "<img alt='" + i18nStrings.regionsString + "' src='" + urlsBase + "/images/map_legend_countries.png' style='margin-right:5px'><font style='color:#555'>" + i18nStrings.countriesString + "</font></li><li><img alt='" + i18nStrings.regionsString + "' src='" + urlsBase + "/images/map_legend_regions.png' style='margin-right:5px'><font style='color:#555'>" + i18nStrings.regionsString + "</font></li></ul></div>"; $('div.leaflet-control-container').append(htmlString); } });
productMods/js/homePageMaps.js
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ $(document).ready(function(){ var globalMapBuilt = false; var countryMapBuilt = false; var localMapBuilt = false; var researchAreas = { "type": "FeatureCollection", "features": []}; $.extend(this, urlsBase); $.extend(this, i18nStrings); $.extend(this, geoResearcherCount); getGeoJsonForMaps(); $('a#globalLink').click(function() { buildGlobalMap(); $(this).addClass("selected"); $('a#countryLink').removeClass("selected"); $('a#nyLink').removeClass("selected"); }); $('a#countryLink').click(function() { buildCountryMap(); $(this).addClass("selected"); $('a#globalLink').removeClass("selected"); $('a#nyLink').removeClass("selected"); }); $('a#localLink').click(function() { buildLocalMap(); $(this).addClass("selected"); $('a#countryLink').removeClass("selected"); $('a#globalLink').removeClass("selected"); }); function getLatLong(country) { var lat = []; latLongJson.map(function (json) { if ( json.name == country) { lat.push(json.data["longitude"]); lat.push(json.data["latitude"]); } }); if (lat.length == 0) { lat.push(0.0); lat.push(0.0); } return(lat); } function getMapType(country) { var mt = ""; latLongJson.map(function (json) { if ( json.name == country) { mt = json.data["mapType"]; } }); return(mt); } function getGeoClass(country) { var gc = ""; latLongJson.map(function (json) { if ( json.name == country) { gc = json.data["geoClass"]; } }); return(gc); } function onEachFeature(feature, layer) { var popupContent = ""; var uri = ""; if (feature.properties && feature.properties.popupContent) { popupContent += feature.properties.popupContent; } if (feature.properties && feature.properties.html) { if ( feature.properties.html == "1") { popupContent += ": " + feature.properties.html + " " + i18nStrings.researcherString; } else { popupContent += ": " + feature.properties.html + " " + i18nStrings.researchersString; } } layer.on('mouseover', function(e) { e.target.bindPopup(popupContent,{closeButton:false}).openPopup(); }); layer.on('mouseout', function(e) { e.target.closePopup(); }); if (feature.properties && feature.properties.uri) { uri += feature.properties.uri; layer.on('click', function(e) { document.location.href = urlsBase + "/individual?uri=" + uri + "&#map"; }); } } function getDivIcon(feature) { var htmlContent = ""; var myIcon; if (feature.properties && feature.properties.html) { htmlContent += feature.properties.html; } if ( htmlContent > 99 ) { myIcon = L.divIcon({className: 'divIconCountPlus', html: htmlContent}); } else { myIcon = L.divIcon({className: 'divIconCount', html: htmlContent}); } return myIcon; } function getMarkerRadius(feature) { var radiusContent; if (feature.properties && feature.properties.radius) { radiusContent = feature.properties.radius; } return radiusContent; } function getMarkerFillColor(feature) { var geoClass = ""; var fillColor; if (feature.properties && feature.properties.radius) { geoClass = feature.properties.geoClass; } if ( geoClass == "region") { fillColor = "#abf7f8"; } else { fillColor = "#fdf9cd" } return fillColor; } function checkGlobalCoordinates(feature, layer) { var theLatLng = new L.LatLng(feature.geometry.coordinates[0],feature.geometry.coordinates[1]); var mt = feature.properties.mapType; if ( !theLatLng.equals([0,0]) && mt == "global" ) { return true; } return false; } function checkCountryCoordinates(feature, layer) { var theLatLng = new L.LatLng(feature.geometry.coordinates[0],feature.geometry.coordinates[1]); var mt = feature.properties.mapType; if ( !theLatLng.equals([0,0]) && mt == "country" ) { return true; } return false; } function checkLocalCoordinates(feature, layer) { var theLatLng = new L.LatLng(feature.geometry.coordinates[0],feature.geometry.coordinates[1]); var mt = feature.properties.mapType; if ( !theLatLng.equals([0,0]) && mt == "local" ) { return true; } return false; } function buildGlobalMap() { $('div#mapGlobal').show(); $('div#mapCountry').hide(); $('div#mapLocal').hide(); if ( !globalMapBuilt ) { var mapGlobal = L.map('mapGlobal').setView([25.25, 23.20], 2); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 12, minZoom: 1, boxZoom: false, doubleClickZoom: false, attribution: 'Tiles &copy; <a href="http://www.esri.com/">Esri</a>' }).addTo(mapGlobal); L.geoJson(researchAreas, { filter: checkGlobalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: getMarkerRadius(feature), fillColor: getMarkerFillColor(feature), color: "none", weight: 1, opacity: 0.8, fillOpacity: 0.8 }); } }).addTo(mapGlobal); L.geoJson(researchAreas, { filter: checkGlobalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.marker(latlng, { icon: getDivIcon(feature) }); } }).addTo(mapGlobal); globalMapBuilt = true; } getResearcherCount("global"); appendLegendToLeafletContainer(); } function buildCountryMap() { $('div#mapGlobal').hide(); $('div#mapLocal').hide(); $('div#mapCountry').show(); if ( !countryMapBuilt ) { // CHANGE THE setView COORDINATES SO THAT THE COUNTRY YOU WANT TO // DISPLAY IS CENTERED CORRECTLY. THE COORDINATES BELOW CENTERS THE MAP ON THE U.S. var mapCountry = L.map('mapCountry').setView([46.0, -97.0], 3); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 30, minZoom: 1, boxZoom: false, zIndex: 1, doubleClickZoom: false, attribution: 'Tiles &copy; <a href="http://www.esri.com/">Esri</a>' }).addTo(mapCountry); L.geoJson(researchAreas, { filter: checkCountryCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: getMarkerRadius(feature), fillColor: "#fdf9cd", //fdf38a", color: "none", weight: 1, opacity: 0.8, fillOpacity: 0.8 }); } }).addTo(mapCountry); L.geoJson(researchAreas, { filter: checkCountryCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.marker(latlng, { icon: getDivIcon(feature) }); } }).addTo(mapCountry); countryMapBuilt = true; } getResearcherCount("country"); } function buildLocalMap() { $('div#mapGlobal').hide(); $('div#mapCountry').hide(); $('div#mapLocal').show(); if ( !localMapBuilt ) { // CHANGE THE setView COORDINATES SO THAT THE LOCAL AREA (E.G. A STATE OR PROVINCE) YOU WANT TO // DISPLAY IS CENTERED CORRECTLY. THE COORDINATES BELOW CENTERS THE MAP ON NEW YORK STATE. var mapLocal = L.map('mapLocal').setView([42.83, -75.50], 7); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 12, minZoom: 1, boxZoom: false, doubleClickZoom: false, attribution: 'Tiles &copy; <a href="http://www.esri.com/">Esri</a>' }).addTo(mapLocal); L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places_Alternate/MapServer/tile\/{z}\/{y}\/{x}.png', { maxZoom: 12, minZoom: 1, boxZoom: false, doubleClickZoom: false }).addTo(mapLocal); L.geoJson(researchAreas, { filter: checkLocalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, { radius: getMarkerRadius(feature) + 3, fillColor: "#fdf9cd", color: "none", weight: 1, opacity: 0.8, fillOpacity: 0.8 }); } }).addTo(mapLocal); L.geoJson(researchAreas, { filter: checkLocalCoordinates, onEachFeature: onEachFeature, pointToLayer: function(feature, latlng) { return L.marker(latlng, { icon: getDivIcon(feature) }); } }).addTo(mapLocal); localMapBuilt = true; } getResearcherCount("local"); } function getGeoJsonForMaps() { $.ajax({ url: urlsBase + "/homePageAjax", dataType: "json", data: { action: "getGeoFocusLocations", }, complete: function(xhr, status) { var results = $.parseJSON(xhr.responseText); if ( results.length == 0 ) { var html = i18nStrings.currentlyNoResearchers; $('section#home-geo-focus div#timeIndicatorGeo span').html(html); $('section#home-geo-focus').css("height","175px"); $('section#home-geo-focus div#timeIndicator').css("margin-top","50px"); $('section#home-geo-focus div#mapGlobal').hide(); $('section#home-geo-focus div#mapCountry').hide(); $('section#home-geo-focus div#mapLocal').hide(); } else { $.each(results, function() { var locale = this.properties.popupContent; this.geometry.coordinates = getLatLong(locale); this.properties.mapType = getMapType(locale); this.properties.geoClass = getGeoClass(locale); researchAreas["features"].push(this); }); buildGlobalMap(); $('div#timeIndicatorGeo').hide(); } } }); } function getResearcherCount(area) { var researcherCount = this.geoResearcherCount; var areaCount = 0; var text = ""; if ( area == "global" ) { text = " " + i18nStrings.countriesAndRegions; } else if ( area == "country" ) { text = " " + i18nStrings.stateString; } else { text = " " + i18nStrings.statewideLocations; } $.each(researchAreas.features, function() { if ( this.properties.mapType == area ) { areaCount = areaCount + 1; } }); if ( areaCount == 1 && text == " states.") { text = " " + i18nStrings.stateString; } if ( researcherCount == 1 ) { researcherText = " " + i18nStrings.researcherString + " " + i18nStrings.inString; } else { researcherText = " " + i18nStrings.researcherInString } $('div#researcherTotal').html("<font style='font-size:1.05em;color:#167093'>" + researcherCount + "</font> " + researcherText + " <font style='font-size:1.05em;color:#167093'>" + areaCount + "</font>" + text); } function appendLegendToLeafletContainer() { var htmlString = "<div class='leaflet-bottom leaflet-left' style='padding:0 0 8px 12px'><ul><li>" + "<img alt='" + i18nStrings.regionsString + "' src='" + urlsBase + "/images/map_legend_countries.png' style='margin-right:5px'><font style='color:#555'>" + i18nStrings.countriesString + "</font></li><li><img alt='" + i18nStrings.regionsString + "' src='" + urlsBase + "/images/map_legend_regions.png' style='margin-right:5px'><font style='color:#555'>" + i18nStrings.regionsString + "</font></li></ul></div>"; $('div.leaflet-control-container').append(htmlString); } });
js file wasn't referencing correct i18n tag
productMods/js/homePageMaps.js
js file wasn't referencing correct i18n tag
<ide><path>roductMods/js/homePageMaps.js <ide> researcherText = " " + i18nStrings.researcherString + " " + i18nStrings.inString; <ide> } <ide> else { <del> researcherText = " " + i18nStrings.researcherInString <add> researcherText = " " + i18nStrings.researchersString <ide> } <ide> <ide> $('div#researcherTotal').html("<font style='font-size:1.05em;color:#167093'>"
Java
apache-2.0
06503f63bf14f629a325ecd368bdf4e42e7c6190
0
AmirFatkullin/AmirFatkullinSelenium
package ru.stqa.training.selenium; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.HasCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; public class moy4test { private WebDriver driver; private WebDriverWait wait; @Before public void start() { DesiredCapabilities caps = new DesiredCapabilities(); driver = new FirefoxDriver(new FirefoxOptions().setLegacy(true)); //caps.setCapability(FirefoxDriver.MARIONETTE, false); // driver = new FirefoxDriver(caps); //driver = new FirefoxDriver( //new FirefoxBinary(new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe")), //new FirefoxProfile(), caps); //driver = new FirefoxDriver( //new FirefoxBinary(new File"C:\\Program Files\\Mozilla Firefox\\firefox.exe")), //new FirefoxProfile(), caps); System.out.println(((HasCapabilities) driver).getCapabilities()); wait=new WebDriverWait(driver,10); } @Test public void moy4Test() { driver.get("http://litecart.stqa.ru/admin/"); driver.findElement(By.name("username")).sendKeys("admin"); driver.findElement(By.name("password")).sendKeys("0b7dba1c77df25bf0"); driver.findElement(By.name("login")).click(); wait.until(titleIs("My Store")); } @After public void stop() { driver.quit(); driver=null; } }
java-example/src/test/java/ru/stqa/training/selenium/moy4test.java
package ru.stqa.training.selenium; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.HasCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.File; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; public class moy4test { private WebDriver driver; private WebDriverWait wait; @Before public void start() { DesiredCapabilities caps = new DesiredCapabilities(); //caps.setCapability(FirefoxDriver.MARIONETTE, false); // driver = new FirefoxDriver(caps); //driver = new FirefoxDriver( //new FirefoxBinary(new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe")), //new FirefoxProfile(), caps); driver = new FirefoxDriver( new FirefoxBinary(new File"C:\\Program Files\\Mozilla Firefox\\firefox.exe")), new FirefoxProfile(), caps); System.out.println(((HasCapabilities) driver).getCapabilities()); wait=new WebDriverWait(driver,10); } @Test public void moy4Test() { driver.get("http://litecart.stqa.ru/admin/"); driver.findElement(By.name("username")).sendKeys("admin"); driver.findElement(By.name("password")).sendKeys("0b7dba1c77df25bf0"); driver.findElement(By.name("login")).click(); wait.until(titleIs("My Store")); } @After public void stop() { driver.quit(); driver=null; } }
вот так все заработало:)
java-example/src/test/java/ru/stqa/training/selenium/moy4test.java
вот так все заработало:)
<ide><path>ava-example/src/test/java/ru/stqa/training/selenium/moy4test.java <ide> @Before <ide> public void start() { <ide> DesiredCapabilities caps = new DesiredCapabilities(); <add> driver = new FirefoxDriver(new FirefoxOptions().setLegacy(true)); <ide> //caps.setCapability(FirefoxDriver.MARIONETTE, false); <ide> // driver = new FirefoxDriver(caps); <ide> //driver = new FirefoxDriver( <ide> //new FirefoxBinary(new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe")), <ide> //new FirefoxProfile(), caps); <del> driver = new FirefoxDriver( <del> new FirefoxBinary(new File"C:\\Program Files\\Mozilla Firefox\\firefox.exe")), <del> new FirefoxProfile(), caps); <add> //driver = new FirefoxDriver( <add> //new FirefoxBinary(new File"C:\\Program Files\\Mozilla Firefox\\firefox.exe")), <add> //new FirefoxProfile(), caps); <ide> System.out.println(((HasCapabilities) driver).getCapabilities()); <ide> wait=new WebDriverWait(driver,10); <ide> }
Java
apache-2.0
c1e2054d21597a043352e6a038f0afcf455281ca
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.testing.parse; import static org.smoothbuild.function.base.FullyQualifiedName.simpleName; import static org.smoothbuild.function.base.Type.FILE; import java.util.Map; import java.util.Set; import org.smoothbuild.function.base.Function; import org.smoothbuild.function.base.FunctionSignature; import org.smoothbuild.function.base.Param; import org.smoothbuild.function.plugin.PluginFunction; import org.smoothbuild.parse.SymbolTable; import com.google.common.collect.ImmutableMap; public class TestingImportedFunctions implements SymbolTable { public static final String IMPORTED_NAME = "imported"; private final Map<String, Function> map; public TestingImportedFunctions() { ImmutableMap<String, Param> params = ImmutableMap.<String, Param> of(); FunctionSignature signature = new FunctionSignature(FILE, simpleName(IMPORTED_NAME), params); Function function = new PluginFunction(signature, null); this.map = ImmutableMap.of(IMPORTED_NAME, function); } @Override public boolean containsFunction(String name) { return map.containsKey(name); } @Override public Function getFunction(String name) { return map.get(name); } @Override public Set<String> names() { return map.keySet(); } }
src/testing/org/smoothbuild/testing/parse/TestingImportedFunctions.java
package org.smoothbuild.testing.parse; import static org.smoothbuild.function.base.FullyQualifiedName.simpleName; import java.util.Map; import java.util.Set; import org.smoothbuild.function.base.Function; import org.smoothbuild.function.base.FunctionSignature; import org.smoothbuild.function.base.Type; import org.smoothbuild.function.plugin.PluginFunction; import org.smoothbuild.parse.SymbolTable; import com.google.common.collect.ImmutableMap; public class TestingImportedFunctions implements SymbolTable { public static final String IMPORTED_NAME = "imported"; private final Map<String, Function> map; public TestingImportedFunctions() { FunctionSignature signature = new FunctionSignature(Type.FILE, simpleName(IMPORTED_NAME), null); Function function = new PluginFunction(signature, null); this.map = ImmutableMap.of(IMPORTED_NAME, function); } @Override public boolean containsFunction(String name) { return map.containsKey(name); } @Override public Function getFunction(String name) { return map.get(name); } @Override public Set<String> names() { return map.keySet(); } }
fixed TestingImportedFunctions
src/testing/org/smoothbuild/testing/parse/TestingImportedFunctions.java
fixed TestingImportedFunctions
<ide><path>rc/testing/org/smoothbuild/testing/parse/TestingImportedFunctions.java <ide> package org.smoothbuild.testing.parse; <ide> <ide> import static org.smoothbuild.function.base.FullyQualifiedName.simpleName; <add>import static org.smoothbuild.function.base.Type.FILE; <ide> <ide> import java.util.Map; <ide> import java.util.Set; <ide> <ide> import org.smoothbuild.function.base.Function; <ide> import org.smoothbuild.function.base.FunctionSignature; <del>import org.smoothbuild.function.base.Type; <add>import org.smoothbuild.function.base.Param; <ide> import org.smoothbuild.function.plugin.PluginFunction; <ide> import org.smoothbuild.parse.SymbolTable; <ide> <ide> private final Map<String, Function> map; <ide> <ide> public TestingImportedFunctions() { <del> FunctionSignature signature = new FunctionSignature(Type.FILE, simpleName(IMPORTED_NAME), null); <add> ImmutableMap<String, Param> params = ImmutableMap.<String, Param> of(); <add> FunctionSignature signature = new FunctionSignature(FILE, simpleName(IMPORTED_NAME), params); <ide> Function function = new PluginFunction(signature, null); <ide> this.map = ImmutableMap.of(IMPORTED_NAME, function); <ide> }
Java
apache-2.0
48c1e7a3c5f1865b8cfbcd1096838bce769b7b0f
0
cloud-software-foundation/c5,cloud-software-foundation/c5,cloud-software-foundation/c5,cloud-software-foundation/c5,cloud-software-foundation/c5
/* * Copyright (C) 2014 Ohm Data * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package c5db.tablet; import c5db.C5ServerConstants; import c5db.interfaces.C5Module; import c5db.interfaces.C5Server; import c5db.interfaces.ControlModule; import c5db.interfaces.server.CommandRpcRequest; import c5db.interfaces.tablet.Tablet; import c5db.messages.generated.CommandReply; import c5db.messages.generated.ModuleSubCommand; import c5db.messages.generated.ModuleType; import com.google.common.util.concurrent.ListenableFuture; import org.jetlang.channels.Request; import org.jetlang.channels.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; public class MetaTabletLeaderBehavior implements TabletLeaderBehavior { private static final Logger LOG = LoggerFactory.getLogger(MetaTabletLeaderBehavior.class); private final ListenableFuture<C5Module> f; private final Request<CommandRpcRequest<?>, CommandReply> request; public MetaTabletLeaderBehavior(final Tablet tablet, final C5Server server) { String metaLeader = C5ServerConstants.SET_META_LEADER + " : " + server.getNodeId(); ModuleSubCommand moduleSubCommand = new ModuleSubCommand(ModuleType.Tablet, metaLeader); CommandRpcRequest<ModuleSubCommand> commandCommandRpcRequest = new CommandRpcRequest<>(tablet.getLeader(), moduleSubCommand); request = new Request<CommandRpcRequest<?>, CommandReply>() { @Override public Session getSession() { LOG.info("getSession"); return null; } @Override public CommandRpcRequest<ModuleSubCommand> getRequest() { return commandCommandRpcRequest; } @Override public void reply(CommandReply i) { LOG.info("Command Reply:", i); } }; f = server.getModule(ModuleType.ControlRpc); } public void start() throws ExecutionException, InterruptedException { ControlModule controlService; controlService = (ControlModule) f.get(); controlService.doMessage(request); } }
c5db/src/main/java/c5db/tablet/MetaTabletLeaderBehavior.java
/* * Copyright (C) 2014 Ohm Data * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package c5db.tablet; import c5db.C5ServerConstants; import c5db.interfaces.C5Module; import c5db.interfaces.C5Server; import c5db.interfaces.ControlModule; import c5db.interfaces.server.CommandRpcRequest; import c5db.interfaces.tablet.Tablet; import c5db.messages.generated.CommandReply; import c5db.messages.generated.ModuleSubCommand; import c5db.messages.generated.ModuleType; import com.google.common.util.concurrent.ListenableFuture; import org.jetlang.channels.Request; import org.jetlang.channels.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; public class MetaTabletLeaderBehavior implements TabletLeaderBehavior { private static final Logger LOG = LoggerFactory.getLogger(MetaTabletLeaderBehavior.class); private final ListenableFuture<C5Module> f; private final Request<CommandRpcRequest<?>, CommandReply> request; public MetaTabletLeaderBehavior(final Tablet tablet, final C5Server server) { String metaLeader = C5ServerConstants.SET_META_LEADER + " : " + server.getNodeId(); ModuleSubCommand moduleSubCommand = new ModuleSubCommand(ModuleType.Tablet, metaLeader); CommandRpcRequest<ModuleSubCommand> commandCommandRpcRequest = new CommandRpcRequest<>(tablet.getLeader(), moduleSubCommand); request = new Request<CommandRpcRequest<?>, CommandReply>() { @Override public Session getSession() { LOG.info("getSession"); return null; } @Override public CommandRpcRequest<ModuleSubCommand> getRequest() { return commandCommandRpcRequest; } @Override public void reply(CommandReply i) { LOG.info("Command Reply"); } }; f = server.getModule(ModuleType.ControlRpc); } public void start() throws ExecutionException, InterruptedException { ControlModule controlService; controlService = (ControlModule) f.get(); controlService.doMessage(request); } }
Print the command reply
c5db/src/main/java/c5db/tablet/MetaTabletLeaderBehavior.java
Print the command reply
<ide><path>5db/src/main/java/c5db/tablet/MetaTabletLeaderBehavior.java <ide> <ide> @Override <ide> public void reply(CommandReply i) { <del> LOG.info("Command Reply"); <add> LOG.info("Command Reply:", i); <ide> } <ide> }; <ide> f = server.getModule(ModuleType.ControlRpc);
JavaScript
apache-2.0
c667473258681cea0808bca73155720f10556587
0
vector-im/vector-web,vector-im/vector-web,vector-im/vector-web,vector-im/vector-web,vector-im/vector-web
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const webpack = require("webpack"); let og_image_url = process.env.RIOT_OG_IMAGE_URL; if (!og_image_url) og_image_url = 'https://app.element.io/themes/element/img/logos/opengraph.png'; module.exports = (env, argv) => { if (process.env.CI_PACKAGE) { // Don't run minification for CI builds (this is only set for runs on develop) // We override this via environment variable to avoid duplicating the scripts // in `package.json` just for a different mode. argv.mode = "development"; } const development = {}; if (argv.mode === "production") { development['devtool'] = 'nosources-source-map'; } else { // This makes the sourcemaps human readable for developers. We use eval-source-map // because the plain source-map devtool ruins the alignment. development['devtool'] = 'eval-source-map'; } // Resolve the directories for the react-sdk and js-sdk for later use. We resolve these early so we // don't have to call them over and over. We also resolve to the package.json instead of the src // directory so we don't have to rely on a index.js or similar file existing. const reactSdkSrcDir = path.resolve(require.resolve("matrix-react-sdk/package.json"), '..', 'src'); const jsSdkSrcDir = path.resolve(require.resolve("matrix-js-sdk/package.json"), '..', 'src'); return { ...development, entry: { "bundle": "./src/vector/index.ts", "indexeddb-worker": "./src/vector/indexeddb-worker.js", "mobileguide": "./src/vector/mobile_guide/index.js", "jitsi": "./src/vector/jitsi/index.ts", "usercontent": "./node_modules/matrix-react-sdk/src/usercontent/index.js", // CSS themes "theme-legacy": "./node_modules/matrix-react-sdk/res/themes/legacy-light/css/legacy-light.scss", "theme-legacy-dark": "./node_modules/matrix-react-sdk/res/themes/legacy-dark/css/legacy-dark.scss", "theme-light": "./node_modules/matrix-react-sdk/res/themes/light/css/light.scss", "theme-dark": "./node_modules/matrix-react-sdk/res/themes/dark/css/dark.scss", "theme-light-custom": "./node_modules/matrix-react-sdk/res/themes/light-custom/css/light-custom.scss", "theme-dark-custom": "./node_modules/matrix-react-sdk/res/themes/dark-custom/css/dark-custom.scss", }, optimization: { // Put all of our CSS into one useful place - this is needed for MiniCssExtractPlugin. // Previously we used a different extraction plugin that did this magic for us, but // now we need to consider that the CSS needs to be bundled up together. splitChunks: { cacheGroups: { styles: { name: 'styles', test: /\.css$/, enforce: true, // Do not add `chunks: 'all'` here because you'll break the app entry point. }, default: { reuseExistingChunk: true, }, }, }, // This fixes duplicate files showing up in chrome with sourcemaps enabled. // See https://github.com/webpack/webpack/issues/7128 for more info. namedModules: false, // Minification is normally enabled by default for webpack in production mode, but // we use a CSS optimizer too and need to manage it ourselves. minimize: argv.mode === 'production', minimizer: argv.mode === 'production' ? [new TerserPlugin({}), new OptimizeCSSAssetsPlugin({})] : [], }, resolve: { // We define an alternative import path so we can safely use src/ across the react-sdk // and js-sdk. We already import from src/ where possible to ensure our source maps are // extremely accurate (and because we're capable of compiling the layers manually rather // than relying on partially-mangled output from babel), though we do need to fix the // package level import (stuff like `import {Thing} from "matrix-js-sdk"` for example). // We can't use the aliasing down below to point at src/ because that'll fail to resolve // the package.json for the dependency. Instead, we rely on the package.json of each // layer to have our custom alternate fields to load things in the right order. These are // the defaults of webpack prepended with `matrix_src_`. mainFields: ['matrix_src_browser', 'matrix_src_main', 'browser', 'main'], aliasFields: ['matrix_src_browser', 'browser'], // We need to specify that TS can be resolved without an extension extensions: ['.js', '.json', '.ts', '.tsx'], alias: { // alias any requires to the react module to the one in our path, // otherwise we tend to get the react source included twice when // using `npm link` / `yarn link`. "react": path.resolve(__dirname, 'node_modules/react'), "react-dom": path.resolve(__dirname, 'node_modules/react-dom'), // same goes for js-sdk - we don't need two copies. "matrix-js-sdk": path.resolve(__dirname, 'node_modules/matrix-js-sdk'), // and prop-types and sanitize-html "prop-types": path.resolve(__dirname, 'node_modules/prop-types'), "sanitize-html": path.resolve(__dirname, 'node_modules/sanitize-html'), // Define a variable so the i18n stuff can load "$webapp": path.resolve(__dirname, 'webapp'), }, }, module: { noParse: [ // for cross platform compatibility use [\\\/] as the path separator // this ensures that the regex trips on both Windows and *nix // don't parse the languages within highlight.js. They cause stack // overflows (https://github.com/webpack/webpack/issues/1721), and // there is no need for webpack to parse them - they can just be // included as-is. /highlight\.js[\\\/]lib[\\\/]languages/, // olm takes ages for webpack to process, and it's already heavily // optimised, so there is little to gain by us uglifying it. /olm[\\\/](javascript[\\\/])?olm\.js$/, ], rules: [ { test: /\.(ts|js)x?$/, include: (f) => { // our own source needs babel-ing if (f.startsWith(path.resolve(__dirname, 'src'))) return true; // we use the original source files of react-sdk and js-sdk, so we need to // run them through babel. Because the path tested is the resolved, absolute // path, these could be anywhere thanks to yarn link. We must also not // include node modules inside these modules, so we add 'src'. if (f.startsWith(reactSdkSrcDir)) return true; if (f.startsWith(jsSdkSrcDir)) return true; // but we can't run all of our dependencies through babel (many of them still // use module.exports which breaks if babel injects an 'include' for its // polyfills: probably fixable but babeling all our dependencies is probably // not necessary anyway). So, for anything else, don't babel. return false; }, loader: 'babel-loader', options: { cacheDirectory: true } }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, sourceMap: true, } }, { loader: 'postcss-loader', ident: 'postcss', options: { sourceMap: true, plugins: () => [ // Note that we use significantly fewer plugins on the plain // CSS parser. If we start to parse plain CSS, we end with all // kinds of nasty problems (like stylesheets not loading). // // You might have noticed that we're also sending regular CSS // through PostCSS. This looks weird, and in fact is probably // not what you'd expect, however in order for our CSS build // to work nicely we have to do this. Because down the line // our SCSS stylesheets reference plain CSS we have to load // the plain CSS through PostCSS so it can find it safely. This // also acts like a babel-for-css by transpiling our (S)CSS // down/up to the right browser support (prefixes, etc). // Further, if we don't do this then PostCSS assumes that our // plain CSS is SCSS and it really doesn't like that, even // though plain CSS should be compatible. The chunking options // at the top of this webpack config help group the SCSS and // plain CSS together for the bundler. require("postcss-simple-vars")(), require("postcss-strip-inline-comments")(), require("postcss-hexrgba")(), // It's important that this plugin is last otherwise we end // up with broken CSS. require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}), ], parser: "postcss-scss", "local-plugins": true, }, }, ] }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, sourceMap: true, } }, { loader: 'postcss-loader', ident: 'postcss', options: { sourceMap: true, plugins: () => [ // Note that we use slightly different plugins for SCSS. require('postcss-import')(), require("postcss-mixins")(), require("postcss-simple-vars")(), require("postcss-extend")(), require("postcss-nested")(), require("postcss-easings")(), require("postcss-strip-inline-comments")(), require("postcss-hexrgba")(), // It's important that this plugin is last otherwise we end // up with broken CSS. require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}), ], parser: "postcss-scss", "local-plugins": true, }, }, ] }, { test: /\.wasm$/, loader: "file-loader", type: "javascript/auto", // https://github.com/webpack/webpack/issues/6725 options: { name: '[name].[hash:7].[ext]', outputPath: '.', }, }, { // cache-bust languages.json file placed in // element-web/webapp/i18n during build by copy-res.js test: /\.*languages.json$/, type: "javascript/auto", loader: 'file-loader', options: { name: 'i18n/[name].[hash:7].[ext]', }, }, { test: /\.(gif|png|svg|ttf|woff|woff2|xml|ico)$/, // Use a content-based hash in the name so that we can set a long cache // lifetime for assets while still delivering changes quickly. oneOf: [ { // Assets referenced in CSS files issuer: /\.(scss|css)$/, loader: 'file-loader', options: { esModule: false, name: '[name].[hash:7].[ext]', outputPath: getAssetOutputPath, publicPath: function(url, resourcePath) { // CSS image usages end up in the `bundles/[hash]` output // directory, so we adjust the final path to navigate up // twice. const outputPath = getAssetOutputPath(url, resourcePath); return toPublicPath(path.join("../..", outputPath)); }, }, }, { // Assets referenced in HTML and JS files loader: 'file-loader', options: { esModule: false, name: '[name].[hash:7].[ext]', outputPath: getAssetOutputPath, publicPath: function(url, resourcePath) { const outputPath = getAssetOutputPath(url, resourcePath); return toPublicPath(outputPath); }, }, }, ], }, ] }, plugins: [ // This exports our CSS using the splitChunks and loaders above. new MiniCssExtractPlugin({ filename: 'bundles/[hash]/[name].css', ignoreOrder: false, // Enable to remove warnings about conflicting order }), // This is the app's main entry point. new HtmlWebpackPlugin({ template: './src/vector/index.html', // we inject the links ourselves via the template, because // HtmlWebpackPlugin will screw up our formatting like the names // of the themes and which chunks we actually care about. inject: false, excludeChunks: ['mobileguide', 'usercontent', 'jitsi'], minify: argv.mode === 'production', vars: { og_image_url: og_image_url, }, }), // This is the jitsi widget wrapper (embedded, so isolated stack) new HtmlWebpackPlugin({ template: './src/vector/jitsi/index.html', filename: 'jitsi.html', minify: argv.mode === 'production', chunks: ['jitsi'], }), // This is the mobile guide's entry point (separate for faster mobile loading) new HtmlWebpackPlugin({ template: './src/vector/mobile_guide/index.html', filename: 'mobile_guide/index.html', minify: argv.mode === 'production', chunks: ['mobileguide'], }), // These are the static error pages for when the javascript env is *really unsupported* new HtmlWebpackPlugin({ template: './src/vector/static/unable-to-load.html', filename: 'static/unable-to-load.html', minify: argv.mode === 'production', chunks: [], }), new HtmlWebpackPlugin({ template: './src/vector/static/incompatible-browser.html', filename: 'static/incompatible-browser.html', minify: argv.mode === 'production', chunks: [], }), // This is the usercontent sandbox's entry point (separate for iframing) new HtmlWebpackPlugin({ template: './node_modules/matrix-react-sdk/src/usercontent/index.html', filename: 'usercontent/index.html', minify: argv.mode === 'production', chunks: ['usercontent'], }), ], output: { path: path.join(__dirname, "webapp"), // The generated JS (and CSS, from the extraction plugin) are put in a // unique subdirectory for the build. There will only be one such // 'bundle' directory in the generated tarball; however, hosting // servers can collect 'bundles' from multiple versions into one // directory and symlink it into place - this allows users who loaded // an older version of the application to continue to access webpack // chunks even after the app is redeployed. filename: "bundles/[hash]/[name].js", chunkFilename: "bundles/[hash]/[name].js", }, // configuration for the webpack-dev-server devServer: { // serve unwebpacked assets from webapp. contentBase: './webapp', // Only output errors, warnings, or new compilations. // This hides the massive list of modules. stats: 'minimal', // hot module replacement doesn't work (I think we'd need react-hot-reload?) // so webpack-dev-server reloads the page on every update which is quite // tedious in Riot since that can take a while. hot: false, inline: false, }, }; }; /** * Merge assets found via CSS and imports into a single tree, while also preserving * directories under e.g. `res` or similar. * * @param {string} url The adjusted name of the file, such as `warning.1234567.svg`. * @param {string} resourcePath The absolute path to the source file with unmodified name. * @return {string} The returned paths will look like `img/warning.1234567.svg`. */ function getAssetOutputPath(url, resourcePath) { // `res` is the parent dir for our own assets in various layers // `dist` is the parent dir for KaTeX assets const prefix = /^.*[/\\](dist|res)[/\\]/; if (!resourcePath.match(prefix)) { throw new Error(`Unexpected asset path: ${resourcePath}`); } let outputDir = path.dirname(resourcePath).replace(prefix, ""); if (resourcePath.includes("KaTeX")) { // Add a clearly named directory segment, rather than leaving the KaTeX // assets loose in each asset type directory. outputDir = path.join(outputDir, "KaTeX"); } return path.join(outputDir, path.basename(url)); } /** * Convert path to public path format, which always uses forward slashes, since it will * be placed directly into things like CSS files. * * @param {string} path Some path to a file. */ function toPublicPath(path) { return path.replace(/\\/g, '/'); }
webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const webpack = require("webpack"); let og_image_url = process.env.RIOT_OG_IMAGE_URL; if (!og_image_url) og_image_url = 'https://app.element.io/themes/element/img/logos/opengraph.png'; module.exports = (env, argv) => { if (process.env.CI_PACKAGE) { // Don't run minification for CI builds (this is only set for runs on develop) // We override this via environment variable to avoid duplicating the scripts // in `package.json` just for a different mode. argv.mode = "development"; } const development = {}; if (argv.mode === "production") { development['devtool'] = 'nosources-source-map'; } else { // This makes the sourcemaps human readable for developers. We use eval-source-map // because the plain source-map devtool ruins the alignment. development['devtool'] = 'eval-source-map'; } // Resolve the directories for the react-sdk and js-sdk for later use. We resolve these early so we // don't have to call them over and over. We also resolve to the package.json instead of the src // directory so we don't have to rely on a index.js or similar file existing. const reactSdkSrcDir = path.resolve(require.resolve("matrix-react-sdk/package.json"), '..', 'src'); const jsSdkSrcDir = path.resolve(require.resolve("matrix-js-sdk/package.json"), '..', 'src'); return { ...development, entry: { "bundle": "./src/vector/index.ts", "indexeddb-worker": "./src/vector/indexeddb-worker.js", "mobileguide": "./src/vector/mobile_guide/index.js", "jitsi": "./src/vector/jitsi/index.ts", "usercontent": "./node_modules/matrix-react-sdk/src/usercontent/index.js", // CSS themes "theme-legacy": "./node_modules/matrix-react-sdk/res/themes/legacy-light/css/legacy-light.scss", "theme-legacy-dark": "./node_modules/matrix-react-sdk/res/themes/legacy-dark/css/legacy-dark.scss", "theme-light": "./node_modules/matrix-react-sdk/res/themes/light/css/light.scss", "theme-dark": "./node_modules/matrix-react-sdk/res/themes/dark/css/dark.scss", "theme-light-custom": "./node_modules/matrix-react-sdk/res/themes/light-custom/css/light-custom.scss", "theme-dark-custom": "./node_modules/matrix-react-sdk/res/themes/dark-custom/css/dark-custom.scss", }, optimization: { // Put all of our CSS into one useful place - this is needed for MiniCssExtractPlugin. // Previously we used a different extraction plugin that did this magic for us, but // now we need to consider that the CSS needs to be bundled up together. splitChunks: { cacheGroups: { styles: { name: 'styles', test: /\.css$/, enforce: true, // Do not add `chunks: 'all'` here because you'll break the app entry point. }, default: { reuseExistingChunk: true, }, }, }, // This fixes duplicate files showing up in chrome with sourcemaps enabled. // See https://github.com/webpack/webpack/issues/7128 for more info. namedModules: false, // Minification is normally enabled by default for webpack in production mode, but // we use a CSS optimizer too and need to manage it ourselves. minimize: argv.mode === 'production', minimizer: argv.mode === 'production' ? [new TerserPlugin({}), new OptimizeCSSAssetsPlugin({})] : [], }, resolve: { // We define an alternative import path so we can safely use src/ across the react-sdk // and js-sdk. We already import from src/ where possible to ensure our source maps are // extremely accurate (and because we're capable of compiling the layers manually rather // than relying on partially-mangled output from babel), though we do need to fix the // package level import (stuff like `import {Thing} from "matrix-js-sdk"` for example). // We can't use the aliasing down below to point at src/ because that'll fail to resolve // the package.json for the dependency. Instead, we rely on the package.json of each // layer to have our custom alternate fields to load things in the right order. These are // the defaults of webpack prepended with `matrix_src_`. mainFields: ['matrix_src_browser', 'matrix_src_main', 'browser', 'main'], aliasFields: ['matrix_src_browser', 'browser'], // We need to specify that TS can be resolved without an extension extensions: ['.js', '.json', '.ts', '.tsx'], alias: { // alias any requires to the react module to the one in our path, // otherwise we tend to get the react source included twice when // using `npm link` / `yarn link`. "react": path.resolve(__dirname, 'node_modules/react'), "react-dom": path.resolve(__dirname, 'node_modules/react-dom'), // same goes for js-sdk - we don't need two copies. "matrix-js-sdk": path.resolve(__dirname, 'node_modules/matrix-js-sdk'), // and prop-types and sanitize-html "prop-types": path.resolve(__dirname, 'node_modules/prop-types'), "sanitize-html": path.resolve(__dirname, 'node_modules/sanitize-html'), // Define a variable so the i18n stuff can load "$webapp": path.resolve(__dirname, 'webapp'), }, }, module: { noParse: [ // for cross platform compatibility use [\\\/] as the path separator // this ensures that the regex trips on both Windows and *nix // don't parse the languages within highlight.js. They cause stack // overflows (https://github.com/webpack/webpack/issues/1721), and // there is no need for webpack to parse them - they can just be // included as-is. /highlight\.js[\\\/]lib[\\\/]languages/, // olm takes ages for webpack to process, and it's already heavily // optimised, so there is little to gain by us uglifying it. /olm[\\\/](javascript[\\\/])?olm\.js$/, ], rules: [ { test: /\.(ts|js)x?$/, include: (f) => { // our own source needs babel-ing if (f.startsWith(path.resolve(__dirname, 'src'))) return true; // we use the original source files of react-sdk and js-sdk, so we need to // run them through babel. Because the path tested is the resolved, absolute // path, these could be anywhere thanks to yarn link. We must also not // include node modules inside these modules, so we add 'src'. if (f.startsWith(reactSdkSrcDir)) return true; if (f.startsWith(jsSdkSrcDir)) return true; // but we can't run all of our dependencies through babel (many of them still // use module.exports which breaks if babel injects an 'include' for its // polyfills: probably fixable but babeling all our dependencies is probably // not necessary anyway). So, for anything else, don't babel. return false; }, loader: 'babel-loader', options: { cacheDirectory: true } }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, sourceMap: true, } }, { loader: 'postcss-loader', ident: 'postcss', options: { sourceMap: true, plugins: () => [ // Note that we use significantly fewer plugins on the plain // CSS parser. If we start to parse plain CSS, we end with all // kinds of nasty problems (like stylesheets not loading). // // You might have noticed that we're also sending regular CSS // through PostCSS. This looks weird, and in fact is probably // not what you'd expect, however in order for our CSS build // to work nicely we have to do this. Because down the line // our SCSS stylesheets reference plain CSS we have to load // the plain CSS through PostCSS so it can find it safely. This // also acts like a babel-for-css by transpiling our (S)CSS // down/up to the right browser support (prefixes, etc). // Further, if we don't do this then PostCSS assumes that our // plain CSS is SCSS and it really doesn't like that, even // though plain CSS should be compatible. The chunking options // at the top of this webpack config help group the SCSS and // plain CSS together for the bundler. require("postcss-simple-vars")(), require("postcss-strip-inline-comments")(), require("postcss-hexrgba")(), // It's important that this plugin is last otherwise we end // up with broken CSS. require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}), ], parser: "postcss-scss", "local-plugins": true, }, }, ] }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { importLoaders: 1, sourceMap: true, } }, { loader: 'postcss-loader', ident: 'postcss', options: { sourceMap: true, plugins: () => [ // Note that we use slightly different plugins for SCSS. require('postcss-import')(), require("postcss-mixins")(), require("postcss-simple-vars")(), require("postcss-extend")(), require("postcss-nested")(), require("postcss-easings")(), require("postcss-strip-inline-comments")(), require("postcss-hexrgba")(), // It's important that this plugin is last otherwise we end // up with broken CSS. require('postcss-preset-env')({stage: 3, browsers: 'last 2 versions'}), ], parser: "postcss-scss", "local-plugins": true, }, }, ] }, { test: /\.wasm$/, loader: "file-loader", type: "javascript/auto", // https://github.com/webpack/webpack/issues/6725 options: { name: '[name].[hash:7].[ext]', outputPath: '.', }, }, { // cache-bust languages.json file placed in // element-web/webapp/i18n during build by copy-res.js test: /\.*languages.json$/, type: "javascript/auto", loader: 'file-loader', options: { name: 'i18n/[name].[hash:7].[ext]', }, }, { test: /\.(gif|png|svg|ttf|woff|woff2|xml|ico)$/, // Use a content-based hash in the name so that we can set a long cache // lifetime for assets while still delivering changes quickly. oneOf: [ { // Assets referenced in CSS files issuer: /\.(scss|css)$/, loader: 'file-loader', options: { esModule: false, name: '[name].[hash:7].[ext]', outputPath: getImgOutputPath, publicPath: function(url, resourcePath) { // CSS image usages end up in the `bundles/[hash]` output // directory, so we adjust the final path to navigate up // twice. const outputPath = getImgOutputPath(url, resourcePath); return toPublicPath(path.join("../..", outputPath)); }, }, }, { // Assets referenced in HTML and JS files loader: 'file-loader', options: { esModule: false, name: '[name].[hash:7].[ext]', outputPath: getImgOutputPath, publicPath: function(url, resourcePath) { const outputPath = getImgOutputPath(url, resourcePath); return toPublicPath(outputPath); }, }, }, ], }, ] }, plugins: [ // This exports our CSS using the splitChunks and loaders above. new MiniCssExtractPlugin({ filename: 'bundles/[hash]/[name].css', ignoreOrder: false, // Enable to remove warnings about conflicting order }), // This is the app's main entry point. new HtmlWebpackPlugin({ template: './src/vector/index.html', // we inject the links ourselves via the template, because // HtmlWebpackPlugin will screw up our formatting like the names // of the themes and which chunks we actually care about. inject: false, excludeChunks: ['mobileguide', 'usercontent', 'jitsi'], minify: argv.mode === 'production', vars: { og_image_url: og_image_url, }, }), // This is the jitsi widget wrapper (embedded, so isolated stack) new HtmlWebpackPlugin({ template: './src/vector/jitsi/index.html', filename: 'jitsi.html', minify: argv.mode === 'production', chunks: ['jitsi'], }), // This is the mobile guide's entry point (separate for faster mobile loading) new HtmlWebpackPlugin({ template: './src/vector/mobile_guide/index.html', filename: 'mobile_guide/index.html', minify: argv.mode === 'production', chunks: ['mobileguide'], }), // These are the static error pages for when the javascript env is *really unsupported* new HtmlWebpackPlugin({ template: './src/vector/static/unable-to-load.html', filename: 'static/unable-to-load.html', minify: argv.mode === 'production', chunks: [], }), new HtmlWebpackPlugin({ template: './src/vector/static/incompatible-browser.html', filename: 'static/incompatible-browser.html', minify: argv.mode === 'production', chunks: [], }), // This is the usercontent sandbox's entry point (separate for iframing) new HtmlWebpackPlugin({ template: './node_modules/matrix-react-sdk/src/usercontent/index.html', filename: 'usercontent/index.html', minify: argv.mode === 'production', chunks: ['usercontent'], }), ], output: { path: path.join(__dirname, "webapp"), // The generated JS (and CSS, from the extraction plugin) are put in a // unique subdirectory for the build. There will only be one such // 'bundle' directory in the generated tarball; however, hosting // servers can collect 'bundles' from multiple versions into one // directory and symlink it into place - this allows users who loaded // an older version of the application to continue to access webpack // chunks even after the app is redeployed. filename: "bundles/[hash]/[name].js", chunkFilename: "bundles/[hash]/[name].js", }, // configuration for the webpack-dev-server devServer: { // serve unwebpacked assets from webapp. contentBase: './webapp', // Only output errors, warnings, or new compilations. // This hides the massive list of modules. stats: 'minimal', // hot module replacement doesn't work (I think we'd need react-hot-reload?) // so webpack-dev-server reloads the page on every update which is quite // tedious in Riot since that can take a while. hot: false, inline: false, }, }; }; /** * Merge assets found via CSS and imports into a single tree, while also preserving * directories under `res`. * * @param {string} url The adjusted name of the file, such as `warning.1234567.svg`. * @param {string} resourcePath The absolute path to the source file with unmodified name. * @return {string} The returned paths will look like `img/warning.1234567.svg`. */ function getImgOutputPath(url, resourcePath) { const prefix = /^.*[/\\]res[/\\]/; const outputDir = path.dirname(resourcePath).replace(prefix, ""); return path.join(outputDir, path.basename(url)); } /** * Convert path to public path format, which always uses forward slashes, since it will * be placed directly into things like CSS files. * * @param {string} path Some path to a file. */ function toPublicPath(path) { return path.replace(/\\/g, '/'); }
Improve asset path for KaTeX fonts This adjusts our asset path handling to group KaTeX fonts in a more sensible way alongside the other fonts we have. It also resolves production build issues on Windows. Fixes https://github.com/vector-im/element-web/issues/15911
webpack.config.js
Improve asset path for KaTeX fonts
<ide><path>ebpack.config.js <ide> options: { <ide> esModule: false, <ide> name: '[name].[hash:7].[ext]', <del> outputPath: getImgOutputPath, <add> outputPath: getAssetOutputPath, <ide> publicPath: function(url, resourcePath) { <ide> // CSS image usages end up in the `bundles/[hash]` output <ide> // directory, so we adjust the final path to navigate up <ide> // twice. <del> const outputPath = getImgOutputPath(url, resourcePath); <add> const outputPath = getAssetOutputPath(url, resourcePath); <ide> return toPublicPath(path.join("../..", outputPath)); <ide> }, <ide> }, <ide> options: { <ide> esModule: false, <ide> name: '[name].[hash:7].[ext]', <del> outputPath: getImgOutputPath, <add> outputPath: getAssetOutputPath, <ide> publicPath: function(url, resourcePath) { <del> const outputPath = getImgOutputPath(url, resourcePath); <add> const outputPath = getAssetOutputPath(url, resourcePath); <ide> return toPublicPath(outputPath); <ide> }, <ide> }, <ide> <ide> /** <ide> * Merge assets found via CSS and imports into a single tree, while also preserving <del> * directories under `res`. <add> * directories under e.g. `res` or similar. <ide> * <ide> * @param {string} url The adjusted name of the file, such as `warning.1234567.svg`. <ide> * @param {string} resourcePath The absolute path to the source file with unmodified name. <ide> * @return {string} The returned paths will look like `img/warning.1234567.svg`. <ide> */ <del>function getImgOutputPath(url, resourcePath) { <del> const prefix = /^.*[/\\]res[/\\]/; <del> const outputDir = path.dirname(resourcePath).replace(prefix, ""); <add>function getAssetOutputPath(url, resourcePath) { <add> // `res` is the parent dir for our own assets in various layers <add> // `dist` is the parent dir for KaTeX assets <add> const prefix = /^.*[/\\](dist|res)[/\\]/; <add> if (!resourcePath.match(prefix)) { <add> throw new Error(`Unexpected asset path: ${resourcePath}`); <add> } <add> let outputDir = path.dirname(resourcePath).replace(prefix, ""); <add> if (resourcePath.includes("KaTeX")) { <add> // Add a clearly named directory segment, rather than leaving the KaTeX <add> // assets loose in each asset type directory. <add> outputDir = path.join(outputDir, "KaTeX"); <add> } <ide> return path.join(outputDir, path.basename(url)); <ide> } <ide>
JavaScript
mit
5e7b8c1819b467234e42cc1c1af33dd7aa047277
0
CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder
'use strict'; /** * Running the indexing procedure in whatever mode the state suggests. */ var Q = require('q'); var processQuery = require('../processing/query'); var config = require('../../../shared/config'); const POST_PROCESSING_STEPS = [ require('../post-processing/delete-removed-assets'), require('../post-processing/clear-index') ]; module.exports = state => { const mode = require('./' + state.mode); // Generate the queries state.queries = mode.generateQueries(state); // Add any indexing restrictions from the configuration. state.queries.forEach((q) => { if (config.cip.indexing.restriction) { q.query = '(' + q.query + ') AND ' + config.cip.indexing.restriction; } }); console.log('\n=== Starting to process ==='); // TODO: Consider if the two new Q(state)s need to be wrapped in promises. return state.queries.reduce((promise, query) => { return promise.then((state) => { // Process the query, hang onto the indexed asset ids and exceptions // and return the state return processQuery(state, query) .then(({indexedIds, errors}) => { query.indexedIds = indexedIds; query.errors = errors; return state; }); }); }, new Q(state)).then((state) => { console.log('Finished processing!'); return POST_PROCESSING_STEPS.reduce(Q.when, new Q(state)); }); };
webapplication/indexing/modes/run.js
'use strict'; /** * Running the indexing procedure in whatever mode the state suggests. */ var Q = require('q'); var processQuery = require('../processing/query'); var config = require('../../../shared/config'); const POST_PROCESSING_STEPS = [ require('../post-processing/delete-removed-assets'), require('../post-processing/clear-index') ]; module.exports = state => { const mode = require('./' + state.mode); // Generate the queries state.queries = mode.generateQueries(state); // Add any indexing restrictions from the configuration. state.queries.forEach((q) => { if (config.cip.indexing.restriction) { q.query = '(' + q.query + ') AND ' + config.cip.indexing.restriction; } }); console.log('\n=== Starting to process ==='); // TODO: Consider if the two new Q(state)s need to be wrapped in promises. return state.queries.reduce((promise, query) => { return promise.then((state) => { // Process the query, hang onto the indexed asset ids and exceptions // and return the state return processQuery(state, query) .then(({ indexedIds, errors }) => { query.indexedIds = indexedIds; query.errors = errors; return state; }); }); }, new Q(state)).then((state) => { console.log('Finished processing!'); return POST_PROCESSING_STEPS.reduce(Q.when, new Q(state)); }); };
Indentation fix
webapplication/indexing/modes/run.js
Indentation fix
<ide><path>ebapplication/indexing/modes/run.js <ide> // Process the query, hang onto the indexed asset ids and exceptions <ide> // and return the state <ide> return processQuery(state, query) <del> .then(({ indexedIds, errors }) => { <del> query.indexedIds = indexedIds; <del> query.errors = errors; <del> return state; <del> }); <add> .then(({indexedIds, errors}) => { <add> query.indexedIds = indexedIds; <add> query.errors = errors; <add> return state; <add> }); <ide> }); <ide> }, new Q(state)).then((state) => { <ide> console.log('Finished processing!');
Java
mit
dbfdffd8a5f41e7f2065c363cd8d023dbf2a4d0f
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.user.service; import org.innovateuk.ifs.BaseServiceUnitTest; import org.innovateuk.ifs.authentication.service.IdentityProviderService; import org.innovateuk.ifs.authentication.validator.PasswordPolicyValidator; import org.innovateuk.ifs.commons.error.CommonErrors; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.resource.SiteTermsAndConditionsResource; import org.innovateuk.ifs.competition.transactional.TermsAndConditionsService; import org.innovateuk.ifs.invite.domain.Invite; import org.innovateuk.ifs.invite.domain.RoleInvite; import org.innovateuk.ifs.invite.repository.UserInviteRepository; import org.innovateuk.ifs.notifications.resource.Notification; import org.innovateuk.ifs.notifications.resource.SystemNotificationSource; import org.innovateuk.ifs.notifications.resource.UserNotificationTarget; import org.innovateuk.ifs.notifications.service.NotificationService; import org.innovateuk.ifs.organisation.builder.OrganisationBuilder; import org.innovateuk.ifs.token.domain.Token; import org.innovateuk.ifs.token.repository.TokenRepository; import org.innovateuk.ifs.token.resource.TokenType; import org.innovateuk.ifs.token.transactional.TokenService; import org.innovateuk.ifs.user.command.GrantRoleCommand; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.mapper.UserMapper; import org.innovateuk.ifs.user.repository.UserRepository; import org.innovateuk.ifs.user.resource.*; import org.innovateuk.ifs.user.transactional.RegistrationService; import org.innovateuk.ifs.user.transactional.UserService; import org.innovateuk.ifs.user.transactional.UserServiceImpl; import org.innovateuk.ifs.userorganisation.domain.UserOrganisation; import org.innovateuk.ifs.userorganisation.mapper.UserOrganisationMapper; import org.innovateuk.ifs.userorganisation.repository.UserOrganisationRepository; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.util.ReflectionTestUtils; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Optional.of; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.USER_SEARCH_INVALID_INPUT_LENGTH; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.SiteTermsAndConditionsResourceBuilder.newSiteTermsAndConditionsResource; import static org.innovateuk.ifs.invite.constant.InviteStatus.OPENED; import static org.innovateuk.ifs.notifications.resource.NotificationMedium.EMAIL; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.innovateuk.ifs.user.builder.UserOrganisationResourceBuilder.newUserOrganisationResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.APPLICANT; import static org.innovateuk.ifs.user.resource.Role.externalApplicantRoles; import static org.innovateuk.ifs.userorganisation.builder.UserOrganisationBuilder.newUserOrganisation; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; /** * Tests of the UserService class */ public class UserServiceImplTest extends BaseServiceUnitTest<UserService> { private static final String WEB_BASE_URL = "baseUrl"; @Captor private ArgumentCaptor<Notification> notificationArgumentCaptor; @Mock private UserOrganisationMapper userOrganisationMapperMock; @Mock private TermsAndConditionsService termsAndConditionsServiceMock; @Mock private TokenService tokenServiceMock; @Mock private UserRepository userRepositoryMock; @Mock private UserMapper userMapperMock; @Mock private PasswordPolicyValidator passwordPolicyValidatorMock; @Mock private IdentityProviderService idpServiceMock; @Mock private TokenRepository tokenRepositoryMock; @Mock private NotificationService notificationServiceMock; @Mock private RegistrationService registrationServiceMock; @Mock private UserOrganisationRepository userOrganisationRepositoryMock; @Mock private SystemNotificationSource systemNotificationSource; @Mock private UserInviteRepository userInviteRepositoryMock; @Mock(name = "randomHashSupplier") private Supplier<String> randomHashSupplierMock; @Override protected UserService supplyServiceUnderTest() { UserServiceImpl spendProfileService = new UserServiceImpl(); ReflectionTestUtils.setField(spendProfileService, "webBaseUrl", WEB_BASE_URL); return spendProfileService; } @Test public void testChangePassword() { User user = newUser().build(); UserResource userResource = newUserResource().withUID("myuid").build(); Token token = new Token(TokenType.RESET_PASSWORD, null, 123L, null, null, null); when(tokenServiceMock.getPasswordResetToken("myhash")).thenReturn(serviceSuccess(token)); when(userRepositoryMock.findOne(123L)).thenReturn(user); when(userMapperMock.mapToResource(user)).thenReturn(userResource); when(passwordPolicyValidatorMock.validatePassword("mypassword", userResource)).thenReturn(serviceSuccess()); when(idpServiceMock.updateUserPassword("myuid", "mypassword")).thenReturn(serviceSuccess("mypassword")); service.changePassword("myhash", "mypassword").getSuccess(); verify(tokenRepositoryMock).delete(token); } @Test public void testChangePasswordButPasswordValidationFails() { User user = newUser().build(); UserResource userResource = newUserResource().withUID("myuid").build(); Token token = new Token(TokenType.RESET_PASSWORD, null, 123L, null, null, null); when(tokenServiceMock.getPasswordResetToken("myhash")).thenReturn(serviceSuccess(token)); when(userRepositoryMock.findOne(123L)).thenReturn(user); when(userMapperMock.mapToResource(user)).thenReturn(userResource); when(passwordPolicyValidatorMock.validatePassword("mypassword", userResource)).thenReturn(ServiceResult.serviceFailure(CommonErrors.badRequestError("bad password"))); ServiceResult<Void> result = service.changePassword("myhash", "mypassword"); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonErrors.badRequestError("bad password"))); verify(tokenRepositoryMock, never()).delete(token); } @Test public void testChangePasswordButPasswordValidationFailsOnIDP() { final User user = newUser().build(); final UserResource userResource = newUserResource().withUID("myuid").build(); final String password = "mypassword"; Token token = new Token(TokenType.RESET_PASSWORD, null, 123L, null, null, null); when(tokenServiceMock.getPasswordResetToken("myhash")).thenReturn(serviceSuccess(token)); when(userRepositoryMock.findOne(123L)).thenReturn(user); when(userMapperMock.mapToResource(user)).thenReturn(userResource); when(passwordPolicyValidatorMock.validatePassword(password, userResource)).thenReturn(serviceSuccess()); when(idpServiceMock.updateUserPassword(anyString(), anyString())).thenReturn(ServiceResult.serviceFailure(CommonErrors.badRequestError("bad password"))); ServiceResult<Void> result = service.changePassword("myhash", password); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonErrors.badRequestError("bad password"))); verify(tokenRepositoryMock, never()).delete(token); } @Test public void testFindInactiveByEmail() { final User user = newUser().build(); final UserResource userResource = newUserResource() .withEmail("[email protected]") .withLastName("A") .withLastName("Bee") .build(); final String email = "[email protected]"; when(userRepositoryMock.findByEmailAndStatus(email, UserStatus.INACTIVE)).thenReturn(of(user)); when(userMapperMock.mapToResource(user)).thenReturn(userResource); final ServiceResult<UserResource> result = service.findInactiveByEmail(email); assertTrue(result.isSuccess()); assertSame(userResource, result.getSuccess()); verify(userRepositoryMock, only()).findByEmailAndStatus(email, UserStatus.INACTIVE); } @Test public void testSendPasswordResetNotification() { String hash = "1234"; UserResource user = newUserResource() .withStatus(UserStatus.ACTIVE) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); UserNotificationTarget to = new UserNotificationTarget(user.getName(), user.getEmail()); Map<String, Object> notificationArgs = asMap("passwordResetLink", "baseUrl/login/reset-password/hash/" + hash); Notification notification = new Notification(systemNotificationSource, to, UserServiceImpl.Notifications.RESET_PASSWORD, notificationArgs); when(notificationServiceMock.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess()); when(randomHashSupplierMock.get()).thenReturn(hash); service.sendPasswordResetNotification(user).getSuccess(); verify(notificationServiceMock).sendNotificationWithFlush(notification, EMAIL); verify(randomHashSupplierMock).get(); } @Test public void testSendPasswordResetNotificationInactiveApplicantNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.APPLICANT)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveApplicantHasVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( asList(Role.APPLICANT, Role.ASSESSOR)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.of(new Token())); when(registrationServiceMock.resendUserVerificationEmail(user)).thenReturn(serviceSuccess()); service.sendPasswordResetNotification(user).getSuccess(); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); } @Test public void testSendPasswordResetNotificationInactiveAssessor() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.ASSESSOR)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveProjectFinance() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.PROJECT_FINANCE)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCompAdmin() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.COMP_ADMIN)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCompExec() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.COMP_EXEC)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCompTechnologist() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.INNOVATION_LEAD)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveLeadApplicantNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE).withRolesGlobal( singletonList(Role.LEADAPPLICANT)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactivePartnerNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE).withRolesGlobal( singletonList(Role.PARTNER)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveProjectManagerNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE).withRolesGlobal( singletonList(Role.PROJECT_MANAGER)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCollaboratorNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.COLLABORATOR)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveFinanceContactNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.FINANCE_CONTACT)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testFindActiveByProcessRoles(){ Set<Role> internalRoles = singleton(Role.PROJECT_FINANCE); Pageable pageable = new PageRequest(0, 5); List<User> activeUsers = newUser().withStatus(UserStatus.ACTIVE).withRoles(internalRoles).build(6); Page<User> expectedPage = new PageImpl<>(activeUsers, pageable, 6L); when(userRepositoryMock.findDistinctByStatusAndRolesIn(UserStatus.ACTIVE, Role.internalRoles().stream().map(r -> Role.getByName(r.getName())).collect(Collectors.toSet()), pageable)).thenReturn(expectedPage); when(userMapperMock.mapToResource(any(User.class))).thenReturn(newUserResource().withFirstName("First").build()); ServiceResult<UserPageResource> result = service.findActiveByRoles(Role.internalRoles(), pageable); assertTrue(result.isSuccess()); assertEquals(5, result.getSuccess().getSize()); assertEquals(2, result.getSuccess().getTotalPages()); assertEquals(6, result.getSuccess().getContent().size()); } @Test public void testFindInactiveByProcessRoles(){ Set<Role> internalRoles = singleton(Role.COMP_ADMIN); Pageable pageable = new PageRequest(0, 5); List<User> inactiveUsers = newUser().withStatus(UserStatus.INACTIVE).withRoles(internalRoles).build(4); Page<User> expectedPage = new PageImpl<>(inactiveUsers, pageable, 4L); when(userRepositoryMock.findDistinctByStatusAndRolesIn(UserStatus.INACTIVE, Role.internalRoles(), pageable)).thenReturn(expectedPage); when(userMapperMock.mapToResource(any(User.class))).thenReturn(newUserResource().withFirstName("First").build()); ServiceResult<UserPageResource> result = service.findInactiveByRoles(Role.internalRoles(), pageable); assertTrue(result.isSuccess()); assertEquals(5, result.getSuccess().getSize()); assertEquals(1, result.getSuccess().getTotalPages()); assertEquals(4, result.getSuccess().getContent().size()); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringIsNull(){ String searchString = null; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringIsEmpty(){ String searchString = ""; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringLengthLessThan5(){ String searchString = "a"; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringIsAllSpaces(){ String searchString = " "; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchCategoryIsName(){ String searchString = "%well%"; SearchCategory searchCategory = SearchCategory.NAME; Set<UserOrganisation> userOrganisations = setUpMockingFindByProcessRolesAndSearchCriteria(); when(userOrganisationRepositoryMock.findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet())).thenReturn(userOrganisations); ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isSuccess()); assertEquals(2, result.getSuccess().size()); assertEquals("Aaron Powell", result.getSuccess().get(0).getName()); assertEquals("Guitar Gods Ltd", result.getSuccess().get(0).getOrganisationName()); assertEquals("Business", result.getSuccess().get(0).getOrganisationType()); assertEquals("David Wellington", result.getSuccess().get(1).getName()); assertEquals("Engine Equations Ltd", result.getSuccess().get(1).getOrganisationName()); assertEquals("Research", result.getSuccess().get(1).getOrganisationType()); verify(userOrganisationRepositoryMock).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); } private Set<UserOrganisation> setUpMockingFindByProcessRolesAndSearchCriteria() { UserOrganisationResource userOrganisationResource1 = newUserOrganisationResource().withName("Aaron Powell") .withOrganisationName("Guitar Gods Ltd") .withOrganisationType("Business") .withEmail("[email protected]").withStatus(UserStatus.ACTIVE) .withOrganisationId(1L).withOrganisationName("Guitar Gods Ltd").build(); UserOrganisationResource userOrganisationResource2 = newUserOrganisationResource().withName("David Wellington") .withOrganisationName("Engine Equations Ltd") .withOrganisationType("Research") .withEmail("[email protected]").withStatus(UserStatus.ACTIVE) .withOrganisationId(2L).withOrganisationName("Engine Equations Ltd").build(); Set<UserOrganisation> userOrganisations = new HashSet<>(newUserOrganisation() .withUser(newUser().withEmailAddress("[email protected]").build(), newUser().withEmailAddress("[email protected]").build()) .withOrganisation(OrganisationBuilder.newOrganisation().withId(1L).withName("Guitar Gods Ltd").build(), OrganisationBuilder.newOrganisation().withId(2L).withName("Engine Equations Ltd").build()) .build(2)); Iterator<UserOrganisation> iterator = userOrganisations.iterator(); when(userOrganisationMapperMock.mapToResource(iterator.next())).thenReturn(userOrganisationResource1); when(userOrganisationMapperMock.mapToResource(iterator.next())).thenReturn(userOrganisationResource2); return userOrganisations; } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchCategoryIsOrganisationName(){ String searchString = "%Ltd%"; SearchCategory searchCategory = SearchCategory.ORGANISATION_NAME; Set<UserOrganisation> userOrganisations = setUpMockingFindByProcessRolesAndSearchCriteria(); when(userOrganisationRepositoryMock.findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet())).thenReturn(userOrganisations); ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isSuccess()); assertEquals(2, result.getSuccess().size()); assertEquals("Guitar Gods Ltd", result.getSuccess().get(0).getOrganisationName()); assertEquals("Engine Equations Ltd", result.getSuccess().get(1).getOrganisationName()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchCategoryIsEmail(){ String searchString = "%com%"; SearchCategory searchCategory = SearchCategory.EMAIL; Set<UserOrganisation> userOrganisations = setUpMockingFindByProcessRolesAndSearchCriteria(); when(userOrganisationRepositoryMock.findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet())).thenReturn(userOrganisations); ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isSuccess()); assertEquals(2, result.getSuccess().size()); assertEquals("[email protected]", result.getSuccess().get(0).getEmail()); assertEquals("[email protected]", result.getSuccess().get(1).getEmail()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); } @Test public void agreeNewTermsAndConditions() { List<SiteTermsAndConditionsResource> siteTermsAndConditions = newSiteTermsAndConditionsResource().build(3); User existingUser = newUser() .withTermsAndConditionsIds(new LinkedHashSet<>(asList( siteTermsAndConditions.get(0).getId(), siteTermsAndConditions.get(1).getId()))) .build(); Set<Long> expectedTermsAndConditionsIds = new LinkedHashSet<>(asList( siteTermsAndConditions.get(0).getId(), siteTermsAndConditions.get(1).getId(), siteTermsAndConditions.get(2).getId() )); when(termsAndConditionsServiceMock.getLatestSiteTermsAndConditions()).thenReturn( serviceSuccess(siteTermsAndConditions.get(2))); when(userRepositoryMock.findOne(existingUser.getId())).thenReturn(existingUser); User userToSave = createUserExpectations(existingUser.getId(), expectedTermsAndConditionsIds); when(userRepositoryMock.save(userToSave)).thenReturn(userToSave); assertTrue(service.agreeNewTermsAndConditions(existingUser.getId()).isSuccess()); InOrder inOrder = inOrder(termsAndConditionsServiceMock, userRepositoryMock); inOrder.verify(termsAndConditionsServiceMock).getLatestSiteTermsAndConditions(); inOrder.verify(userRepositoryMock).findOne(existingUser.getId()); inOrder.verify(userRepositoryMock).save(createUserExpectations(existingUser.getId(), expectedTermsAndConditionsIds)); inOrder.verifyNoMoreInteractions(); } @Test public void grantRole() { GrantRoleCommand grantRoleCommand = new GrantRoleCommand(1L, APPLICANT); User user = newUser().build(); when(userRepositoryMock.findOne(grantRoleCommand.getUserId())).thenReturn(user); ServiceResult<Void> result = service.grantRole(grantRoleCommand); assertTrue(result.isSuccess()); assertTrue(user.hasRole(APPLICANT)); } @Test public void updateEmail() { User user = newUser().build(); String updateEmail = "[email protected]"; List<Invite> invite = singletonList(new RoleInvite("Mister", "[email protected]", "", APPLICANT, OPENED)); when(userRepositoryMock.findOne(user.getId())).thenReturn(user); when(userInviteRepositoryMock.findByEmail(user.getEmail())).thenReturn(invite); when(idpServiceMock.updateUserEmail(anyString(), anyString())).thenReturn(ServiceResult.serviceSuccess("uid")); ServiceResult<Void> result = service.updateEmail(user.getId(), updateEmail); assertTrue(result.isSuccess()); assertEquals("[email protected]", user.getEmail()); } @Test public void updateEmailForNoInviteUsers() { User user = newUser().build(); String updateEmail = "[email protected]"; when(userRepositoryMock.findOne(user.getId())).thenReturn(user); when(userInviteRepositoryMock.findByEmail(user.getEmail())).thenReturn(emptyList()); user.setEmail(updateEmail); when(idpServiceMock.updateUserEmail(anyString(), anyString())).thenReturn(ServiceResult.serviceSuccess("uid")); ServiceResult<Void> result = service.updateEmail(user.getId(), updateEmail); assertTrue(result.isSuccess()); assertEquals("[email protected]", user.getEmail()); } private User createUserExpectations(Long userId, Set<Long> termsAndConditionsIds) { return createLambdaMatcher(user -> { assertEquals(userId, user.getId()); assertEquals(termsAndConditionsIds, user.getTermsAndConditionsIds()); return true; }); } }
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/user/service/UserServiceImplTest.java
package org.innovateuk.ifs.user.service; import org.innovateuk.ifs.BaseServiceUnitTest; import org.innovateuk.ifs.authentication.service.IdentityProviderService; import org.innovateuk.ifs.authentication.validator.PasswordPolicyValidator; import org.innovateuk.ifs.commons.error.CommonErrors; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.resource.SiteTermsAndConditionsResource; import org.innovateuk.ifs.competition.transactional.TermsAndConditionsService; import org.innovateuk.ifs.invite.domain.Invite; import org.innovateuk.ifs.invite.domain.RoleInvite; import org.innovateuk.ifs.invite.repository.UserInviteRepository; import org.innovateuk.ifs.notifications.resource.Notification; import org.innovateuk.ifs.notifications.resource.SystemNotificationSource; import org.innovateuk.ifs.notifications.resource.UserNotificationTarget; import org.innovateuk.ifs.notifications.service.NotificationService; import org.innovateuk.ifs.organisation.builder.OrganisationBuilder; import org.innovateuk.ifs.token.domain.Token; import org.innovateuk.ifs.token.repository.TokenRepository; import org.innovateuk.ifs.token.resource.TokenType; import org.innovateuk.ifs.token.transactional.TokenService; import org.innovateuk.ifs.user.command.GrantRoleCommand; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.mapper.UserMapper; import org.innovateuk.ifs.user.repository.UserRepository; import org.innovateuk.ifs.user.resource.*; import org.innovateuk.ifs.user.transactional.RegistrationService; import org.innovateuk.ifs.user.transactional.UserService; import org.innovateuk.ifs.user.transactional.UserServiceImpl; import org.innovateuk.ifs.userorganisation.domain.UserOrganisation; import org.innovateuk.ifs.userorganisation.mapper.UserOrganisationMapper; import org.innovateuk.ifs.userorganisation.repository.UserOrganisationRepository; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.util.ReflectionTestUtils; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static java.util.Optional.of; import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.USER_SEARCH_INVALID_INPUT_LENGTH; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.SiteTermsAndConditionsResourceBuilder.newSiteTermsAndConditionsResource; import static org.innovateuk.ifs.invite.constant.InviteStatus.OPENED; import static org.innovateuk.ifs.notifications.resource.NotificationMedium.EMAIL; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.innovateuk.ifs.user.builder.UserOrganisationResourceBuilder.newUserOrganisationResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.APPLICANT; import static org.innovateuk.ifs.user.resource.Role.externalApplicantRoles; import static org.innovateuk.ifs.userorganisation.builder.UserOrganisationBuilder.newUserOrganisation; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; /** * Tests of the UserService class */ public class UserServiceImplTest extends BaseServiceUnitTest<UserService> { private static final String WEB_BASE_URL = "baseUrl"; @Captor private ArgumentCaptor<Notification> notificationArgumentCaptor; @Mock private UserOrganisationMapper userOrganisationMapperMock; @Mock private TermsAndConditionsService termsAndConditionsServiceMock; @Mock private TokenService tokenServiceMock; @Mock private UserRepository userRepositoryMock; @Mock private UserMapper userMapperMock; @Mock private PasswordPolicyValidator passwordPolicyValidatorMock; @Mock private IdentityProviderService idpServiceMock; @Mock private TokenRepository tokenRepositoryMock; @Mock private NotificationService notificationServiceMock; @Mock private RegistrationService registrationServiceMock; @Mock private UserOrganisationRepository userOrganisationRepositoryMock; @Mock private SystemNotificationSource systemNotificationSource; @Mock private UserInviteRepository userInviteRepositoryMock; @Mock(name = "randomHashSupplier") private Supplier<String> randomHashSupplierMock; @Override protected UserService supplyServiceUnderTest() { UserServiceImpl spendProfileService = new UserServiceImpl(); ReflectionTestUtils.setField(spendProfileService, "webBaseUrl", WEB_BASE_URL); return spendProfileService; } @Test public void testChangePassword() { User user = newUser().build(); UserResource userResource = newUserResource().withUID("myuid").build(); Token token = new Token(TokenType.RESET_PASSWORD, null, 123L, null, null, null); when(tokenServiceMock.getPasswordResetToken("myhash")).thenReturn(serviceSuccess(token)); when(userRepositoryMock.findOne(123L)).thenReturn(user); when(userMapperMock.mapToResource(user)).thenReturn(userResource); when(passwordPolicyValidatorMock.validatePassword("mypassword", userResource)).thenReturn(serviceSuccess()); when(idpServiceMock.updateUserPassword("myuid", "mypassword")).thenReturn(serviceSuccess("mypassword")); service.changePassword("myhash", "mypassword").getSuccess(); verify(tokenRepositoryMock).delete(token); } @Test public void testChangePasswordButPasswordValidationFails() { User user = newUser().build(); UserResource userResource = newUserResource().withUID("myuid").build(); Token token = new Token(TokenType.RESET_PASSWORD, null, 123L, null, null, null); when(tokenServiceMock.getPasswordResetToken("myhash")).thenReturn(serviceSuccess(token)); when(userRepositoryMock.findOne(123L)).thenReturn(user); when(userMapperMock.mapToResource(user)).thenReturn(userResource); when(passwordPolicyValidatorMock.validatePassword("mypassword", userResource)).thenReturn(ServiceResult.serviceFailure(CommonErrors.badRequestError("bad password"))); ServiceResult<Void> result = service.changePassword("myhash", "mypassword"); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonErrors.badRequestError("bad password"))); verify(tokenRepositoryMock, never()).delete(token); } @Test public void testChangePasswordButPasswordValidationFailsOnIDP() { final User user = newUser().build(); final UserResource userResource = newUserResource().withUID("myuid").build(); final String password = "mypassword"; Token token = new Token(TokenType.RESET_PASSWORD, null, 123L, null, null, null); when(tokenServiceMock.getPasswordResetToken("myhash")).thenReturn(serviceSuccess(token)); when(userRepositoryMock.findOne(123L)).thenReturn(user); when(userMapperMock.mapToResource(user)).thenReturn(userResource); when(passwordPolicyValidatorMock.validatePassword(password, userResource)).thenReturn(serviceSuccess()); when(idpServiceMock.updateUserPassword(anyString(), anyString())).thenReturn(ServiceResult.serviceFailure(CommonErrors.badRequestError("bad password"))); ServiceResult<Void> result = service.changePassword("myhash", password); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonErrors.badRequestError("bad password"))); verify(tokenRepositoryMock, never()).delete(token); } @Test public void testFindInactiveByEmail() { final User user = newUser().build(); final UserResource userResource = newUserResource() .withEmail("[email protected]") .withLastName("A") .withLastName("Bee") .build(); final String email = "[email protected]"; when(userRepositoryMock.findByEmailAndStatus(email, UserStatus.INACTIVE)).thenReturn(of(user)); when(userMapperMock.mapToResource(user)).thenReturn(userResource); final ServiceResult<UserResource> result = service.findInactiveByEmail(email); assertTrue(result.isSuccess()); assertSame(userResource, result.getSuccess()); verify(userRepositoryMock, only()).findByEmailAndStatus(email, UserStatus.INACTIVE); } @Test public void testSendPasswordResetNotification() { String hash = "1234"; UserResource user = newUserResource() .withStatus(UserStatus.ACTIVE) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); UserNotificationTarget to = new UserNotificationTarget(user.getName(), user.getEmail()); Map<String, Object> notificationArgs = asMap("passwordResetLink", "baseUrl/login/reset-password/hash/" + hash); Notification notification = new Notification(systemNotificationSource, to, UserServiceImpl.Notifications.RESET_PASSWORD, notificationArgs); when(notificationServiceMock.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess()); when(randomHashSupplierMock.get()).thenReturn(hash); service.sendPasswordResetNotification(user).getSuccess(); verify(notificationServiceMock).sendNotificationWithFlush(notification, EMAIL); verify(randomHashSupplierMock).get(); } @Test public void testSendPasswordResetNotificationInactiveApplicantNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.APPLICANT)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveApplicantHasVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( asList(Role.APPLICANT, Role.ASSESSOR)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.of(new Token())); when(registrationServiceMock.resendUserVerificationEmail(user)).thenReturn(serviceSuccess()); service.sendPasswordResetNotification(user).getSuccess(); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); } @Test public void testSendPasswordResetNotificationInactiveAssessor() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.ASSESSOR)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveProjectFinance() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.PROJECT_FINANCE)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCompAdmin() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.COMP_ADMIN)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCompExec() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.COMP_EXEC)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCompTechnologist() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.INNOVATION_LEAD)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); ServiceResult<Void> result = service.sendPasswordResetNotification(user); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveLeadApplicantNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE).withRolesGlobal( singletonList(Role.LEADAPPLICANT)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactivePartnerNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE).withRolesGlobal( singletonList(Role.PARTNER)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveProjectManagerNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE).withRolesGlobal( singletonList(Role.PROJECT_MANAGER)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveCollaboratorNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.COLLABORATOR)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testSendPasswordResetNotificationInactiveFinanceContactNoVerifyToken() { final UserResource user = newUserResource() .withStatus(UserStatus.INACTIVE) .withRolesGlobal( singletonList(Role.FINANCE_CONTACT)) .withEmail("[email protected]") .withFirstName("A") .withLastName("Bee") .build(); when(tokenRepositoryMock.findByTypeAndClassNameAndClassPk(TokenType.VERIFY_EMAIL_ADDRESS, User.class.getCanonicalName(), user.getId())).thenReturn(Optional.empty()); ServiceResult<Void> result = service.sendPasswordResetNotification(user); verify(tokenRepositoryMock).findByTypeAndClassNameAndClassPk(any(), any(), any()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(UserResource.class, user.getEmail(),UserStatus.ACTIVE))); } @Test public void testFindActiveByProcessRoles(){ Set<Role> internalRoles = singleton(Role.PROJECT_FINANCE); Pageable pageable = new PageRequest(0, 5); List<User> activeUsers = newUser().withStatus(UserStatus.ACTIVE).withRoles(internalRoles).build(6); Page<User> expectedPage = new PageImpl<>(activeUsers, pageable, 6L); when(userRepositoryMock.findDistinctByStatusAndRolesIn(UserStatus.ACTIVE, Role.internalRoles().stream().map(r -> Role.getByName(r.getName())).collect(Collectors.toSet()), pageable)).thenReturn(expectedPage); when(userMapperMock.mapToResource(any(User.class))).thenReturn(newUserResource().withFirstName("First").build()); ServiceResult<UserPageResource> result = service.findActiveByRoles(Role.internalRoles(), pageable); assertTrue(result.isSuccess()); assertEquals(5, result.getSuccess().getSize()); assertEquals(2, result.getSuccess().getTotalPages()); assertEquals(6, result.getSuccess().getContent().size()); } @Test public void testFindInactiveByProcessRoles(){ Set<Role> internalRoles = singleton(Role.COMP_ADMIN); Pageable pageable = new PageRequest(0, 5); List<User> inactiveUsers = newUser().withStatus(UserStatus.INACTIVE).withRoles(internalRoles).build(4); Page<User> expectedPage = new PageImpl<>(inactiveUsers, pageable, 4L); when(userRepositoryMock.findDistinctByStatusAndRolesIn(UserStatus.INACTIVE, Role.internalRoles(), pageable)).thenReturn(expectedPage); when(userMapperMock.mapToResource(any(User.class))).thenReturn(newUserResource().withFirstName("First").build()); ServiceResult<UserPageResource> result = service.findInactiveByRoles(Role.internalRoles(), pageable); assertTrue(result.isSuccess()); assertEquals(5, result.getSuccess().getSize()); assertEquals(1, result.getSuccess().getTotalPages()); assertEquals(4, result.getSuccess().getContent().size()); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringIsNull(){ String searchString = null; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringIsEmpty(){ String searchString = ""; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringLengthLessThan5(){ String searchString = "a"; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchStringIsAllSpaces(){ String searchString = " "; SearchCategory searchCategory = SearchCategory.NAME; ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isFailure()); assertEquals(USER_SEARCH_INVALID_INPUT_LENGTH.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationMapperMock, never()).mapToResource(any(UserOrganisation.class)); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchCategoryIsName(){ String searchString = "%well%"; SearchCategory searchCategory = SearchCategory.NAME; Set<UserOrganisation> userOrganisations = setUpMockingFindByProcessRolesAndSearchCriteria(); when(userOrganisationRepositoryMock.findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet())).thenReturn(userOrganisations); ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isSuccess()); assertEquals(2, result.getSuccess().size()); assertEquals("Aaron Powell", result.getSuccess().get(0).getName()); assertEquals("Guitar Gods Ltd", result.getSuccess().get(0).getOrganisationName()); assertEquals("Business", result.getSuccess().get(0).getOrganisationType()); assertEquals("David Wellington", result.getSuccess().get(1).getName()); assertEquals("Engine Equations Ltd", result.getSuccess().get(1).getOrganisationName()); assertEquals("Research", result.getSuccess().get(1).getOrganisationType()); verify(userOrganisationRepositoryMock).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); } private Set<UserOrganisation> setUpMockingFindByProcessRolesAndSearchCriteria() { UserOrganisationResource userOrganisationResource1 = newUserOrganisationResource().withName("Aaron Powell") .withOrganisationName("Guitar Gods Ltd") .withOrganisationType("Business") .withEmail("[email protected]").withStatus(UserStatus.ACTIVE) .withOrganisationId(1L).withOrganisationName("Guitar Gods Ltd").build(); UserOrganisationResource userOrganisationResource2 = newUserOrganisationResource().withName("David Wellington") .withOrganisationName("Engine Equations Ltd") .withOrganisationType("Research") .withEmail("[email protected]").withStatus(UserStatus.ACTIVE) .withOrganisationId(2L).withOrganisationName("Engine Equations Ltd").build(); Set<UserOrganisation> userOrganisations = new HashSet<>(newUserOrganisation() .withUser(newUser().withEmailAddress("[email protected]").build(), newUser().withEmailAddress("[email protected]").build()) .withOrganisation(OrganisationBuilder.newOrganisation().withId(1L).withName("Guitar Gods Ltd").build(), OrganisationBuilder.newOrganisation().withId(2L).withName("Engine Equations Ltd").build()) .build(2)); Iterator<UserOrganisation> iterator = userOrganisations.iterator(); when(userOrganisationMapperMock.mapToResource(iterator.next())).thenReturn(userOrganisationResource1); when(userOrganisationMapperMock.mapToResource(iterator.next())).thenReturn(userOrganisationResource2); return userOrganisations; } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchCategoryIsOrganisationName(){ String searchString = "%Ltd%"; SearchCategory searchCategory = SearchCategory.ORGANISATION_NAME; Set<UserOrganisation> userOrganisations = setUpMockingFindByProcessRolesAndSearchCriteria(); when(userOrganisationRepositoryMock.findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet())).thenReturn(userOrganisations); ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isSuccess()); assertEquals(2, result.getSuccess().size()); assertEquals("Guitar Gods Ltd", result.getSuccess().get(0).getOrganisationName()); assertEquals("Engine Equations Ltd", result.getSuccess().get(1).getOrganisationName()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); } @Test public void findByProcessRolesAndSearchCriteriaWhenSearchCategoryIsEmail(){ String searchString = "%com%"; SearchCategory searchCategory = SearchCategory.EMAIL; Set<UserOrganisation> userOrganisations = setUpMockingFindByProcessRolesAndSearchCriteria(); when(userOrganisationRepositoryMock.findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet())).thenReturn(userOrganisations); ServiceResult<List<UserOrganisationResource>> result = service.findByProcessRolesAndSearchCriteria(externalApplicantRoles(), searchString, searchCategory); assertTrue(result.isSuccess()); assertEquals(2, result.getSuccess().size()); assertEquals("[email protected]", result.getSuccess().get(0).getEmail()); assertEquals("[email protected]", result.getSuccess().get(1).getEmail()); verify(userOrganisationRepositoryMock, never()).findByUserFirstNameLikeOrUserLastNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anyString(), anySet()); verify(userOrganisationRepositoryMock, never()).findByOrganisationNameLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); verify(userOrganisationRepositoryMock).findByUserEmailLikeAndUserRolesInOrderByUserEmailAsc(anyString(), anySet()); } @Test public void agreeNewTermsAndConditions() { List<SiteTermsAndConditionsResource> siteTermsAndConditions = newSiteTermsAndConditionsResource().build(3); User existingUser = newUser() .withTermsAndConditionsIds(new LinkedHashSet<>(asList( siteTermsAndConditions.get(0).getId(), siteTermsAndConditions.get(1).getId()))) .build(); Set<Long> expectedTermsAndConditionsIds = new LinkedHashSet<>(asList( siteTermsAndConditions.get(0).getId(), siteTermsAndConditions.get(1).getId(), siteTermsAndConditions.get(2).getId() )); when(termsAndConditionsServiceMock.getLatestSiteTermsAndConditions()).thenReturn( serviceSuccess(siteTermsAndConditions.get(2))); when(userRepositoryMock.findOne(existingUser.getId())).thenReturn(existingUser); User userToSave = createUserExpectations(existingUser.getId(), expectedTermsAndConditionsIds); when(userRepositoryMock.save(userToSave)).thenReturn(userToSave); assertTrue(service.agreeNewTermsAndConditions(existingUser.getId()).isSuccess()); InOrder inOrder = inOrder(termsAndConditionsServiceMock, userRepositoryMock); inOrder.verify(termsAndConditionsServiceMock).getLatestSiteTermsAndConditions(); inOrder.verify(userRepositoryMock).findOne(existingUser.getId()); inOrder.verify(userRepositoryMock).save(createUserExpectations(existingUser.getId(), expectedTermsAndConditionsIds)); inOrder.verifyNoMoreInteractions(); } @Test public void grantRole() { GrantRoleCommand grantRoleCommand = new GrantRoleCommand(1L, APPLICANT); User user = newUser().build(); when(userRepositoryMock.findOne(grantRoleCommand.getUserId())).thenReturn(user); ServiceResult<Void> result = service.grantRole(grantRoleCommand); assertTrue(result.isSuccess()); assertTrue(user.hasRole(APPLICANT)); } @Test public void updateEmail() { User user = newUser().build(); String updateEmail = "[email protected]"; List<Invite> invite = singletonList(new RoleInvite("Mister", "[email protected]", "", APPLICANT, OPENED)); when(userRepositoryMock.findOne(user.getId())).thenReturn(user); when(userInviteRepositoryMock.findByEmail(user.getEmail())).thenReturn(invite); when(idpServiceMock.updateUserEmail(anyString(), anyString())).thenReturn(ServiceResult.serviceSuccess("uid")); ServiceResult<Void> result = service.updateEmail(user.getId(), updateEmail); assertTrue(result.isSuccess()); assertTrue(user.getEmail().equals("[email protected]")); } private User createUserExpectations(Long userId, Set<Long> termsAndConditionsIds) { return createLambdaMatcher(user -> { assertEquals(userId, user.getId()); assertEquals(termsAndConditionsIds, user.getTermsAndConditionsIds()); return true; }); } }
Test to update emails for users with no invite added
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/user/service/UserServiceImplTest.java
Test to update emails for users with no invite added
<ide><path>fs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/user/service/UserServiceImplTest.java <ide> import java.util.stream.Collectors; <ide> <ide> import static java.util.Arrays.asList; <del>import static java.util.Collections.singleton; <del>import static java.util.Collections.singletonList; <add>import static java.util.Collections.*; <ide> import static java.util.Optional.of; <ide> import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher; <ide> import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; <ide> ServiceResult<Void> result = service.updateEmail(user.getId(), updateEmail); <ide> <ide> assertTrue(result.isSuccess()); <del> assertTrue(user.getEmail().equals("[email protected]")); <add> assertEquals("[email protected]", user.getEmail()); <add> } <add> <add> @Test <add> public void updateEmailForNoInviteUsers() { <add> <add> User user = newUser().build(); <add> String updateEmail = "[email protected]"; <add> <add> when(userRepositoryMock.findOne(user.getId())).thenReturn(user); <add> when(userInviteRepositoryMock.findByEmail(user.getEmail())).thenReturn(emptyList()); <add> user.setEmail(updateEmail); <add> when(idpServiceMock.updateUserEmail(anyString(), anyString())).thenReturn(ServiceResult.serviceSuccess("uid")); <add> <add> ServiceResult<Void> result = service.updateEmail(user.getId(), updateEmail); <add> <add> assertTrue(result.isSuccess()); <add> assertEquals("[email protected]", user.getEmail()); <ide> } <ide> <ide> private User createUserExpectations(Long userId, Set<Long> termsAndConditionsIds) {
JavaScript
cc0-1.0
3b78aa0ae64cb348d44a778d462b82f889cd294c
0
melrodbos/TIY-Assignments,melrodbos/TIY-Assignments
var expect = require("chai").expect; function toNumber(word) { if (word === "zero") { return 0; } if (word === "one") { return 1; } if (word === "two") { return 2; } if (word === "three") { return 3; } if (word === "four") { return 4; } if (word === "five") { return 5; } if (word === "six") { return 6; } if (word === "seven") { return 7; } if (word === "eight") { return 8; } if (word === "nine") { return 9; } } expect(toNumber("zero")).to.equal(0); expect(toNumber("one")).to.equal(1); expect(toNumber("two")).to.equal(2); expect(toNumber("three")).to.equal(3); expect(toNumber("four")).to.equal(4); expect(toNumber("five")).to.equal(5); expect(toNumber("six")).to.equal(6); expect(toNumber("seven")).to.equal(7); expect(toNumber("eight")).to.equal(8); expect(toNumber("nine")).to.equal(9); function plus(A, B) { return toNumber(A) + toNumber(B); } expect(plus).to.exist; expect(plus("zero", "zero")).to.equal(0); expect(plus("zero", "one")).to.equal(1); expect(plus("zero", "two")).to.equal(2); expect(plus("zero", "three")).to.equal(3); expect(plus("zero", "four")).to.equal(4); expect(plus("zero", "five")).to.equal(5); expect(plus("zero", "six")).to.equal(6); expect(plus("zero", "seven")).to.equal(7); expect(plus("zero", "eight")).to.equal(8); expect(plus("zero", "nine")).to.equal(9); expect(plus("zero", "one")).to.equal(1); expect(plus("one", "one")).to.equal(2); expect(plus("one", "one")).to.equal(2); expect(plus("one", "two")).to.equal(3); expect(plus("one", "three")).to.equal(4); expect(plus("one", "four")).to.equal(5); expect(plus("one", "five")).to.equal(6); expect(plus("one", "six")).to.equal(7); expect(plus("one", "seven")).to.equal(8); expect(plus("one", "eight")).to.equal(9); expect(plus("one", "nine")).to.equal(10); expect(plus("two", "zero")).to.equal(2); expect(plus("two", "one")).to.equal(3); expect(plus("two", "two")).to.equal(4); expect(plus("two", "three")).to.equal(5); expect(plus("two", "four")).to.equal(6); expect(plus("two", "five")).to.equal(7); expect(plus("two", "six")).to.equal(8); expect(plus("two", "seven")).to.equal(9); expect(plus("two", "eight")).to.equal(10); expect(plus("two", "nine")).to.equal(11); expect(plus("three", "zero")).to.equal(3); expect(plus("three", "one")).to.equal(4); expect(plus("three", "two")).to.equal(5); expect(plus("three", "three")).to.equal(6); expect(plus("three", "four")).to.equal(7); expect(plus("three", "five")).to.equal(8); expect(plus("three", "six")).to.equal(9); expect(plus("three", "seven")).to.equal(10); expect(plus("three", "eight")).to.equal(11); expect(plus("three", "nine")).to.equal(12); expect(plus("four", "zero")).to.equal(4); expect(plus("four", "one")).to.equal(5); expect(plus("four", "two")).to.equal(6); expect(plus("four", "three")).to.equal(7); expect(plus("four", "four")).to.equal(8); expect(plus("four", "five")).to.equal(9); expect(plus("four", "six")).to.equal(10); expect(plus("four", "seven")).to.equal(11); expect(plus("four", "eight")).to.equal(12); expect(plus("four", "nine")).to.equal(13); expect(plus("five", "zero")).to.equal(5); expect(plus("five", "one")).to.equal(6); expect(plus("five", "two")).to.equal(7); expect(plus("five", "three")).to.equal(8); expect(plus("five", "four")).to.equal(9); expect(plus("five", "five")).to.equal(10); expect(plus("five", "six")).to.equal(11); expect(plus("five", "seven")).to.equal(12); expect(plus("five", "eight")).to.equal(13); expect(plus("five", "nine")).to.equal(14); expect(plus("six", "zero")).to.equal(6); expect(plus("six", "one")).to.equal(7); expect(plus("six", "two")).to.equal(8); expect(plus("six", "three")).to.equal(9); expect(plus("six", "four")).to.equal(10); expect(plus("six", "five")).to.equal(11); expect(plus("six", "six")).to.equal(12); expect(plus("six", "seven")).to.equal(13); expect(plus("six", "eight")).to.equal(14); expect(plus("six", "nine")).to.equal(15); expect(plus("seven", "zero")).to.equal(7); expect(plus("seven", "one")).to.equal(8); expect(plus("seven", "two")).to.equal(9); expect(plus("seven", "three")).to.equal(10); expect(plus("seven", "four")).to.equal(11); expect(plus("seven", "five")).to.equal(12); expect(plus("seven", "six")).to.equal(13); expect(plus("seven", "seven")).to.equal(14); expect(plus("seven", "eight")).to.equal(15); expect(plus("seven", "nine")).to.equal(16); expect(plus("eight", "zero")).to.equal(8); expect(plus("eight", "one")).to.equal(9); expect(plus("eight", "two")).to.equal(10); expect(plus("eight", "three")).to.equal(11); expect(plus("eight", "four")).to.equal(12); expect(plus("eight", "five")).to.equal(13); expect(plus("eight", "six")).to.equal(14); expect(plus("eight", "seven")).to.equal(15); expect(plus("eight", "eight")).to.equal(16); expect(plus("eight", "nine")).to.equal(17); expect(plus("nine", "zero")).to.equal(9); expect(plus("nine", "one")).to.equal(10); expect(plus("nine", "two")).to.equal(11); expect(plus("nine", "three")).to.equal(12); expect(plus("nine", "four")).to.equal(13); expect(plus("nine", "five")).to.equal(14); expect(plus("nine", "six")).to.equal(15); expect(plus("nine", "seven")).to.equal(16); expect(plus("nine", "eight")).to.equal(17); expect(plus("nine", "nine")).to.equal(18); console.log(plus("zero", "zero")); console.log(plus("zero", "one")); function minus(A, B) { return toNumber(A) - toNumber(B); } expect(minus).to.exist; expect(minus("zero", "zero")).to.equal(0); expect(minus("zero", "one")).to.equal(-1); expect(minus("zero", "two")).to.equal(-2); expect(minus("zero", "three")).to.equal(-3); expect(minus("zero", "four")).to.equal(-4); expect(minus("zero", "five")).to.equal(-5); expect(minus("zero", "six")).to.equal(-6); expect(minus("zero", "seven")).to.equal(-7); expect(minus("zero", "eight")).to.equal(-8); expect(minus("zero", "nine")).to.equal(-9); expect(minus).to.exist; expect(minus("one", "zero")).to.equal(1); expect(minus("one", "one")).to.equal(0); expect(minus("one", "two")).to.equal(-1); expect(minus("one", "three")).to.equal(-2); expect(minus("one", "four")).to.equal(-3); expect(minus("one", "five")).to.equal(-4); expect(minus("one", "six")).to.equal(-5); expect(minus("one", "seven")).to.equal(-6); expect(minus("one", "eight")).to.equal(-7); expect(minus("one", "nine")).to.equal(-8); expect(minus).to.exist; expect(minus("two", "zero")).to.equal(2); expect(minus("two", "one")).to.equal(1); expect(minus("two", "two")).to.equal(0); expect(minus("two", "three")).to.equal(-1); expect(minus("two", "four")).to.equal(-2); expect(minus("two", "five")).to.equal(-3); expect(minus("two", "six")).to.equal(-4); expect(minus("two", "seven")).to.equal(-5); expect(minus("two", "eight")).to.equal(-6); expect(minus("two", "nine")).to.equal(-7); expect(minus).to.exist; expect(minus("three", "zero")).to.equal(3); expect(minus("three", "one")).to.equal(2); expect(minus("three", "two")).to.equal(1); expect(minus("three", "three")).to.equal(0); expect(minus("three", "four")).to.equal(-1); expect(minus("three", "five")).to.equal(-2); expect(minus("three", "six")).to.equal(-3); expect(minus("three", "seven")).to.equal(-4); expect(minus("three", "eight")).to.equal(-5); expect(minus("three", "nine")).to.equal(-6); expect(minus("four", "zero")).to.equal(4); expect(minus("four", "one")).to.equal(3); expect(minus("four", "two")).to.equal(2); expect(minus("four", "three")).to.equal(1); expect(minus("four", "four")).to.equal(0); expect(minus("four", "five")).to.equal(-1); expect(minus("four", "six")).to.equal(-2); expect(minus("four", "seven")).to.equal(-3); expect(minus("four", "eight")).to.equal(-4); expect(minus("four", "nine")).to.equal(-5); expect(minus("five", "zero")).to.equal(5); expect(minus("five", "one")).to.equal(4); expect(minus("five", "two")).to.equal(3); expect(minus("five", "three")).to.equal(2); expect(minus("five", "four")).to.equal(1); expect(minus("five", "five")).to.equal(0); expect(minus("five", "six")).to.equal(-1); expect(minus("five", "seven")).to.equal(-2); expect(minus("five", "eight")).to.equal(-3); expect(minus("five", "nine")).to.equal(-4); expect(minus("six","zero")).to.equal(6); expect(minus("six", "one")).to.equal(5); expect(minus("six", "two")).to.equal(4); expect(minus("six", "three")).to.equal(3); expect(minus("six", "four")).to.equal(2); expect(minus("six", "five")).to.equal(1); expect(minus("six", "six")).to.equal(0); expect(minus("six", "seven")).to.equal(-1); expect(minus("six", "eight")).to.equal(-2); expect(minus("six", "nine")).to.equal(-3); expect(minus("seven", "zero")).to.equal(7); expect(minus("seven", "one")).to.equal(6); expect(minus("seven", "two")).to.equal(5); expect(minus("seven", "three")).to.equal(4); expect(minus("seven", "four")).to.equal(3); expect(minus("seven", "five")).to.equal(2); expect(minus("seven", "six")).to.equal(1); expect(minus("seven", "seven")).to.equal(0); expect(minus("seven", "eight")).to.equal(-1); expect(minus("seven", "nine")).to.equal(-2); expect(minus("eight", "zero")).to.equal(8); expect(minus("eight", "one")).to.equal(7); expect(minus("eight", "two")).to.equal(6); expect(minus("eight", "three")).to.equal(5); expect(minus("eight", "four")).to.equal(4); expect(minus("eight", "five")).to.equal(3); expect(minus("eight","six")).to.equal(2); expect(minus("eight", "seven")).to.equal(1); expect(minus("eight", "eight")).to.equal(0); expect(minus("eight", "nine")).to.equal(-1); expect(minus("nine", "zero")).to.equal(9); expect(minus("nine", "one")).to.equal(8); expect(minus("nine", "two")).to.equal(7); expect(minus("nine", "three")).to.equal(6); expect(minus("nine", "four")).to.equal(5); expect(minus("nine", "five")).to.equal(4); expect(minus("nine", "six")).to.equal(3); expect(minus("nine", "seven")).to.equal(2); expect(minus("nine", "eight")).to.equal(1); expect(minus("nine", "nine")).to.equal(0) console.log(minus("zero", "zero")); console.log(minus("zero", "one"));
string-calculator.js
var expect = require("chai").expect; function toNumber(word) { if (word === "zero") { return 0; } if (word === "one") { return 1; } if (word === "two") { return 2; } if (word === "three") { return 3; } if (word === "four") { return 4; } if (word === "five") { return 5; } if (word === "six") { return 6; } if (word === "seven") { return 7; } if (word === "eight") { return 8; } if (word === "nine") { return 9; } } expect(toNumber("zero")).to.equal(0); expect(toNumber("one")).to.equal(1); expect(toNumber("two")).to.equal(2); expect(toNumber("three")).to.equal(3); expect(toNumber("four")).to.equal(4); expect(toNumber("five")).to.equal(5); expect(toNumber("six")).to.equal(6); expect(toNumber("seven")).to.equal(7); expect(toNumber("eight")).to.equal(8); expect(toNumber("nine")).to.equal(9); function plus(A, B) { return toNumber(A) + toNumber(B); } expect(plus).to.exist; expect(plus("zero", "zero")).to.equal(0); expect(plus("zero", "one")).to.equal(1); expect(plus("zero", "two")).to.equal(2); expect(plus("zero", "three")).to.equal(3); expect(plus("zero", "four")).to.equal(4); expect(plus("zero", "five")).to.equal(5); expect(plus("zero", "six")).to.equal(6); expect(plus("zero", "seven")).to.equal(7); expect(plus("zero", "eight")).to.equal(8); expect(plus("zero", "nine")).to.equal(9); expect(plus("zero", "one")).to.equal(1); expect(plus("one", "one")).to.equal(2); expect(plus("one", "one")).to.equal(2); expect(plus("one", "two")).to.equal(3); expect(plus("one", "three")).to.equal(4); expect(plus("one", "four")).to.equal(5); expect(plus("one", "five")).to.equal(6); expect(plus("one", "six")).to.equal(7); expect(plus("one", "seven")).to.equal(8); expect(plus("one", "eight")).to.equal(9); expect(plus("one", "nine")).to.equal(10); expect(plus("two", "zero")).to.equal(2); expect(plus("two", "one")).to.equal(3); expect(plus("two", "two")).to.equal(4); expect(plus("two", "three")).to.equal(5); expect(plus("two", "four")).to.equal(6); expect(plus("two", "five")).to.equal(7); expect(plus("two", "six")).to.equal(8); expect(plus("two", "seven")).to.equal(9); expect(plus("two", "eight")).to.equal(10); expect(plus("two", "nine")).to.equal(11); expect(plus("three", "zero")).to.equal(3); expect(plus("three", "one")).to.equal(4); expect(plus("three", "two")).to.equal(5); expect(plus("three", "three")).to.equal(6); expect(plus("three", "four")).to.equal(7); expect(plus("three", "five")).to.equal(8); expect(plus("three", "six")).to.equal(9); expect(plus("three", "seven")).to.equal(10); expect(plus("three", "eight")).to.equal(11); expect(plus("three", "nine")).to.equal(12); expect(plus("four", "zero")).to.equal(4); expect(plus("four", "one")).to.equal(5); expect(plus("four", "two")).to.equal(6); expect(plus("four", "three")).to.equal(7); expect(plus("four", "four")).to.equal(8); expect(plus("four", "five")).to.equal(9); expect(plus("four", "six")).to.equal(10); expect(plus("four", "seven")).to.equal(11); expect(plus("four", "eight")).to.equal(12); expect(plus("four", "nine")).to.equal(13); expect(plus("five", "zero")).to.equal(5); expect(plus("five", "one")).to.equal(6); expect(plus("five", "two")).to.equal(7); expect(plus("five", "three")).to.equal(8); expect(plus("five", "four")).to.equal(9); expect(plus("five", "five")).to.equal(10); expect(plus("five", "six")).to.equal(11); expect(plus("five", "seven")).to.equal(12); expect(plus("five", "eight")).to.equal(13); expect(plus("five", "nine")).to.equal(14); expect(plus("six", "zero")).to.equal(6); expect(plus("six", "one")).to.equal(7); expect(plus("six", "two")).to.equal(8); expect(plus("six", "three")).to.equal(9); expect(plus("six", "four")).to.equal(10); expect(plus("six", "five")).to.equal(11); expect(plus("six", "six")).to.equal(12); expect(plus("six", "seven")).to.equal(13); expect(plus("six", "eight")).to.equal(14); expect(plus("six", "nine")).to.equal(15); expect(plus("seven", "zero")).to.equal(7); expect(plus("seven", "one")).to.equal(8); expect(plus("seven", "two")).to.equal(9); expect(plus("seven", "three")).to.equal(10); expect(plus("seven", "four")).to.equal(11); expect(plus("seven", "five")).to.equal(12); expect(plus("seven", "six")).to.equal(13); expect(plus("seven", "seven")).to.equal(14); expect(plus("seven", "eight")).to.equal(15); expect(plus("seven", "nine")).to.equal(16); expect(plus("eight", "zero")).to.equal(8); expect(plus("eight", "one")).to.equal(9); expect(plus("eight", "two")).to.equal(10); expect(plus("eight", "three")).to.equal(11); expect(plus("eight", "four")).to.equal(12); expect(plus("eight", "five")).to.equal(13); expect(plus("eight", "six")).to.equal(14); expect(plus("eight", "seven")).to.equal(15); expect(plus("eight", "eight")).to.equal(16); expect(plus("eight", "nine")).to.equal(17); expect(plus("nine", "zero")).to.equal(9); expect(plus("nine", "one")).to.equal(10); expect(plus("nine", "two")).to.equal(11); expect(plus("nine", "three")).to.equal(12); expect(plus("nine", "four")).to.equal(13); expect(plus("nine", "five")).to.equal(14); expect(plus("nine", "six")).to.equal(15); expect(plus("nine", "seven")).to.equal(16); expect(plus("nine", "eight")).to.equal(17); expect(plus("nine", "nine")).to.equal(18); console.log(plus("zero", "zero")); console.log(plus("zero", "one")); function minus(A, B) { return toNumber(A) - toNumber(B); } expect(minus).to.exist; expect(minus("zero", "zero")).to.equal(0); expect(minus("zero", "one")).to.equal(-1); expect(minus("zero", "two")).to.equal(-2); expect(minus("zero", "three")).to.equal(-3); expect(minus("zero", "four")).to.equal(-4); expect(minus("zero", "five")).to.equal(-5); expect(minus("zero", "six")).to.equal(-6); expect(minus("zero", "seven")).to.equal(-7); expect(minus("zero", "eight")).to.equal(-8); expect(minus("zero", "nine")).to.equal(-9); expect(minus).to.exist; expect(minus("one", "zero")).to.equal(1); expect(minus("one", "one")).to.equal(0); expect(minus("one", "two")).to.equal(-1); expect(minus("one", "three")).to.equal(-2); expect(minus("one", "four")).to.equal(-3); expect(minus("one", "five")).to.equal(-4); expect(minus("one", "six")).to.equal(-5); expect(minus("one", "seven")).to.equal(-6); expect(minus("one", "eight")).to.equal(-7); expect(minus("one", "nine")).to.equal(-8); expect(minus).to.exist; expect(minus("two", "zero")).to.equal(2); expect(minus("two", "one")).to.equal(1); expect(minus("two", "two")).to.equal(0); expect(minus("two", "three")).to.equal(-1); expect(minus("two", "four")).to.equal(-2); expect(minus("two", "five")).to.equal(-3); expect(minus("two", "six")).to.equal(-4); expect(minus("two", "seven")).to.equal(-5); expect(minus("two", "eight")).to.equal(-6); expect(minus("two", "nine")).to.equal(-7); expect(minus).to.exist; expect(minus("three", "zero")).to.equal(3); expect(minus("three", "one")).to.equal(2); expect(minus("three", "two")).to.equal(1); expect(minus("three", "three")).to.equal(0); expect(minus("three", "four")).to.equal(-1); expect(minus("three", "five")).to.equal(-2); expect(minus("three", "six")).to.equal(-3); expect(minus("three", "seven")).to.equal(-4); expect(minus("three", "eight")).to.equal(-5); expect(minus("three", "nine")).to.equal(-6); expect(minus("four", "zero")).to.equal(4); expect(minus("four", "one")).to.equal(3); expect(minus("four", "two")).to.equal(2); expect(minus("four", "three")).to.equal(1); expect(minus("four", "four")).to.equal(0); expect(minus("four", "five")).to.equal(-1); expect(minus("four", "six")).to.equal(-2); expect(minus("four", "seven")).to.equal(-3); expect(minus("four", "eight")).to.equal(-4); expect(minus("four", "nine")).to.equal(-5); expect(minus("five", "zero")).to.equal(5); expect(minus("five", "one")).to.equal(4); expect(minus("five", "two")).to.equal(3); expect(minus("five", "three")).to.equal(2); expect(minus("five", "four")).to.equal(1); expect(minus("five", "five")).to.equal(0); expect(minus("five", "six")).to.equal(-1); expect(minus("five", "seven")).to.equal(-2); expect(minus("five", "eight")).to.equal(-3); expect(minus("five", "nine")).to.equal(-4); expect(minus("six","zero")).to.equal(6); expect(minus("six", "one")).to.equal(5); expect(minus("six", "two")).to.equal(4); expect(minus("six", "three")).to.equal(3); expect(minus("six", "four")).to.equal(2); expect(minus("six", "five")).to.equal(1); expect(minus("six", "six")).to.equal(0); expect(minus("six", "seven")).to.equal(-1); expect(minus("six", "eight")).to.equal(-2); expect(minus("six", "nine")).to.equal(-3); expect(minus("seven", "zero")).to.equal(7); expect(minus("seven", "one")).to.equal(6); expect(minus("seven", "two")).to.equal(5); expect(minus("seven", "three")).to.equal(4); expect(minus("seven", "four")).to.equal(3); expect(minus("seven", "five")).to.equal(2); expect(minus("seven", "six")).to.equal(1); expect(minus("seven", "seven")).to.equal(0); expect(minus("seven", "eight")).to.equal(-1); expect(minus("seven", "nine")).to.equal(-2); expect(minus("eight", "zero")).to.equal(8); expect(minus("eight", "one")).to.equal(7); expect(minus("eight", "two")).to.equal(6); expect(minus("eight", "three")).to.equal(5); expect(minus("eight", "four")).to.equal(4); expect(minus("eight", "five")).to.equal(3); expect(minus("eight","six")).to.equal(2); expect(minus("eight", "seven")).to.equal(1); expect(minus("eight", "eight")).to.equal(0); expect(minus("eight", "nine")).to.equal(-1); console.log(minus("zero", "zero")); console.log(minus("zero", "one"));
subtraction test pass and complete
string-calculator.js
subtraction test pass and complete
<ide><path>tring-calculator.js <ide> expect(minus("eight", "eight")).to.equal(0); <ide> expect(minus("eight", "nine")).to.equal(-1); <ide> <del> <add>expect(minus("nine", "zero")).to.equal(9); <add>expect(minus("nine", "one")).to.equal(8); <add>expect(minus("nine", "two")).to.equal(7); <add>expect(minus("nine", "three")).to.equal(6); <add>expect(minus("nine", "four")).to.equal(5); <add>expect(minus("nine", "five")).to.equal(4); <add>expect(minus("nine", "six")).to.equal(3); <add>expect(minus("nine", "seven")).to.equal(2); <add>expect(minus("nine", "eight")).to.equal(1); <add>expect(minus("nine", "nine")).to.equal(0) <ide> <ide> console.log(minus("zero", "zero")); <ide> console.log(minus("zero", "one"));
Java
mit
be92bc58317ad4b467085c6ccebc0f543dbf59ab
0
csonuryilmaz/heybot,csonuryilmaz/heybot
package heybot; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import utilities.Properties; import operation.*; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.http.util.TextUtils; import org.apache.commons.io.comparator.NameFileComparator; import org.apache.commons.lang3.StringUtils; import utilities.Copy; import utilities.Editor; import utilities.Open; public class heybot { private final static String VERSION = "2.6.2.5"; private static final String NEWLINE = System.getProperty("line.separator"); public static final String WORKSPACE = System.getProperty("user.home") + "/.heybot/workspace"; public static void main(String[] args) { printLogo(); printVersion(); createWorkspaceIfNotExists(); if (args.length > 0) { processArgs(args); } else { printHelp(); } } private static void processArgs(String[] args) { CommandLine line = getParser(buildOptions(), args); if (line.hasOption("help")) { printHelp(); } else if (line.hasOption("version")) { printVersionDetailed(); } else if (line.hasOption("list")) { listAllOperations(); } else if (line.hasOption("list-prefix")) { listOperationsStartsWith(line.getOptionValue("list-prefix")); } else if (line.hasOption("insert")) { if (line.getArgs().length > 0) { insertOperationParameters(line.getOptionValue("insert"), line.getArgs()); } else { System.err.println("Ooops! Please add parameters after operation."); } } else if (line.hasOption("select")) { selectOperationParameters(line.getOptionValue("select"), line.getArgs()); } else if (line.hasOption("open")) { openOperation(line.getOptionValue("open")); } else if (line.hasOption("remove")) { removeOperation(line.getOptionValue("remove")); } else if (line.hasOption("editor")) { setDefaultEditor(line.getOptionValue("editor")); } else if (line.hasOption("copy")) { copyOperation(line); } else { start(line); } } private static void listAllOperations() { listFiles(new File(WORKSPACE).listFiles((File dir, String name) -> name.toLowerCase().endsWith(".hb"))); } private static void listOperationsStartsWith(String prefix) { listFiles(new File(WORKSPACE).listFiles((File dir, String name) -> name.toLowerCase().startsWith(prefix.toLowerCase()) && name.toLowerCase().endsWith(".hb"))); } private static void listFiles(File[] files) { if (files != null) { Arrays.sort(files, NameFileComparator.NAME_COMPARATOR); for (File file : files) { System.out.println(file.getName()); } printTotalOperationsFound(files.length); } else { printTotalOperationsFound(0); } } private static void printTotalOperationsFound(int count) { System.out.println(); System.out.println("Total " + count + " operation(s) found."); } private static void printVersionDetailed() { System.out.println("Copyright (c) 2017 Onur Yılmaz"); System.out.println("MIT License: <https://github.com/csonuryilmaz/heybot/blob/master/LICENSE.txt>"); System.out.println("This is free software: you are free to change and redistribute it."); System.out.println("There is NO WARRANTY, to the extent permitted by law."); } private static void start(CommandLine line) { String[] args = line.getArgs(); if (args.length > 1) { processOperation(args[0], Arrays.copyOfRange(args, 1, args.length)); } else if (args.length == 1) { processOperation(args[0], new String[0]); } else { String doOptionValue = line.getOptionValue("do"); if (!TextUtils.isEmpty(doOptionValue)) { processOperation(doOptionValue, new String[0]); } else { System.err.println("Ooops! Unrecognized argument. Please refer to documentation."); } } } private static void processOperation(String operation, String[] parameters) { try { tryExecute(getFullPath(getFileName(operation)), parameters); } catch (Exception ex) { System.err.println("Ooops! An error occurred while executing [" + operation + "]"); printException(ex); if (ex.getCause() != null) { System.err.println(NEWLINE+"It has a cause. See below for details."); printException(ex.getCause()); } } } private static void printException(Throwable exception) { System.err.println("Exception:\t" + exception.getClass().getCanonicalName()); System.err.println("Message:\t" + exception.getMessage()); System.err.println("StackTrace:"); exception.printStackTrace(); } private static String getFileName(String arg) { return arg.endsWith(".hb") ? arg : arg + ".hb"; } private static void tryExecute(String hbFile, String[] parameters) throws Exception { Properties prop = new Properties(); prop.load(hbFile); Operation operation = getOperation(prop, parameters); if (operation != null) { insertOnTheFlyParameters(operation, prop, parameters); operation.start(prop); } } private static void insertOnTheFlyParameters(Operation operation, Properties prop, String[] parameters) { if (parameters.length > 0) { String value; if (operation instanceof BeginIssue) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } } else if (operation instanceof Review) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } } else if (operation instanceof BeginIssueWithGit) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } } else if (operation instanceof UploadGitDiff) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } else { System.out.println("[w] ISSUE parameter will be used from .hb file. Can't override."); } } } } private static String parseIssue(String parameter) { parameter = StringUtils.trimToEmpty(parameter); parameter = parameter.replaceAll("[^\\d.]", ""); try { return String.valueOf(Integer.parseUnsignedInt(parameter)); } catch (NumberFormatException e) { System.out.println(e.getMessage() + " Tried to parse value: " + parameter); return ""; } } private static Operation getOperation(Properties prop, String[] parameters) throws Exception { String opValue = prop.getProperty("OPERATION"); if (TextUtils.isEmpty(opValue)) { System.err.println("Ooops! Parameter OPERATION not found in .hb file."); } else { opValue = opValue.toLowerCase(new Locale("tr-TR")); switch (opValue) { case "upload": return new Upload(); case "upload-git-diff": return new UploadGitDiff(); case "upload-file": return new UploadFile(parameters.length > 0 ? parameters[0] : ""); case "cleanup": return new Cleanup(); case "review": return new Review(); case "check-new": return new CheckNew(); case "cleanup-svn": return new CleanupSvn(); case "sync-issue": return new SyncIssue(); case "next-version": return new NextVersion(); case "release": return new Release(); case "begin-issue": return new BeginIssue(); case "snapshot": return new Snapshot(); case "begin-issue-with-git": return new BeginIssueWithGit(); default: System.err.println("Ooops! Unsupported operation. Please check version and manual."); } } return null; } private static String getFullPath(String hbFile) { if (hbFile.contains("/")) { return hbFile; // already full path is given } else { return WORKSPACE + "/" + hbFile; } } private static void createWorkspaceIfNotExists() { File workspace = new File(WORKSPACE); if (!workspace.exists()) { if (!workspace.mkdirs()) { System.err.println("[e] Workspace folder not found and could not be created!"); System.err.println("[e] " + workspace.getAbsolutePath()); System.exit(-1); } } } //<editor-fold defaultstate="collapsed" desc="help"> private static final String HEADER = NEWLINE + "Designed to help developers on their day-to-day development activities. Works in subversion and redmine ecosystem." + NEWLINE + NEWLINE; private static final String FOOTER = NEWLINE + "Report bugs to \"[email protected]\" " + NEWLINE + " or drop an issue @ http://bit.ly/2S83xvy" + NEWLINE + "Releases: http://bit.ly/2BukdrR" + NEWLINE + "Document: http://bit.ly/2Sd8zqQ" + NEWLINE + NEWLINE + "Happy coding!" + NEWLINE; private static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new MyOptionComparator()); formatter.printHelp("heybot", HEADER, buildOptions(), FOOTER, true); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="syntax"> private static Options buildOptions() { Options options = new Options(); options.addOption("d", "do", true, "Heybot operation file with .hb extension." + NEWLINE + "something.hb"); options.getOption("do").setRequired(true); options.addOption("h", "help", false, "Prints this help message."); options.addOption("v", "version", false, "Prints detailed version information."); options.addOption("l", "list", false, "Lists all operation files in workspace."); options.addOption("lp", "list-prefix", true, "Lists operation files in workspace which starts with given value."); options.addOption("i", "insert", true, "Inserts (by replacing if exists) given parameter values of an operation."); options.addOption("s", "select", true, "Selects all parameters with values of an operation"); options.addOption("o", "open", true, "Opens operation file by default external editor in order to view or modify."); options.addOption("r", "remove", true, "Removes operation file from workspace."); Option editor = new Option("e", "editor", true, "Sets default external editor used when a file needs to be viewed or edited."); editor.setOptionalArg(true); options.addOption(editor); options.addOption(new Option("c", "copy", true, "Copies an operation file as a new operation file in workspace.")); return options; } private static void printLogo() { String logo = " _ _ _ " + NEWLINE + " | |_ ___ _ _| |_ ___| |_ " + NEWLINE + " | | -_| | | . | . | _| " + NEWLINE + " |_|_|___|_ |___|___|_| " + NEWLINE + " |___| " + ""; System.out.println(logo); } private static void printVersion() { System.out.println(NEWLINE + " " + VERSION + NEWLINE); } private static class MyOptionComparator<T extends Option> implements Comparator<T> { private static final String OPTS_ORDER = "oh"; // short option names @Override public int compare(T o1, T o2) { int io1 = OPTS_ORDER.indexOf(o1.getOpt()); int io2 = OPTS_ORDER.indexOf(o2.getOpt()); if (io1 >= 0) { return io1 - io2; } return 1; // no index defined, default tail! } } private static CommandLine getParser(Options options, String[] args) { // create the parser CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments return parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Ooops! Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } return null; } //</editor-fold> private static void insertOperationParameters(String operation, String[] parameters) { try { String hbFile = WORKSPACE + "/" + getFileName(operation); Properties prop = new Properties(); prop.load(hbFile); for (String parameter : parameters) { insertParameter(parameter, prop); } } catch (ConfigurationException | FileNotFoundException ex) { System.err.println("Ooops! Error occurred while handling operation file: " + ex.getMessage()); } } private static void insertParameter(String parameter, Properties prop) { String[] tokens = parseParameter(parameter); if (tokens.length > 0) { System.out.println("[*] " + tokens[0]); insertParameter(tokens, prop); } else { System.out.println("[x] " + "Unparsable operation parameter: "); System.out.println(parameter); } } private static void insertParameter(String[] tokens, Properties prop) { String value = prop.getProperty(tokens[0]); if (value != null) { System.out.println(" - " + value); setParameter(tokens, prop); } else { setParameter(tokens, prop); } } private static void setParameter(String[] tokens, Properties prop) { System.out.println(" + " + tokens[1]); prop.setProperty(tokens[0], tokens[1]); System.out.println("[✓] Inserted."); } private static String[] parseParameter(String parameter) { int i = parameter.indexOf("="); if (i > 0) { String[] tokens = new String[2]; tokens[0] = parameter.substring(0, i); tokens[1] = parameter.substring(i + 1); return tokens; } return new String[0]; } private static void selectOperationParameters(String operation, String[] parameters) { try { String hbFile = WORKSPACE + "/" + getFileName(operation); Properties prop = new Properties(); prop.load(hbFile); if (parameters.length == 0) { selectAllParameters(prop); } else { selectParameters(prop, parameters); } } catch (ConfigurationException | FileNotFoundException ex) { System.err.println("Ooops! Error occurred while handling operation file: " + ex.getMessage()); } } private static void selectAllParameters(Properties prop) { String[][] parameters = prop.getAllParameters(); for (String[] parameter : parameters) { System.out.println(parameter[0] + "=" + parameter[1]); } } private static void selectParameters(Properties prop, String[] parameters) { for (String parameter : parameters) { System.out.println(parameter + "=" + (prop.getProperty(parameter) != null ? prop.getProperty(parameter) : "")); } } private static void openOperation(String operation) { try { new Open(WORKSPACE, getFileName(operation)).run(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static void removeOperation(String operation) { File hbFile = new File(WORKSPACE + "/" + getFileName(operation)); if (hbFile.exists()) { if (hbFile.isFile() && hbFile.delete()) { System.out.println("[✓] Removed."); } else { System.out.println("[x] Could not be removed. Please check that's an operation file."); } } else { System.out.println("[!] Operation file could not be found in workspace."); } } private static void setDefaultEditor(String editor) { try { new Editor(WORKSPACE, editor).run(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static void copyOperation(CommandLine line) { try { new Copy(WORKSPACE, line).run(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } }
heybot/src/heybot/heybot.java
package heybot; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import utilities.Properties; import operation.*; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.http.util.TextUtils; import org.apache.commons.io.comparator.NameFileComparator; import org.apache.commons.lang3.StringUtils; import utilities.Copy; import utilities.Editor; import utilities.Open; public class heybot { private final static String VERSION = "2.5.1.4"; private static final String NEWLINE = System.getProperty("line.separator"); public static final String WORKSPACE = System.getProperty("user.home") + "/.heybot/workspace"; public static void main(String[] args) { printLogo(); printVersion(); createWorkspaceIfNotExists(); if (args.length > 0) { processArgs(args); } else { printHelp(); } } private static void processArgs(String[] args) { CommandLine line = getParser(buildOptions(), args); if (line.hasOption("help")) { printHelp(); } else if (line.hasOption("version")) { printVersionDetailed(); } else if (line.hasOption("list")) { listAllOperations(); } else if (line.hasOption("list-prefix")) { listOperationsStartsWith(line.getOptionValue("list-prefix")); } else if (line.hasOption("insert")) { if (line.getArgs().length > 0) { insertOperationParameters(line.getOptionValue("insert"), line.getArgs()); } else { System.err.println("Ooops! Please add parameters after operation."); } } else if (line.hasOption("select")) { selectOperationParameters(line.getOptionValue("select"), line.getArgs()); } else if (line.hasOption("open")) { openOperation(line.getOptionValue("open")); } else if (line.hasOption("remove")) { removeOperation(line.getOptionValue("remove")); } else if (line.hasOption("editor")) { setDefaultEditor(line.getOptionValue("editor")); } else if (line.hasOption("copy")) { copyOperation(line); } else { start(line); } } private static void listAllOperations() { listFiles(new File(WORKSPACE).listFiles((File dir, String name) -> name.toLowerCase().endsWith(".hb"))); } private static void listOperationsStartsWith(String prefix) { listFiles(new File(WORKSPACE).listFiles((File dir, String name) -> name.toLowerCase().startsWith(prefix.toLowerCase()) && name.toLowerCase().endsWith(".hb"))); } private static void listFiles(File[] files) { if (files != null) { Arrays.sort(files, NameFileComparator.NAME_COMPARATOR); for (File file : files) { System.out.println(file.getName()); } printTotalOperationsFound(files.length); } else { printTotalOperationsFound(0); } } private static void printTotalOperationsFound(int count) { System.out.println(); System.out.println("Total " + count + " operation(s) found."); } private static void printVersionDetailed() { System.out.println("Copyright (c) 2017 Onur Yılmaz"); System.out.println("MIT License: <https://github.com/csonuryilmaz/heybot/blob/master/LICENSE.txt>"); System.out.println("This is free software: you are free to change and redistribute it."); System.out.println("There is NO WARRANTY, to the extent permitted by law."); } private static void start(CommandLine line) { String[] args = line.getArgs(); if (args.length > 1) { processOperation(args[0], Arrays.copyOfRange(args, 1, args.length)); } else if (args.length == 1) { processOperation(args[0], new String[0]); } else { String doOptionValue = line.getOptionValue("do"); if (!TextUtils.isEmpty(doOptionValue)) { processOperation(doOptionValue, new String[0]); } else { System.err.println("Ooops! Unrecognized argument. Please refer to documentation."); } } } private static void processOperation(String operation, String[] parameters) { try { tryExecute(getFullPath(getFileName(operation)), parameters); } catch (Exception ex) { System.err.println("Ooops! An error occurred while executing [" + operation + "]"); printException(ex); if (ex.getCause() != null) { System.err.println(NEWLINE+"It has a cause. See below for details."); printException(ex.getCause()); } } } private static void printException(Throwable exception) { System.err.println("Exception:\t" + exception.getClass().getCanonicalName()); System.err.println("Message:\t" + exception.getMessage()); System.err.println("StackTrace:"); exception.printStackTrace(); } private static String getFileName(String arg) { return arg.endsWith(".hb") ? arg : arg + ".hb"; } private static void tryExecute(String hbFile, String[] parameters) throws Exception { Properties prop = new Properties(); prop.load(hbFile); Operation operation = getOperation(prop, parameters); if (operation != null) { insertOnTheFlyParameters(operation, prop, parameters); operation.start(prop); } } private static void insertOnTheFlyParameters(Operation operation, Properties prop, String[] parameters) { if (parameters.length > 0) { String value; if (operation instanceof BeginIssue) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } } else if (operation instanceof Review) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } } else if (operation instanceof BeginIssueWithGit) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } } else if (operation instanceof UploadGitDiff) { if ((value = parseIssue(parameters[0])).length() > 0) { insertParameter("ISSUE=" + value, prop); } else { System.out.println("[w] ISSUE parameter will be used from .hb file. Can't override."); } } } } private static String parseIssue(String parameter) { parameter = StringUtils.trimToEmpty(parameter); parameter = parameter.replaceAll("[^\\d.]", ""); try { return String.valueOf(Integer.parseUnsignedInt(parameter)); } catch (NumberFormatException e) { System.out.println(e.getMessage() + " Tried to parse value: " + parameter); return ""; } } private static Operation getOperation(Properties prop, String[] parameters) throws Exception { String opValue = prop.getProperty("OPERATION"); if (TextUtils.isEmpty(opValue)) { System.err.println("Ooops! Parameter OPERATION not found in .hb file."); } else { opValue = opValue.toLowerCase(new Locale("tr-TR")); switch (opValue) { case "upload": return new Upload(); case "upload-git-diff": return new UploadGitDiff(); case "upload-file": return new UploadFile(parameters.length > 0 ? parameters[0] : ""); case "cleanup": return new Cleanup(); case "review": return new Review(); case "check-new": return new CheckNew(); case "cleanup-svn": return new CleanupSvn(); case "sync-issue": return new SyncIssue(); case "next-version": return new NextVersion(); case "release": return new Release(); case "begin-issue": return new BeginIssue(); case "snapshot": return new Snapshot(); case "begin-issue-with-git": return new BeginIssueWithGit(); default: System.err.println("Ooops! Unsupported operation. Please check version and manual."); } } return null; } private static String getFullPath(String hbFile) { if (hbFile.contains("/")) { return hbFile; // already full path is given } else { return WORKSPACE + "/" + hbFile; } } private static void createWorkspaceIfNotExists() { File workspace = new File(WORKSPACE); if (!workspace.exists()) { if (!workspace.mkdirs()) { System.err.println("[e] Workspace folder not found and could not be created!"); System.err.println("[e] " + workspace.getAbsolutePath()); System.exit(-1); } } } //<editor-fold defaultstate="collapsed" desc="help"> private static final String HEADER = NEWLINE + "Designed to help developers on their day-to-day development activities. Works in subversion and redmine ecosystem." + NEWLINE + NEWLINE; private static final String FOOTER = NEWLINE + "Report bugs to \"[email protected]\" " + NEWLINE + " or drop an issue @ http://bit.ly/2S83xvy" + NEWLINE + "Releases: http://bit.ly/2BukdrR" + NEWLINE + "Document: http://bit.ly/2Sd8zqQ" + NEWLINE + NEWLINE + "Happy coding!" + NEWLINE; private static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new MyOptionComparator()); formatter.printHelp("heybot", HEADER, buildOptions(), FOOTER, true); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="syntax"> private static Options buildOptions() { Options options = new Options(); options.addOption("d", "do", true, "Heybot operation file with .hb extension." + NEWLINE + "something.hb"); options.getOption("do").setRequired(true); options.addOption("h", "help", false, "Prints this help message."); options.addOption("v", "version", false, "Prints detailed version information."); options.addOption("l", "list", false, "Lists all operation files in workspace."); options.addOption("lp", "list-prefix", true, "Lists operation files in workspace which starts with given value."); options.addOption("i", "insert", true, "Inserts (by replacing if exists) given parameter values of an operation."); options.addOption("s", "select", true, "Selects all parameters with values of an operation"); options.addOption("o", "open", true, "Opens operation file by default external editor in order to view or modify."); options.addOption("r", "remove", true, "Removes operation file from workspace."); Option editor = new Option("e", "editor", true, "Sets default external editor used when a file needs to be viewed or edited."); editor.setOptionalArg(true); options.addOption(editor); options.addOption(new Option("c", "copy", true, "Copies an operation file as a new operation file in workspace.")); return options; } private static void printLogo() { String logo = " _ _ _ " + NEWLINE + " | |_ ___ _ _| |_ ___| |_ " + NEWLINE + " | | -_| | | . | . | _| " + NEWLINE + " |_|_|___|_ |___|___|_| " + NEWLINE + " |___| " + ""; System.out.println(logo); } private static void printVersion() { System.out.println(NEWLINE + " " + VERSION + NEWLINE); } private static class MyOptionComparator<T extends Option> implements Comparator<T> { private static final String OPTS_ORDER = "oh"; // short option names @Override public int compare(T o1, T o2) { int io1 = OPTS_ORDER.indexOf(o1.getOpt()); int io2 = OPTS_ORDER.indexOf(o2.getOpt()); if (io1 >= 0) { return io1 - io2; } return 1; // no index defined, default tail! } } private static CommandLine getParser(Options options, String[] args) { // create the parser CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments return parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Ooops! Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } return null; } //</editor-fold> private static void insertOperationParameters(String operation, String[] parameters) { try { String hbFile = WORKSPACE + "/" + getFileName(operation); Properties prop = new Properties(); prop.load(hbFile); for (String parameter : parameters) { insertParameter(parameter, prop); } } catch (ConfigurationException | FileNotFoundException ex) { System.err.println("Ooops! Error occurred while handling operation file: " + ex.getMessage()); } } private static void insertParameter(String parameter, Properties prop) { String[] tokens = parseParameter(parameter); if (tokens.length > 0) { System.out.println("[*] " + tokens[0]); insertParameter(tokens, prop); } else { System.out.println("[x] " + "Unparsable operation parameter: "); System.out.println(parameter); } } private static void insertParameter(String[] tokens, Properties prop) { String value = prop.getProperty(tokens[0]); if (value != null) { System.out.println(" - " + value); setParameter(tokens, prop); } else { setParameter(tokens, prop); } } private static void setParameter(String[] tokens, Properties prop) { System.out.println(" + " + tokens[1]); prop.setProperty(tokens[0], tokens[1]); System.out.println("[✓] Inserted."); } private static String[] parseParameter(String parameter) { int i = parameter.indexOf("="); if (i > 0) { String[] tokens = new String[2]; tokens[0] = parameter.substring(0, i); tokens[1] = parameter.substring(i + 1); return tokens; } return new String[0]; } private static void selectOperationParameters(String operation, String[] parameters) { try { String hbFile = WORKSPACE + "/" + getFileName(operation); Properties prop = new Properties(); prop.load(hbFile); if (parameters.length == 0) { selectAllParameters(prop); } else { selectParameters(prop, parameters); } } catch (ConfigurationException | FileNotFoundException ex) { System.err.println("Ooops! Error occurred while handling operation file: " + ex.getMessage()); } } private static void selectAllParameters(Properties prop) { String[][] parameters = prop.getAllParameters(); for (String[] parameter : parameters) { System.out.println(parameter[0] + "=" + parameter[1]); } } private static void selectParameters(Properties prop, String[] parameters) { for (String parameter : parameters) { System.out.println(parameter + "=" + (prop.getProperty(parameter) != null ? prop.getProperty(parameter) : "")); } } private static void openOperation(String operation) { try { new Open(WORKSPACE, getFileName(operation)).run(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static void removeOperation(String operation) { File hbFile = new File(WORKSPACE + "/" + getFileName(operation)); if (hbFile.exists()) { if (hbFile.isFile() && hbFile.delete()) { System.out.println("[✓] Removed."); } else { System.out.println("[x] Could not be removed. Please check that's an operation file."); } } else { System.out.println("[!] Operation file could not be found in workspace."); } } private static void setDefaultEditor(String editor) { try { new Editor(WORKSPACE, editor).run(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static void copyOperation(CommandLine line) { try { new Copy(WORKSPACE, line).run(); } catch (Exception ex) { System.err.println(ex.getMessage()); } } }
Project is now portable between Netbeans and IntelliJ Idea.
heybot/src/heybot/heybot.java
Project is now portable between Netbeans and IntelliJ Idea.
<ide><path>eybot/src/heybot/heybot.java <ide> public class heybot <ide> { <ide> <del> private final static String VERSION = "2.5.1.4"; <add> private final static String VERSION = "2.6.2.5"; <ide> private static final String NEWLINE = System.getProperty("line.separator"); <ide> public static final String WORKSPACE = System.getProperty("user.home") + "/.heybot/workspace"; <ide>
Java
apache-2.0
a5ad502533931f824f22e1adbca36c1b63b570a7
0
Data4All/Data4All
/* * Copyright (c) 2014, 2015 Data4All * * <p>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 * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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 io.github.data4all.activity; import io.github.data4all.R; import io.github.data4all.handler.DataBaseHandler; import io.github.data4all.logger.Log; import io.github.data4all.model.TwoColumnAdapter; import io.github.data4all.model.data.AbstractDataElement; import io.github.data4all.model.data.ClassifiedTag; import io.github.data4all.model.data.ClassifiedValue; import io.github.data4all.model.data.Tag; import io.github.data4all.network.MapBoxTileSourceV4; import io.github.data4all.util.MapUtil; import io.github.data4all.util.Tagging; import io.github.data4all.view.D4AMapView; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.views.MapController; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** * View after Drawing and Tagging * * @author Maurice Boyke * */ public class ResultViewActivity extends AbstractActivity implements OnClickListener { private static final String TAG = "ResultViewActivity"; private D4AMapView mapView; // Default OpenStreetMap TileSource protected MapBoxTileSourceV4 osmMap; protected static final String OSM_MAP_NAME = "mapbox.streets"; // Minimal Zoom Level protected static final int MINIMAL_ZOOM_LEVEL = 10; // Maximal Zoom Level protected static final int MAXIMAL_ZOOM_LEVEL = 22; private MapController mapController; // Listview for the Dialog private ListView listView; // The OSM Element private AbstractDataElement element; // The Dialog for the unclassified tags private Dialog dialog; // The List that will be shown in the Activity private List<String> endList; // The list of all Keys private List<String> keyList; // The alertDialog of the Classified tags private AlertDialog alert; // The Map with the String and the ClassifiedTag private Map<String, ClassifiedTag> tagMap; // The Rescources private Resources res; // The Map wiht the String and the Tag private Map<String, Tag> mapTag; // The Map with the String and ClassifiedValue private Map<String, ClassifiedValue> classifiedMap; private View viewFooter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); osmMap = new MapBoxTileSourceV4(OSM_MAP_NAME, MINIMAL_ZOOM_LEVEL, MAXIMAL_ZOOM_LEVEL); // Here is the OsmDroidMap created setContentView(R.layout.activity_result_view); mapView = (D4AMapView) this.findViewById(R.id.mapviewResult); element = getIntent().getParcelableExtra("OSM_ELEMENT"); mapView.setTileSource(osmMap); mapController = (MapController) this.mapView.getController(); mapController.setCenter(MapUtil.getCenterFromOsmElement(element)); final BoundingBoxE6 boundingBox = MapUtil .getBoundingBoxForOsmElement(element); mapView.setBoundingBox(boundingBox); mapView.setScrollable(false); mapView.addOsmElementToMap(this, element); // Here the List of tags is created listView = (ListView) this.findViewById(R.id.listViewResultView); res = getResources(); tagMap = Tagging.getMapKeys(getIntent().getExtras().getInt("TYPE_DEF"), res); mapTag = Tagging.getUnclassifiedMapKeys(res); if (!Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")).isEmpty()) { final LayoutInflater inflater = getLayoutInflater(); viewFooter = ((LayoutInflater) this .getSystemService(LAYOUT_INFLATER_SERVICE)).inflate( R.drawable.footer_listviewresult, null, false); listView.addFooterView(viewFooter); final TextView tVFooter = ((TextView) viewFooter .findViewById(R.id.titleFooter)); tVFooter.setOnClickListener(this); viewFooter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { createDialogAddTags(); } }); } this.output(); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { Log.i(TAG, "pos" + position); Log.i(TAG, "Tagkey" + keyList.get(position)); final String selectedString = keyList.get(position); if (Tagging.isClassifiedTag(keyList.get(position), res)) { ResultViewActivity.this.changeClassifiedTag(selectedString); } else { ResultViewActivity.this .changeUnclassifiedTag(selectedString); } } }); final ImageButton resultButton = (ImageButton) this .findViewById(R.id.buttonResult); resultButton.setOnClickListener(this); final ImageButton resultButtonToCamera = (ImageButton) this .findViewById(R.id.buttonResultToCamera); resultButtonToCamera.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.result_view, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. final int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Shows the Tags in a List */ private void output() { endList = new ArrayList<String>(); keyList = new ArrayList<String>(); final List<Tag> tagList = new ArrayList<Tag>(); for (Entry entry : element.getTags().entrySet()) { final Tag tagKey = (Tag) entry.getKey(); tagList.add(tagKey); Log.i(TAG, tagKey.getKey()); keyList.add(res.getString(tagKey.getNameRessource())); if (Tagging.isClassifiedTag(getString(tagKey.getNameRessource()), res)) { try { endList.add(getString((Integer) R.string.class .getDeclaredField( "name_" + tagKey.getKey() + "_" + element.getTags().get(tagKey) .replaceAll(":", "_")).get( null))); } catch (IllegalArgumentException e) { Log.e(TAG, "", e); } catch (IllegalAccessException e) { Log.e(TAG, "", e); } catch (NoSuchFieldException e) { Log.e(TAG, "", e); } } else { endList.add(element.getTags().get(tagKey)); } } listView.setAdapter(new TwoColumnAdapter(this, keyList, endList)); } /** * Changes the Classified Tags with the selected String and saves the new * one * * @param selectedString * is the Selected String */ private void changeClassifiedTag(final String selectedString) { Log.i(TAG, "Classified Tag"); final AlertDialog.Builder alertDialog = new AlertDialog.Builder( ResultViewActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth); alertDialog.setTitle("Select Tag"); final CharSequence[] showArray; showArray = Tagging.ClassifiedValueList(tagMap.get(selectedString) .getClassifiedValues(), res); classifiedMap = Tagging.classifiedValueMap(tagMap.get(selectedString) .getClassifiedValues(), res, false); alertDialog.setItems(showArray, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String value = (String) showArray[which]; final String realValue = classifiedMap.get(value).getValue(); Log.i(TAG, "Value " + realValue); Log.i(TAG, tagMap.get(selectedString).toString()); element.addOrUpdateTag(tagMap.get(selectedString), realValue); ResultViewActivity.this.output(); } }); alert = alertDialog.create(); alert.getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT)); alert.show(); } /** * Changes the selected Unclassified Tag and saves the new one in element * * @param selectedString * is the String which is selected */ private void changeUnclassifiedTag(final String selectedString) { dialog = new Dialog(ResultViewActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth); dialog.setContentView(R.layout.dialog_dynamic); dialog.setTitle(selectedString); final Button okay = new Button(ResultViewActivity.this); final EditText text = new EditText(ResultViewActivity.this); text.setTextColor(Color.WHITE); text.setInputType(mapTag.get(selectedString).getType()); okay.setText(R.string.ok); okay.setTextColor(Color.WHITE); final LinearLayout layout = (LinearLayout) dialog .findViewById(R.id.dialogDynamic); layout.addView(text); layout.addView(okay); okay.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (text.getText().toString().matches("")) { ResultViewActivity.this.output(); dialog.dismiss(); } else { element.addOrUpdateTag(mapTag.get(selectedString), text .getText().toString()); ResultViewActivity.this.output(); // checks if you can add more Tags if not it removes footer if (Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")) .isEmpty()) { listView.removeFooterView(viewFooter); } dialog.dismiss(); } } }); dialog.show(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.buttonResult: this.addOsmElementToDB(element); final AlertDialog.Builder builder = new AlertDialog.Builder( ResultViewActivity.this); builder.setMessage(R.string.resultViewAlertDialogMessage); final Intent intent = new Intent(this, LoginActivity.class); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startActivityForResult(intent); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { setResult(RESULT_OK); finishWorkflow(); } }); alert = builder.create(); alert.show(); break; case R.id.buttonResultToCamera: this.addOsmElementToDB(element); finishWorkflow(); break; case R.id.titleFooter: createDialogAddTags(); break; default: break; } } /** * creates the Dialog with the List of all unclassified Tags which are not * used. * */ private void createDialogAddTags() { final AlertDialog.Builder alertDialog = new AlertDialog.Builder( ResultViewActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth); final List<Tag> list = Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")); final String[] listString; listString = Tagging.TagsToStringRes(list, res); alertDialog.setItems(listString, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i(TAG, listString[which]); changeUnclassifiedTag(listString[which]); alert.dismiss(); } }); list.clear(); alert = alertDialog.create(); alert.getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT)); alert.show(); } /** * Adds an Osm Element to the DataBase * * @param the * Data Element to add **/ private void addOsmElementToDB(AbstractDataElement dataElement) { final DataBaseHandler db = new DataBaseHandler(this); db.createDataElement(dataElement); db.close(); } /* * (non-Javadoc) * * @see * io.github.data4all.activity.AbstractActivity#onWorkflowFinished(android * .content.Intent) */ @Override protected void onWorkflowFinished(Intent data) { finishWorkflow(); } }
src/main/java/io/github/data4all/activity/ResultViewActivity.java
/* * Copyright (c) 2014, 2015 Data4All * * <p>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 * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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 io.github.data4all.activity; import io.github.data4all.R; import io.github.data4all.handler.DataBaseHandler; import io.github.data4all.logger.Log; import io.github.data4all.model.TwoColumnAdapter; import io.github.data4all.model.data.AbstractDataElement; import io.github.data4all.model.data.ClassifiedTag; import io.github.data4all.model.data.ClassifiedValue; import io.github.data4all.model.data.Tag; import io.github.data4all.network.MapBoxTileSourceV4; import io.github.data4all.util.MapUtil; import io.github.data4all.util.Tagging; import io.github.data4all.view.D4AMapView; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.views.MapController; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** * View after Drawing and Tagging * * @author Maurice Boyke * */ public class ResultViewActivity extends AbstractActivity implements OnClickListener { private static final String TAG = "ResultViewActivity"; private D4AMapView mapView; // Default OpenStreetMap TileSource protected MapBoxTileSourceV4 osmMap; protected static final String OSM_MAP_NAME = "mapbox.streets"; // Minimal Zoom Level protected static final int MINIMAL_ZOOM_LEVEL = 10; // Maximal Zoom Level protected static final int MAXIMAL_ZOOM_LEVEL = 22; private MapController mapController; // Listview for the Dialog private ListView listView; // The OSM Element private AbstractDataElement element; // The Dialog for the unclassified tags private Dialog dialog; // The List that will be shown in the Activity private List<String> endList; // The list of all Keys private List<String> keyList; // The alertDialog of the Classified tags private AlertDialog alert; // The Map with the String and the ClassifiedTag private Map<String, ClassifiedTag> tagMap; // The Rescources private Resources res; // The Map wiht the String and the Tag private Map<String, Tag> mapTag; // The Map with the String and ClassifiedValue private Map<String, ClassifiedValue> classifiedMap; private View viewFooter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); osmMap = new MapBoxTileSourceV4(OSM_MAP_NAME, MINIMAL_ZOOM_LEVEL, MAXIMAL_ZOOM_LEVEL); // Here is the OsmDroidMap created setContentView(R.layout.activity_result_view); mapView = (D4AMapView) this.findViewById(R.id.mapviewResult); element = getIntent().getParcelableExtra("OSM_ELEMENT"); mapView.setTileSource(osmMap); mapController = (MapController) this.mapView.getController(); mapController.setCenter(MapUtil.getCenterFromOsmElement(element)); final BoundingBoxE6 boundingBox = MapUtil.getBoundingBoxForOsmElement(element); mapView.setBoundingBox(boundingBox); mapView.setScrollable(false); mapView.addOsmElementToMap(this, element); // Here the List of tags is created listView = (ListView) this.findViewById(R.id.listViewResultView); res = getResources(); tagMap = Tagging.getMapKeys(getIntent().getExtras().getInt("TYPE_DEF"), res); mapTag = Tagging.getUnclassifiedMapKeys(res); if(!Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")).isEmpty()){ final LayoutInflater inflater = getLayoutInflater(); viewFooter =((LayoutInflater) this .getSystemService(LAYOUT_INFLATER_SERVICE)).inflate( R.drawable.footer_listviewresult, null, false); listView.addFooterView(viewFooter); final TextView tVFooter = ((TextView) viewFooter.findViewById(R.id.titleFooter)); tVFooter.setOnClickListener(this); viewFooter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { createDialogAddTags(); } }); } this.output(); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { Log.i(TAG, "pos" + position); Log.i(TAG, "Tagkey" + keyList.get(position)); final String selectedString = keyList.get(position); if (Tagging.isClassifiedTag(keyList.get(position), res)) { ResultViewActivity.this.changeClassifiedTag(selectedString); } else { ResultViewActivity.this .changeUnclassifiedTag(selectedString); } } }); final ImageButton resultButton = (ImageButton) this.findViewById(R.id.buttonResult); resultButton.setOnClickListener(this); final ImageButton resultButtonToCamera = (ImageButton) this.findViewById(R.id.buttonResultToCamera); resultButtonToCamera.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.result_view, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. final int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Shows the Tags in a List */ private void output() { endList = new ArrayList<String>(); keyList = new ArrayList<String>(); final List<Tag> tagList = new ArrayList<Tag>(); for (Entry entry : element.getTags().entrySet()) { final Tag tagKey = (Tag) entry.getKey(); tagList.add(tagKey); Log.i(TAG, tagKey.getKey()); keyList.add(res.getString(tagKey.getNameRessource())); if (Tagging.isClassifiedTag(getString(tagKey.getNameRessource()), res)) { try { endList.add(getString((Integer) R.string.class .getDeclaredField( "name_" + tagKey.getKey() + "_" + element.getTags().get(tagKey) .replaceAll(":", "_")).get( null))); } catch (IllegalArgumentException e) { Log.e(TAG, "", e); } catch (IllegalAccessException e) { Log.e(TAG, "", e); } catch (NoSuchFieldException e) { Log.e(TAG, "", e); } } else { endList.add(element.getTags().get(tagKey)); } } listView.setAdapter(new TwoColumnAdapter(this, keyList, endList)); } /** * Changes the Classified Tags with the selected String and saves the new * one * * @param selectedString * is the Selected String */ private void changeClassifiedTag(final String selectedString) { Log.i(TAG, "Classified Tag"); final AlertDialog.Builder alertDialog = new AlertDialog.Builder(ResultViewActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth); alertDialog.setTitle("Select Tag"); final CharSequence[] showArray; showArray = Tagging.ClassifiedValueList(tagMap.get(selectedString) .getClassifiedValues(), res); classifiedMap = Tagging.classifiedValueMap(tagMap.get(selectedString) .getClassifiedValues(), res, false); alertDialog.setItems(showArray, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String value = (String) showArray[which]; final String realValue = classifiedMap.get(value).getValue(); Log.i(TAG, "Value " + realValue); Log.i(TAG, tagMap.get(selectedString).toString()); element.addOrUpdateTag(tagMap.get(selectedString), realValue); ResultViewActivity.this.output(); } }); alert = alertDialog.create(); alert.getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT)); alert.show(); } /** * Changes the selected Unclassified Tag and saves the new one in element * * @param selectedString * is the String which is selected */ private void changeUnclassifiedTag(final String selectedString) { dialog = new Dialog(ResultViewActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth); dialog.setContentView(R.layout.dialog_dynamic); dialog.setTitle(selectedString); final Button okay = new Button(ResultViewActivity.this); final EditText text = new EditText(ResultViewActivity.this); text.setTextColor(Color.WHITE); text.setInputType(mapTag.get(selectedString).getType()); okay.setText(R.string.ok); okay.setTextColor(Color.WHITE); final LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.dialogDynamic); layout.addView(text); layout.addView(okay); okay.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if(text.getText().toString().matches("")){ ResultViewActivity.this.output(); dialog.dismiss(); }else { element.addOrUpdateTag(mapTag.get(selectedString), text .getText().toString()); ResultViewActivity.this.output(); // checks if you can add more Tags if not it removes footer if(Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")).isEmpty()){ listView.removeFooterView(viewFooter); } dialog.dismiss(); } } }); dialog.show(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.buttonResult: this.addOsmElementToDB(element); final AlertDialog.Builder builder = new AlertDialog.Builder(ResultViewActivity.this); builder.setMessage(R.string.resultViewAlertDialogMessage); final Intent intent = new Intent(this, LoginActivity.class); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startActivityForResult(intent); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { setResult(RESULT_OK); finishWorkflow(); } }); alert = builder.create(); alert.show(); break; case R.id.buttonResultToCamera: this.addOsmElementToDB(element); finishWorkflow(); break; case R.id.titleFooter: createDialogAddTags(); break; default: break; } } /** * creates the Dialog with the List of all unclassified Tags * which are not used. * */ private void createDialogAddTags(){ final AlertDialog.Builder alertDialog = new AlertDialog.Builder(ResultViewActivity.this, android.R.style.Theme_Holo_Dialog_MinWidth); final List <Tag> list = Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")); final String [] listString; listString = Tagging.TagsToStringRes(list, res); alertDialog.setItems(listString, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i(TAG, listString [which]); changeUnclassifiedTag(listString [which]); alert.dismiss(); } }); list.clear(); alert = alertDialog.create(); alert.getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT)); alert.show(); } /** * Adds an Osm Element to the DataBase * * @param the * Data Element to add **/ private void addOsmElementToDB(AbstractDataElement dataElement) { final DataBaseHandler db = new DataBaseHandler(this); db.createDataElement(dataElement); db.close(); } /* * (non-Javadoc) * * @see * io.github.data4all.activity.AbstractActivity#onWorkflowFinished(android * .content.Intent) */ @Override protected void onWorkflowFinished(Intent data) { finishWorkflow(); } }
sonar refs #3218
src/main/java/io/github/data4all/activity/ResultViewActivity.java
sonar refs #3218
<ide><path>rc/main/java/io/github/data4all/activity/ResultViewActivity.java <ide> private Map<String, Tag> mapTag; <ide> // The Map with the String and ClassifiedValue <ide> private Map<String, ClassifiedValue> classifiedMap; <del> <add> <ide> private View viewFooter; <ide> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <del> osmMap = <del> new MapBoxTileSourceV4(OSM_MAP_NAME, MINIMAL_ZOOM_LEVEL, <del> MAXIMAL_ZOOM_LEVEL); <add> osmMap = new MapBoxTileSourceV4(OSM_MAP_NAME, MINIMAL_ZOOM_LEVEL, <add> MAXIMAL_ZOOM_LEVEL); <ide> <ide> // Here is the OsmDroidMap created <ide> setContentView(R.layout.activity_result_view); <ide> mapView.setTileSource(osmMap); <ide> mapController = (MapController) this.mapView.getController(); <ide> mapController.setCenter(MapUtil.getCenterFromOsmElement(element)); <del> final BoundingBoxE6 boundingBox = <del> MapUtil.getBoundingBoxForOsmElement(element); <add> final BoundingBoxE6 boundingBox = MapUtil <add> .getBoundingBoxForOsmElement(element); <ide> mapView.setBoundingBox(boundingBox); <ide> mapView.setScrollable(false); <ide> mapView.addOsmElementToMap(this, element); <ide> // Here the List of tags is created <ide> listView = (ListView) this.findViewById(R.id.listViewResultView); <ide> res = getResources(); <del> tagMap = <del> Tagging.getMapKeys(getIntent().getExtras().getInt("TYPE_DEF"), <del> res); <add> tagMap = Tagging.getMapKeys(getIntent().getExtras().getInt("TYPE_DEF"), <add> res); <ide> mapTag = Tagging.getUnclassifiedMapKeys(res); <del> if(!Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")).isEmpty()){ <del> final LayoutInflater inflater = getLayoutInflater(); <del> viewFooter =((LayoutInflater) this <del> .getSystemService(LAYOUT_INFLATER_SERVICE)).inflate( <del> R.drawable.footer_listviewresult, null, false); <del> listView.addFooterView(viewFooter); <del> final TextView tVFooter = ((TextView) viewFooter.findViewById(R.id.titleFooter)); <del> tVFooter.setOnClickListener(this); <del> viewFooter.setOnClickListener(new OnClickListener() { <del> <del> @Override <del> public void onClick(View v) { <del> createDialogAddTags(); <del> <del> } <del> }); <add> if (!Tagging.getAllNonSelectedTags(element.getTags(), <add> getIntent().getExtras().getInt("TYPE_DEF")).isEmpty()) { <add> final LayoutInflater inflater = getLayoutInflater(); <add> viewFooter = ((LayoutInflater) this <add> .getSystemService(LAYOUT_INFLATER_SERVICE)).inflate( <add> R.drawable.footer_listviewresult, null, false); <add> listView.addFooterView(viewFooter); <add> final TextView tVFooter = ((TextView) viewFooter <add> .findViewById(R.id.titleFooter)); <add> tVFooter.setOnClickListener(this); <add> viewFooter.setOnClickListener(new OnClickListener() { <add> <add> @Override <add> public void onClick(View v) { <add> createDialogAddTags(); <add> <add> } <add> }); <ide> } <ide> this.output(); <ide> listView.setOnItemClickListener(new OnItemClickListener() { <ide> public void onItemClick(AdapterView<?> parent, View view, <ide> final int position, long id) { <del> Log.i(TAG, "pos" + position); <add> Log.i(TAG, "pos" + position); <ide> Log.i(TAG, "Tagkey" + keyList.get(position)); <ide> final String selectedString = keyList.get(position); <ide> if (Tagging.isClassifiedTag(keyList.get(position), res)) { <ide> } <ide> } <ide> }); <del> final ImageButton resultButton = <del> (ImageButton) this.findViewById(R.id.buttonResult); <add> final ImageButton resultButton = (ImageButton) this <add> .findViewById(R.id.buttonResult); <ide> resultButton.setOnClickListener(this); <del> final ImageButton resultButtonToCamera = <del> (ImageButton) this.findViewById(R.id.buttonResultToCamera); <add> final ImageButton resultButtonToCamera = (ImageButton) this <add> .findViewById(R.id.buttonResultToCamera); <ide> resultButtonToCamera.setOnClickListener(this); <ide> } <ide> <ide> } <ide> <ide> } <del> <add> <ide> listView.setAdapter(new TwoColumnAdapter(this, keyList, endList)); <ide> } <ide> <ide> */ <ide> private void changeClassifiedTag(final String selectedString) { <ide> Log.i(TAG, "Classified Tag"); <del> final AlertDialog.Builder alertDialog = <del> new AlertDialog.Builder(ResultViewActivity.this, <del> android.R.style.Theme_Holo_Dialog_MinWidth); <add> final AlertDialog.Builder alertDialog = new AlertDialog.Builder( <add> ResultViewActivity.this, <add> android.R.style.Theme_Holo_Dialog_MinWidth); <ide> alertDialog.setTitle("Select Tag"); <ide> final CharSequence[] showArray; <del> showArray = <del> Tagging.ClassifiedValueList(tagMap.get(selectedString) <del> .getClassifiedValues(), res); <del> classifiedMap = <del> Tagging.classifiedValueMap(tagMap.get(selectedString) <del> .getClassifiedValues(), res, false); <add> showArray = Tagging.ClassifiedValueList(tagMap.get(selectedString) <add> .getClassifiedValues(), res); <add> classifiedMap = Tagging.classifiedValueMap(tagMap.get(selectedString) <add> .getClassifiedValues(), res, false); <ide> alertDialog.setItems(showArray, new DialogInterface.OnClickListener() { <ide> @Override <ide> public void onClick(DialogInterface dialog, int which) { <ide> * is the String which is selected <ide> */ <ide> private void changeUnclassifiedTag(final String selectedString) { <del> dialog = <del> new Dialog(ResultViewActivity.this, <del> android.R.style.Theme_Holo_Dialog_MinWidth); <add> dialog = new Dialog(ResultViewActivity.this, <add> android.R.style.Theme_Holo_Dialog_MinWidth); <ide> dialog.setContentView(R.layout.dialog_dynamic); <ide> dialog.setTitle(selectedString); <ide> final Button okay = new Button(ResultViewActivity.this); <ide> text.setInputType(mapTag.get(selectedString).getType()); <ide> okay.setText(R.string.ok); <ide> okay.setTextColor(Color.WHITE); <del> final LinearLayout layout = <del> (LinearLayout) dialog.findViewById(R.id.dialogDynamic); <add> final LinearLayout layout = (LinearLayout) dialog <add> .findViewById(R.id.dialogDynamic); <ide> layout.addView(text); <ide> layout.addView(okay); <ide> okay.setOnClickListener(new OnClickListener() { <ide> @Override <ide> public void onClick(View arg0) { <del> if(text.getText().toString().matches("")){ <del> ResultViewActivity.this.output(); <del> dialog.dismiss(); <del> }else { <del> element.addOrUpdateTag(mapTag.get(selectedString), text <del> .getText().toString()); <del> ResultViewActivity.this.output(); <del> // checks if you can add more Tags if not it removes footer <del> if(Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")).isEmpty()){ <del> listView.removeFooterView(viewFooter); <del> } <del> dialog.dismiss(); <del> } <add> if (text.getText().toString().matches("")) { <add> ResultViewActivity.this.output(); <add> dialog.dismiss(); <add> } else { <add> element.addOrUpdateTag(mapTag.get(selectedString), text <add> .getText().toString()); <add> ResultViewActivity.this.output(); <add> // checks if you can add more Tags if not it removes footer <add> if (Tagging.getAllNonSelectedTags(element.getTags(), <add> getIntent().getExtras().getInt("TYPE_DEF")) <add> .isEmpty()) { <add> listView.removeFooterView(viewFooter); <add> } <add> dialog.dismiss(); <add> } <ide> } <ide> }); <ide> dialog.show(); <ide> <ide> @Override <ide> public void onClick(View v) { <del> switch (v.getId()) { <del> case R.id.buttonResult: <add> switch (v.getId()) { <add> case R.id.buttonResult: <ide> this.addOsmElementToDB(element); <del> final AlertDialog.Builder builder = <del> new AlertDialog.Builder(ResultViewActivity.this); <add> final AlertDialog.Builder builder = new AlertDialog.Builder( <add> ResultViewActivity.this); <ide> builder.setMessage(R.string.resultViewAlertDialogMessage); <ide> final Intent intent = new Intent(this, LoginActivity.class); <ide> builder.setPositiveButton(R.string.yes, <ide> alert = builder.create(); <ide> alert.show(); <ide> break; <del> case R.id.buttonResultToCamera: <add> case R.id.buttonResultToCamera: <ide> this.addOsmElementToDB(element); <ide> finishWorkflow(); <ide> break; <del> case R.id.titleFooter: <del> createDialogAddTags(); <del> break; <del> default: <del> break; <del> } <del> } <del> <add> case R.id.titleFooter: <add> createDialogAddTags(); <add> break; <add> default: <add> break; <add> } <add> } <add> <ide> /** <del> * creates the Dialog with the List of all unclassified Tags <del> * which are not used. <add> * creates the Dialog with the List of all unclassified Tags which are not <add> * used. <ide> * <ide> */ <del> private void createDialogAddTags(){ <del> final AlertDialog.Builder alertDialog = <del> new AlertDialog.Builder(ResultViewActivity.this, <del> android.R.style.Theme_Holo_Dialog_MinWidth); <del> final List <Tag> list = Tagging.getAllNonSelectedTags(element.getTags(), getIntent().getExtras().getInt("TYPE_DEF")); <del> final String [] listString; <del> listString = Tagging.TagsToStringRes(list, res); <del> alertDialog.setItems(listString, new DialogInterface.OnClickListener() { <del> <del> @Override <del> public void onClick(DialogInterface dialog, int which) { <del> Log.i(TAG, listString [which]); <del> changeUnclassifiedTag(listString [which]); <del> alert.dismiss(); <del> } <del> }); <del> list.clear(); <del> alert = alertDialog.create(); <del> alert.getWindow().setBackgroundDrawable( <del> new ColorDrawable(android.graphics.Color.TRANSPARENT)); <del> alert.show(); <del> <del> <add> private void createDialogAddTags() { <add> final AlertDialog.Builder alertDialog = new AlertDialog.Builder( <add> ResultViewActivity.this, <add> android.R.style.Theme_Holo_Dialog_MinWidth); <add> final List<Tag> list = Tagging.getAllNonSelectedTags(element.getTags(), <add> getIntent().getExtras().getInt("TYPE_DEF")); <add> final String[] listString; <add> listString = Tagging.TagsToStringRes(list, res); <add> alertDialog.setItems(listString, new DialogInterface.OnClickListener() { <add> <add> @Override <add> public void onClick(DialogInterface dialog, int which) { <add> Log.i(TAG, listString[which]); <add> changeUnclassifiedTag(listString[which]); <add> alert.dismiss(); <add> } <add> }); <add> list.clear(); <add> alert = alertDialog.create(); <add> alert.getWindow().setBackgroundDrawable( <add> new ColorDrawable(android.graphics.Color.TRANSPARENT)); <add> alert.show(); <add> <ide> } <ide> <ide> /**
Java
apache-2.0
2a6ae3c8af40cbe503ebf43367119e8f6d925c5a
0
Catpaw42/Area51_E2014,Catpaw42/Area51_E2014,Catpaw42/Area51_E2014
package servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.spoledge.audao.db.dao.DaoException; import database.DataSourceConnector; import database.dao.DaoFactory; import database.dao.DaoFactory.Factory; import database.dao.PatientDao; import database.dao.RekvisitionDao; import database.dao.mysql.BrugerDaoImpl; import database.dao.mysql.DaoFactoryImpl; import database.dao.mysql.PatientDaoImpl; import database.dao.mysql.RekvisitionDaoImpl; import database.dto.Bruger; import database.dto.Patient; import database.dto.Rekvisition; import database.dto.Rekvisition.AmbulantKoersel; import database.dto.Rekvisition.HenvistTil; import database.dto.Rekvisition.HospitalOenske; import database.dto.Rekvisition.IndlaeggelseTransport; import database.dto.Rekvisition.Prioritering; import database.dto.Rekvisition.Samtykke; import database.interfaces.IDataSourceConnector.ConnectionException; /** * Servlet implementation class NyRekvisitionServlet */ @SuppressWarnings("serial") @WebServlet("/NyRekvisitionServlet") public class NyRekvisitionServlet extends HttpServlet { /** * @see HttpServlet#HttpServlet() */ public NyRekvisitionServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request.setAttribute("modaliteter", arg1); TODO send list of modalities //request.setAttribute("Undersoegelses_typer", Object[][] ); TODO send list of types request.getRequestDispatcher("nyRekvisitionPage.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Getting a database connection.... Connection connection = null; try { connection = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //making patient object... Patient pt = new Patient(); pt.setFoedselsdag(java.sql.Date.valueOf(parseCprBirthday(request))); pt.setPatientCpr(request.getParameter("patient_cpr")); pt.setPatientAdresse(request.getParameter("patient_adresse")); pt.setPatientNavn(request.getParameter("patient_navn")); pt.setPatientTlf(request.getParameter("patient_tlf")); pt.setStamafdeling("TestAfdeling"); //TODO get from User System.out.println(pt); //Time to store patient Integer ptId = null; PatientDao ptDao = new PatientDaoImpl(connection); try { ptId = ptDao.insert(pt); } catch (DaoException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Making Rekvisition DTO Rekvisition rek = new Rekvisition(); //Rekvisition.setPaaroerende TODO rek.setPaaroerende(request.getParameter("paaroerende")); rek.setSamtykke(convertSamtykke(request)); //TODO validate samtykke. rek.setTriage(request.getParameter("triage")); rek.setCave(request.getParameter("cave"));//TODO validate try { rek.setRekvirentId(Integer.valueOf(request.getParameter("rekvirent"))); } catch (NumberFormatException e){ //TODO handle missing rekvirent //returnToPage("Manglende RekvirentID); } rek.setRekvirentId(1); // TODO FIX! rek.setHenvAfd("TestAfd"); //TODO get from user! rek.setVisitatorId(-1); //Remove - Should be null //TODO Rekvirerende afdeling findes ikke - bundet til brugeren? rek.setHenvLaege(request.getParameter("henv_laege")); rek.setKontaktTlf(request.getParameter("kontakt_tlf")); rek.setUdfIndlagt(Boolean.valueOf(request.getParameter("udf_indlagt"))); rek.setAmbulant(!rek.getUdfIndlagt()); rek.setHenvistTil(convertHenvistTil(request)); rek.setHospitalOenske(convertHospitalOenske(request)); rek.setPrioritering(convertPrioritering(request)); try { rek.setUndersoegelsesTypeId(Integer.valueOf(request.getParameter("undersoegelses_id"))); } catch (NumberFormatException e) { //TODO meaningful handling of error } rek.setUndersoegelsesTypeId(1); //TODO FIXXX!!! rek.setKliniskProblemstilling(request.getParameter("klinisk_problemstilling")); rek.setAmbulantKoersel(convertAmbulantKoersel(request)); rek.setIndlaeggelseTransport(convertIndlaeggelseTransport(request)); rek.setDatoForslag(request.getParameter("dato_forslag")); rek.setGraviditet(Boolean.valueOf(request.getParameter("graviditet"))); rek.setHoerehaemmet(getBoolFromCheckbox(request,"hoerehaemmet")); rek.setSynshaemmet(getBoolFromCheckbox(request, "synshaemmet")); rek.setAmputeret(getBoolFromCheckbox(request, "amputeret")); rek.setKanIkkeStaa(getBoolFromCheckbox(request, "kan_ikke_staa")); rek.setDement(getBoolFromCheckbox(request, "dement")); rek.setAfasi(getBoolFromCheckbox(request, "afasi")); try { rek.setIltLiterPrmin(Integer.valueOf(request.getParameter("ilt"))); } catch (NumberFormatException e){ rek.setIltLiterPrmin(null); } rek.setTolkSprog(request.getParameter("tolk")); rek.setIsolation(request.getParameter("isolation")); try { rek.setCytostatikaDato(java.sql.Date.valueOf(request.getParameter("cytostatika"))); System.out.println(rek.getCytostatikaDato()); } catch (IllegalArgumentException e) { rek.setCytostatikaDato(null); } rek.setTidlBilledDiagnostik(request.getParameter("tidl_billed_diagnostik")); rek.setPatientId(ptId); rek.setStatus(Rekvisition.Status.PENDING); rek.setAfsendtDato(new Date()); System.out.println(rek); //Time to store requisition RekvisitionDao rekDao = new RekvisitionDaoImpl(connection); try { rekDao.insert(rek); } catch (DaoException e) { // TODO Auto-generated catch block e.printStackTrace(); } //HopeFully it went well ;) PrintWriter out = response.getWriter(); out.println("<HTML><BODY>Tak for din henvendelse - du kan følge med i status for din rekvisition i oversigten <BR>"); out.println("<A HREF='RekvisitionServlet'>Tilbage til rekvisitioner</A></BODY><HTML>"); } private String parseCprBirthday(HttpServletRequest request) { String foedselsdagString = request.getParameter("patient_cpr"); Integer foedeaar = Integer.valueOf(foedselsdagString.substring(4, 6)); String digit7String = foedselsdagString.substring(7,8); if (digit7String.equalsIgnoreCase("-") ) digit7String = foedselsdagString.substring(8, 9); Integer digit7 = Integer.valueOf(digit7String); if (digit7 <= 3 ){ foedeaar = 1900 + foedeaar; } else { if ((digit7 == 4 || digit7 == 9) && foedeaar >=37){ foedeaar = 1900 + foedeaar; } else { if (foedeaar >=58){ foedeaar = 1800 + foedeaar; } else { foedeaar = 2000 + foedeaar; } } } foedselsdagString = String.valueOf(foedeaar) + "-" + foedselsdagString.substring(2,4)+"-"+foedselsdagString.substring(0, 2); return foedselsdagString; } private Boolean getBoolFromCheckbox(HttpServletRequest request, String boxname) { if("on".equals(request.getParameter(boxname))){ // check box is selected return true; } else{ // check box is not selected return false; } } private IndlaeggelseTransport convertIndlaeggelseTransport( HttpServletRequest request) { IndlaeggelseTransport indlTrans; String transString = request.getParameter("indlagt_transport"); if (transString==null) return null; switch (transString) { case "selv": indlTrans = Rekvisition.IndlaeggelseTransport.GAA_UDEN_PORTOER; break; case "portoer": indlTrans = Rekvisition.IndlaeggelseTransport.GAA_MED_PORTOER; break; case "koerestol": indlTrans = Rekvisition.IndlaeggelseTransport.KOERESTOL; break; case "seng": indlTrans = Rekvisition.IndlaeggelseTransport.SENG; break; default: indlTrans=null; break; } return indlTrans; } private AmbulantKoersel convertAmbulantKoersel(HttpServletRequest request) { AmbulantKoersel ambuTrans; String transString = request.getParameter("ambulant_transport"); if (transString==null) return null; switch (transString) { case "ingen": ambuTrans = Rekvisition.AmbulantKoersel.INGEN; break; case "siddende": ambuTrans = Rekvisition.AmbulantKoersel.SIDDENDE; break; case "liggende": ambuTrans = Rekvisition.AmbulantKoersel.LIGGENDE; break; default: ambuTrans = null; break; } return ambuTrans; } private Prioritering convertPrioritering(HttpServletRequest request) { Prioritering prio; String prioString = request.getParameter("prioriterings_oenske"); if (prioString==null)return null; switch (prioString) { case "haste": prio = Rekvisition.Prioritering.HASTE; break; case "fremskyndet": prio = Rekvisition.Prioritering.FREMSKYNDET; break; case "rutine": prio = Rekvisition.Prioritering.RUTINE; break; case "pakke": prio = Rekvisition.Prioritering.PAKKEFORLOEB; break; default: prio = null; break; } return prio; } private HospitalOenske convertHospitalOenske(HttpServletRequest request) { HospitalOenske hospOensk; String hospOenskString = request.getParameter("hospitals_oenske"); if (hospOenskString==null) return null; switch (hospOenskString) { case "hilleroed": hospOensk = Rekvisition.HospitalOenske.HILLEROED; break; case "frederikssund": hospOensk = Rekvisition.HospitalOenske.FREDERIKSSUND; break; case "helsingoer": hospOensk = Rekvisition.HospitalOenske.HELSINGOER; break; default: hospOensk=null; break; } return hospOensk; } private HenvistTil convertHenvistTil(HttpServletRequest request) { HenvistTil henv; String henvString = request.getParameter("henvist_til"); if (henvString==null) return null; switch (henvString) { case "radiologisk": henv = Rekvisition.HenvistTil.RADIOLOGISK; break; case "klinfys": henv = Rekvisition.HenvistTil.KLINISK; break; default: henv = null; break; } return henv; } private Samtykke convertSamtykke(HttpServletRequest request) { Samtykke samtykke; String samtykkeString = request.getParameter("samtykke"); if (samtykkeString == null) return null; switch (samtykkeString) { case "ja": samtykke = Rekvisition.Samtykke.JA; break; case "nej": samtykke = Rekvisition.Samtykke.NEJ; break; default: samtykke = Rekvisition.Samtykke.UDEN_SAMTYKKE; break; } return samtykke; } }
Xray/src/servlets/NyRekvisitionServlet.java
package servlets; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.spoledge.audao.db.dao.DaoException; import database.DataSourceConnector; import database.dao.DaoFactory; import database.dao.DaoFactory.Factory; import database.dao.PatientDao; import database.dao.RekvisitionDao; import database.dao.mysql.BrugerDaoImpl; import database.dao.mysql.DaoFactoryImpl; import database.dao.mysql.PatientDaoImpl; import database.dao.mysql.RekvisitionDaoImpl; import database.dto.Bruger; import database.dto.Patient; import database.dto.Rekvisition; import database.dto.Rekvisition.AmbulantKoersel; import database.dto.Rekvisition.HenvistTil; import database.dto.Rekvisition.HospitalOenske; import database.dto.Rekvisition.IndlaeggelseTransport; import database.dto.Rekvisition.Prioritering; import database.dto.Rekvisition.Samtykke; import database.interfaces.IDataSourceConnector.ConnectionException; /** * Servlet implementation class NyRekvisitionServlet */ @SuppressWarnings("serial") @WebServlet("/NyRekvisitionServlet") public class NyRekvisitionServlet extends HttpServlet { /** * @see HttpServlet#HttpServlet() */ public NyRekvisitionServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request.setAttribute("modaliteter", arg1); TODO send list of modalities //request.setAttribute("Undersoegelses_typer", Object[][] ); TODO send list of types request.getRequestDispatcher("nyRekvisitionPage.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Getting a database connection.... Connection connection = null; try { connection = DataSourceConnector.getConnection(); } catch (ConnectionException e1) { e1.printStackTrace(); } //making patient object... Patient pt = new Patient(); pt.setFoedselsdag(java.sql.Date.valueOf(parseCprBirthday(request))); pt.setPatientCpr(request.getParameter("patient_cpr")); pt.setPatientAdresse(request.getParameter("patient_adresse")); pt.setPatientNavn(request.getParameter("patient_navn")); pt.setPatientTlf(request.getParameter("patient_tlf")); pt.setStamafdeling("TestAfdeling"); //TODO get from User System.out.println(pt); //Time to store patient Integer ptId = null; PatientDao ptDao = new PatientDaoImpl(connection); try { ptId = ptDao.insert(pt); } catch (DaoException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Making Rekvisition DTO Rekvisition rek = new Rekvisition(); //Rekvisition.setPaaroerende TODO rek.setPaaroerende(request.getParameter("paaroerende")); rek.setSamtykke(convertSamtykke(request)); //TODO validate samtykke. rek.setTriage(request.getParameter("triage")); rek.setCave(request.getParameter("cave"));//TODO validate try { rek.setRekvirentId(Integer.valueOf(request.getParameter("rekvirent"))); } catch (NumberFormatException e){ //TODO handle missing rekvirent //returnToPage("Manglende RekvirentID); } rek.setRekvirentId(1); // TODO FIX! rek.setHenvAfd("TestAfd"); //TODO get from user! rek.setVisitatorId(-1); //Remove - Should be null //TODO Rekvirerende afdeling findes ikke - bundet til brugeren? rek.setHenvLaege(request.getParameter("henv_laege")); rek.setKontaktTlf(request.getParameter("kontakt_tlf")); rek.setUdfIndlagt(Boolean.valueOf(request.getParameter("udf_indlagt"))); rek.setAmbulant(!rek.getUdfIndlagt()); rek.setHenvistTil(convertHenvistTil(request)); rek.setHospitalOenske(convertHospitalOenske(request)); rek.setPrioritering(convertPrioritering(request)); try { rek.setUndersoegelsesTypeId(Integer.valueOf(request.getParameter("undersoegelses_id"))); } catch (NumberFormatException e) { //TODO meaningful handling of error } rek.setUndersoegelsesTypeId(1); //TODO FIXXX!!! rek.setKliniskProblemstilling(request.getParameter("klinisk_problemstilling")); rek.setAmbulantKoersel(convertAmbulantKoersel(request)); rek.setIndlaeggelseTransport(convertIndlaeggelseTransport(request)); rek.setDatoForslag(request.getParameter("dato_forslag")); rek.setGraviditet(Boolean.valueOf(request.getParameter("graviditet"))); rek.setHoerehaemmet(getBoolFromCheckbox(request,"hoerehaemmet")); rek.setSynshaemmet(getBoolFromCheckbox(request, "synshaemmet")); rek.setAmputeret(getBoolFromCheckbox(request, "amputeret")); rek.setKanIkkeStaa(getBoolFromCheckbox(request, "kan_ikke_staa")); rek.setDement(getBoolFromCheckbox(request, "dement")); rek.setAfasi(getBoolFromCheckbox(request, "afasi")); try { rek.setIltLiterPrmin(Integer.valueOf(request.getParameter("ilt"))); } catch (NumberFormatException e){ rek.setIltLiterPrmin(null); } rek.setTolkSprog(request.getParameter("tolk")); rek.setIsolation(request.getParameter("isolation")); try { rek.setCytostatikaDato(java.sql.Date.valueOf(request.getParameter("cytostatika"))); System.out.println(rek.getCytostatikaDato()); } catch (IllegalArgumentException e) { rek.setCytostatikaDato(null); } rek.setTidlBilledDiagnostik(request.getParameter("tidl_billed_diagnostik")); rek.setPatientId(ptId); rek.setStatus(Rekvisition.Status.PENDING); rek.setAfsendtDato(new Date()); System.out.println(rek); //Time to store requisition RekvisitionDao rekDao = new RekvisitionDaoImpl(connection); try { rekDao.insert(rek); } catch (DaoException e) { // TODO Auto-generated catch block e.printStackTrace(); } //HopeFully it went well ;) PrintWriter out = response.getWriter(); out.println("<HTML><BODY>Tak for din henvendelse - du kan følge med i status for din rekvisition i oversigten <BR>"); out.println("<A HREF='RekvisitionServlet'>Tilbage til rekvisitioner</A></BODY><HTML>"); } private String parseCprBirthday(HttpServletRequest request) { String foedselsdagString = request.getParameter("patient_cpr"); Integer foedeaar = Integer.valueOf(foedselsdagString.substring(4, 6)); if (new java.util.Date().getYear() - foedeaar >= 100 ){ foedeaar = 2000 + foedeaar; } else { foedeaar = 1900 + foedeaar; } foedselsdagString = String.valueOf(foedeaar) + "-" + foedselsdagString.substring(2,4)+"-"+foedselsdagString.substring(0, 2); return foedselsdagString; } private Boolean getBoolFromCheckbox(HttpServletRequest request, String boxname) { if("on".equals(request.getParameter(boxname))){ // check box is selected return true; } else{ // check box is not selected return false; } } private IndlaeggelseTransport convertIndlaeggelseTransport( HttpServletRequest request) { IndlaeggelseTransport indlTrans; String transString = request.getParameter("indlagt_transport"); if (transString==null) return null; switch (transString) { case "selv": indlTrans = Rekvisition.IndlaeggelseTransport.GAA_UDEN_PORTOER; break; case "portoer": indlTrans = Rekvisition.IndlaeggelseTransport.GAA_MED_PORTOER; break; case "koerestol": indlTrans = Rekvisition.IndlaeggelseTransport.KOERESTOL; break; case "seng": indlTrans = Rekvisition.IndlaeggelseTransport.SENG; break; default: indlTrans=null; break; } return indlTrans; } private AmbulantKoersel convertAmbulantKoersel(HttpServletRequest request) { AmbulantKoersel ambuTrans; String transString = request.getParameter("ambulant_transport"); if (transString==null) return null; switch (transString) { case "ingen": ambuTrans = Rekvisition.AmbulantKoersel.INGEN; break; case "siddende": ambuTrans = Rekvisition.AmbulantKoersel.SIDDENDE; break; case "liggende": ambuTrans = Rekvisition.AmbulantKoersel.LIGGENDE; break; default: ambuTrans = null; break; } return ambuTrans; } private Prioritering convertPrioritering(HttpServletRequest request) { Prioritering prio; String prioString = request.getParameter("prioriterings_oenske"); if (prioString==null)return null; switch (prioString) { case "haste": prio = Rekvisition.Prioritering.HASTE; break; case "fremskyndet": prio = Rekvisition.Prioritering.FREMSKYNDET; break; case "rutine": prio = Rekvisition.Prioritering.RUTINE; break; case "pakke": prio = Rekvisition.Prioritering.PAKKEFORLOEB; break; default: prio = null; break; } return prio; } private HospitalOenske convertHospitalOenske(HttpServletRequest request) { HospitalOenske hospOensk; String hospOenskString = request.getParameter("hospitals_oenske"); if (hospOenskString==null) return null; switch (hospOenskString) { case "hilleroed": hospOensk = Rekvisition.HospitalOenske.HILLEROED; break; case "frederikssund": hospOensk = Rekvisition.HospitalOenske.FREDERIKSSUND; break; case "helsingoer": hospOensk = Rekvisition.HospitalOenske.HELSINGOER; break; default: hospOensk=null; break; } return hospOensk; } private HenvistTil convertHenvistTil(HttpServletRequest request) { HenvistTil henv; String henvString = request.getParameter("henvist_til"); if (henvString==null) return null; switch (henvString) { case "radiologisk": henv = Rekvisition.HenvistTil.RADIOLOGISK; break; case "klinfys": henv = Rekvisition.HenvistTil.KLINISK; break; default: henv = null; break; } return henv; } private Samtykke convertSamtykke(HttpServletRequest request) { Samtykke samtykke; String samtykkeString = request.getParameter("samtykke"); if (samtykkeString == null) return null; switch (samtykkeString) { case "ja": samtykke = Rekvisition.Samtykke.JA; break; case "nej": samtykke = Rekvisition.Samtykke.NEJ; break; default: samtykke = Rekvisition.Samtykke.UDEN_SAMTYKKE; break; } return samtykke; } }
updated birthday algorithm
Xray/src/servlets/NyRekvisitionServlet.java
updated birthday algorithm
<ide><path>ray/src/servlets/NyRekvisitionServlet.java <ide> private String parseCprBirthday(HttpServletRequest request) { <ide> String foedselsdagString = request.getParameter("patient_cpr"); <ide> Integer foedeaar = Integer.valueOf(foedselsdagString.substring(4, 6)); <del> if (new java.util.Date().getYear() - foedeaar >= 100 ){ <del> foedeaar = 2000 + foedeaar; <add> String digit7String = foedselsdagString.substring(7,8); <add> if (digit7String.equalsIgnoreCase("-") ) digit7String = foedselsdagString.substring(8, 9); <add> Integer digit7 = Integer.valueOf(digit7String); <add> if (digit7 <= 3 ){ <add> foedeaar = 1900 + foedeaar; <ide> } else { <del> foedeaar = 1900 + foedeaar; <add> if ((digit7 == 4 || digit7 == 9) && foedeaar >=37){ <add> foedeaar = 1900 + foedeaar; <add> } else { <add> if (foedeaar >=58){ <add> foedeaar = 1800 + foedeaar; <add> } else { <add> foedeaar = 2000 + foedeaar; <add> } <add> } <add> <ide> } <ide> foedselsdagString = String.valueOf(foedeaar) + "-" + foedselsdagString.substring(2,4)+"-"+foedselsdagString.substring(0, 2); <ide> return foedselsdagString;
Java
mit
29913533064cad9804da4c27a498c62e08808821
0
ryanwilliams83/cordova-plugin-app-utils,Busivid/cordova-plugin-app-utils,Busivid/cordova-plugin-app-utils,ryanwilliams83/cordova-plugin-app-utils
package com.busivid.cordova.apputils; import android.app.Activity; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Build; import android.provider.Telephony; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Method; import java.util.ArrayList; public class AppUtils extends CordovaPlugin { private static final int EMAIL_INTENT_RESULT = 1000; private static final int SMS_INTENT_RESULT = 1001; private CallbackContext callbackContext; // The callback context from which we were invoked. @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; if (action.equals("BundleInfo")) { try { JSONObject bundleInfo = this.bundleInfo(); callbackContext.success(bundleInfo); } catch (NameNotFoundException exception) { callbackContext.error(exception.getMessage()); } } else if(action.equals("ComposeEmail")) { JSONObject jsonObject = args.getJSONObject(0); String body = jsonObject.getString("body"); JSONArray recipientsJson = jsonObject.getJSONArray("recipients"); String subject = jsonObject.getString("subject"); String[] recipients = convertJsonArrayToStringArray(recipientsJson); composeEmail(body, subject, recipients); } else if(action.equals("ComposeSMS")) { JSONObject jsonObject = args.getJSONObject(0); String body = jsonObject.getString("body"); JSONArray recipientsJson = jsonObject.getJSONArray("recipients"); String[] recipients = convertJsonArrayToStringArray(recipientsJson); composeSMS(body, recipients); } else if (action.equals("DeviceInfo")) { JSONObject deviceInfo = new JSONObject(); deviceInfo.put("name", this.getHostname()); callbackContext.success(deviceInfo); } else { return false; } return true; } public JSONObject bundleInfo() throws JSONException, NameNotFoundException { JSONObject results = new JSONObject(); Activity cordovaActivity = this.cordova.getActivity(); String packageName = cordovaActivity.getPackageName(); PackageInfo packageInfo = cordovaActivity.getPackageManager().getPackageInfo(packageName, 0); boolean isDebug = (cordovaActivity.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; results.put("bundleVersion", packageInfo.versionCode); results.put("bundleId", packageName); results.put("bundleIsDebug", isDebug); return results; } public static String getHostname() { try { Method getString = Build.class.getDeclaredMethod("getString", String.class); getString.setAccessible(true); return getString.invoke(null, "net.hostname").toString(); } catch (Exception ex) { return null; } } public static String[] convertJsonArrayToStringArray(JSONArray jsonArray) { try { ArrayList<String> list = new ArrayList<String>(); for(int i = 0; i < jsonArray.length(); i++) { list.add((String)jsonArray.get(i)); } return list.toArray(new String[list.size()]); } catch (JSONException exception) { return new String[0]; } } public static String joinArrayToString(String[] input, String seperator) { String output = ""; for (String s : input) { if(output == "") { output += s; } else { output += seperator + s; } } return output; } public void composeEmail(final String body, final String subject, final String[] recipients) { final CordovaPlugin plugin = (CordovaPlugin) this; Runnable worker = new Runnable() { public void run() { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("message/rfc822"); //emailIntent.setType("text/html"); emailIntent.putExtra(Intent.EXTRA_EMAIL, recipients); emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(Intent.EXTRA_TEXT, android.text.Html.fromHtml(body)); emailIntent.putExtra(Intent.EXTRA_HTML_TEXT, android.text.Html.fromHtml(body)); plugin.cordova.startActivityForResult(plugin, emailIntent, EMAIL_INTENT_RESULT); } }; this.cordova.getThreadPool().execute(worker); } public void composeSMS(final String body, final String[] recipients) { final CordovaPlugin plugin = (CordovaPlugin) this; final String recipientsAsString = joinArrayToString(recipients, ","); Runnable worker = new Runnable() { public void run() { Intent smsIntent = new Intent(); smsIntent.setData(Uri.parse("sms:" + recipientsAsString)); smsIntent.putExtra("address", recipientsAsString); smsIntent.putExtra(Intent.EXTRA_TEXT, body); smsIntent.putExtra("exit_on_sent", true); smsIntent.putExtra("sms_body", body); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { smsIntent.setAction(Intent.ACTION_SENDTO); String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(plugin.cordova.getActivity()); if (defaultSmsPackageName != null) smsIntent.setPackage(defaultSmsPackageName); } else { smsIntent.setAction(Intent.ACTION_VIEW); } plugin.cordova.startActivityForResult(plugin, smsIntent, SMS_INTENT_RESULT); } }; this.cordova.getThreadPool().execute(worker); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == EMAIL_INTENT_RESULT || requestCode == SMS_INTENT_RESULT) { this.callbackContext.success(); } } }
src/android/AppUtils.java
package com.busivid.cordova.apputils; import android.app.Activity; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Build; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Method; import java.util.ArrayList; public class AppUtils extends CordovaPlugin { private static final int EMAIL_INTENT_RESULT = 1000; private static final int SMS_INTENT_RESULT = 1001; private CallbackContext callbackContext; // The callback context from which we were invoked. @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; if (action.equals("BundleInfo")) { try { JSONObject bundleInfo = this.bundleInfo(); callbackContext.success(bundleInfo); } catch (NameNotFoundException exception) { callbackContext.error(exception.getMessage()); } } else if(action.equals("ComposeEmail")) { JSONObject jsonObject = args.getJSONObject(0); String body = jsonObject.getString("body"); JSONArray recipientsJson = jsonObject.getJSONArray("recipients"); String subject = jsonObject.getString("subject"); String[] recipients = convertJsonArrayToStringArray(recipientsJson); composeEmail(body, subject, recipients); } else if(action.equals("ComposeSMS")) { JSONObject jsonObject = args.getJSONObject(0); String body = jsonObject.getString("body"); JSONArray recipientsJson = jsonObject.getJSONArray("recipients"); String[] recipients = convertJsonArrayToStringArray(recipientsJson); composeSMS(body, recipients); } else if (action.equals("DeviceInfo")) { JSONObject deviceInfo = new JSONObject(); deviceInfo.put("name", this.getHostname()); callbackContext.success(deviceInfo); } else { return false; } return true; } public JSONObject bundleInfo() throws JSONException, NameNotFoundException { JSONObject results = new JSONObject(); Activity cordovaActivity = this.cordova.getActivity(); String packageName = cordovaActivity.getPackageName(); PackageInfo packageInfo = cordovaActivity.getPackageManager().getPackageInfo(packageName, 0); boolean isDebug = (cordovaActivity.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; results.put("bundleVersion", packageInfo.versionCode); results.put("bundleId", packageName); results.put("bundleIsDebug", isDebug); return results; } public static String getHostname() { try { Method getString = Build.class.getDeclaredMethod("getString", String.class); getString.setAccessible(true); return getString.invoke(null, "net.hostname").toString(); } catch (Exception ex) { return null; } } public static String[] convertJsonArrayToStringArray(JSONArray jsonArray) { try { ArrayList<String> list = new ArrayList<String>(); for(int i = 0; i < jsonArray.length(); i++) { list.add((String)jsonArray.get(i)); } return list.toArray(new String[list.size()]); } catch (JSONException exception) { return new String[0]; } } public static String joinArrayToString(String[] input, String seperator) { String output = ""; for (String s : input) { if(output == "") { output += s; } else { output += seperator + s; } } return output; } public void composeEmail(final String body, final String subject, final String[] recipients) { final CordovaPlugin plugin = (CordovaPlugin) this; Runnable worker = new Runnable() { public void run() { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("message/rfc822"); //emailIntent.setType("text/html"); emailIntent.putExtra(Intent.EXTRA_EMAIL, recipients); emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(Intent.EXTRA_TEXT, android.text.Html.fromHtml(body)); emailIntent.putExtra(Intent.EXTRA_HTML_TEXT, android.text.Html.fromHtml(body)); plugin.cordova.startActivityForResult(plugin, emailIntent, EMAIL_INTENT_RESULT); } }; this.cordova.getThreadPool().execute(worker); } public void composeSMS(final String body, final String[] recipients) { final CordovaPlugin plugin = (CordovaPlugin) this; final String recipientsAsString = joinArrayToString(recipients, ","); Runnable worker = new Runnable() { public void run() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("smsto:"+recipientsAsString)); smsIntent.setType("vnd.android-dir/mms-sms"); smsIntent.putExtra("address", recipientsAsString); smsIntent.putExtra("exit_on_sent", true); smsIntent.putExtra("sms_body", body); plugin.cordova.startActivityForResult(plugin, smsIntent, SMS_INTENT_RESULT); return; } //pre-kitkat way of sending an sms Intent smsIntent = new Intent(Intent.ACTION_VIEW); smsIntent.setData(Uri.parse("sms:")); smsIntent.putExtra("sms_body", body); plugin.cordova.startActivityForResult(plugin, smsIntent, SMS_INTENT_RESULT); } }; this.cordova.getThreadPool().execute(worker); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == EMAIL_INTENT_RESULT || requestCode == SMS_INTENT_RESULT) { this.callbackContext.success(); } } }
Fix SMS on Google Pixel 2
src/android/AppUtils.java
Fix SMS on Google Pixel 2
<ide><path>rc/android/AppUtils.java <ide> import android.content.pm.PackageManager.NameNotFoundException; <ide> import android.net.Uri; <ide> import android.os.Build; <add>import android.provider.Telephony; <ide> <ide> import org.apache.cordova.CallbackContext; <ide> import org.apache.cordova.CordovaPlugin; <ide> <ide> Runnable worker = new Runnable() { <ide> public void run() { <del> if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { <del> Intent smsIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("smsto:"+recipientsAsString)); <del> smsIntent.setType("vnd.android-dir/mms-sms"); <del> smsIntent.putExtra("address", recipientsAsString); <del> smsIntent.putExtra("exit_on_sent", true); <del> smsIntent.putExtra("sms_body", body); <del> plugin.cordova.startActivityForResult(plugin, smsIntent, SMS_INTENT_RESULT); <del> return; <add> Intent smsIntent = new Intent(); <add> smsIntent.setData(Uri.parse("sms:" + recipientsAsString)); <add> smsIntent.putExtra("address", recipientsAsString); <add> smsIntent.putExtra(Intent.EXTRA_TEXT, body); <add> smsIntent.putExtra("exit_on_sent", true); <add> smsIntent.putExtra("sms_body", body); <add> <add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { <add> smsIntent.setAction(Intent.ACTION_SENDTO); <add> String defaultSmsPackageName = Telephony.Sms.getDefaultSmsPackage(plugin.cordova.getActivity()); <add> if (defaultSmsPackageName != null) <add> smsIntent.setPackage(defaultSmsPackageName); <add> } else { <add> smsIntent.setAction(Intent.ACTION_VIEW); <ide> } <del> //pre-kitkat way of sending an sms <del> Intent smsIntent = new Intent(Intent.ACTION_VIEW); <del> smsIntent.setData(Uri.parse("sms:")); <del> smsIntent.putExtra("sms_body", body); <add> <ide> plugin.cordova.startActivityForResult(plugin, smsIntent, SMS_INTENT_RESULT); <ide> } <ide> };
Java
bsd-3-clause
3bbe98207b46ac1eeb996e334f8f4ac76f090841
0
eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j
/******************************************************************************* * Copyright (c) 2019 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.repository.manager; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import org.eclipse.rdf4j.http.protocol.Protocol; import org.eclipse.rdf4j.query.resultio.TupleQueryResultFormat; import org.eclipse.rdf4j.repository.config.RepositoryConfig; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import com.github.tomakehurst.wiremock.junit.WireMockRule; /** * Unit tests for {@link RemoteRepositoryManager} * * @author Jeen Broekstra * */ public class RemoteRepositoryManagerTest extends RepositoryManagerTest { @ClassRule public static WireMockRule wireMockRule = new WireMockRule(8089); // No-args constructor defaults to port 8080 @Override @Before public void setUp() { subject = new RemoteRepositoryManager("http://localhost:8089/rdf4j-server"); wireMockRule.resetAll(); } @Test public void testAddRepositoryConfig() throws Exception { wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol")) .willReturn(aResponse().withStatus(200).withBody(Protocol.VERSION))); wireMockRule .stubFor(put(urlEqualTo("/rdf4j-server/repositories/test")).willReturn(aResponse().withStatus(204))); RepositoryConfig config = new RepositoryConfig("test"); subject.addRepositoryConfig(config); wireMockRule.verify( putRequestedFor(urlEqualTo("/rdf4j-server/repositories/test")).withRequestBody(matching("^BRDF.*")) .withHeader("Content-Type", equalTo("application/x-binary-rdf"))); } @Test public void testAddRepositoryConfigLegacy() throws Exception { wireMockRule.stubFor( get(urlEqualTo("/rdf4j-server/protocol")).willReturn(aResponse().withStatus(200).withBody("8"))); wireMockRule.stubFor(post(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements")) .willReturn(aResponse().withStatus(204))); wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/repositories")) .willReturn(aResponse().withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType()) .withBodyFile("repository-list-response.srx") .withStatus(200))); RepositoryConfig config = new RepositoryConfig("test"); subject.addRepositoryConfig(config); wireMockRule.verify(postRequestedFor(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements")) .withRequestBody(matching("^BRDF.*")) .withHeader("Content-Type", equalTo("application/x-binary-rdf"))); } }
repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java
/******************************************************************************* * Copyright (c) 2019 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.repository.manager; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import org.eclipse.rdf4j.http.protocol.Protocol; import org.eclipse.rdf4j.query.resultio.TupleQueryResultFormat; import org.eclipse.rdf4j.repository.config.RepositoryConfig; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import com.github.tomakehurst.wiremock.junit.WireMockRule; /** * Unit tests for {@link RemoteRepositoryManager} * * @author Jeen Broekstra * */ public class RemoteRepositoryManagerTest extends RepositoryManagerTest { @ClassRule public static WireMockRule wireMockRule = new WireMockRule(8089); // No-args constructor defaults to port 8080 @Override @Before public void setUp() { subject = new RemoteRepositoryManager("http://localhost:8089/rdf4j-server"); wireMockRule.resetAll(); } @Test public void testAddRepositoryConfig() throws Exception { wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol")) .willReturn(aResponse().withStatus(200).withBody(Protocol.VERSION))); wireMockRule.stubFor(put(urlEqualTo("/rdf4j-server/repositories/test")) .willReturn(aResponse() .withStatus(204))); RepositoryConfig config = new RepositoryConfig("test"); subject.addRepositoryConfig(config); wireMockRule.verify(putRequestedFor(urlEqualTo("/rdf4j-server/repositories/test")) .withRequestBody(matching("^BRDF.*")) .withHeader("Content-Type", equalTo("application/x-binary-rdf"))); } @Test public void testAddRepositoryConfigLegacy() throws Exception { wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol")) .willReturn(aResponse().withStatus(200).withBody("8"))); wireMockRule.stubFor(post(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements")) .willReturn(aResponse() .withStatus(204))); wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/repositories")) .willReturn(aResponse() .withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType()) .withBodyFile("repository-list-response.srx") .withStatus(200))); RepositoryConfig config = new RepositoryConfig("test"); subject.addRepositoryConfig(config); wireMockRule.verify(postRequestedFor(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements")) .withRequestBody(matching("^BRDF.*")) .withHeader("Content-Type", equalTo("application/x-binary-rdf"))); } }
formatter :cop:
repository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java
formatter :cop:
<ide><path>epository/manager/src/test/java/org/eclipse/rdf4j/repository/manager/RemoteRepositoryManagerTest.java <ide> public void testAddRepositoryConfig() throws Exception { <ide> wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol")) <ide> .willReturn(aResponse().withStatus(200).withBody(Protocol.VERSION))); <del> wireMockRule.stubFor(put(urlEqualTo("/rdf4j-server/repositories/test")) <del> .willReturn(aResponse() <del> .withStatus(204))); <add> wireMockRule <add> .stubFor(put(urlEqualTo("/rdf4j-server/repositories/test")).willReturn(aResponse().withStatus(204))); <ide> <ide> RepositoryConfig config = new RepositoryConfig("test"); <ide> <ide> subject.addRepositoryConfig(config); <ide> <del> wireMockRule.verify(putRequestedFor(urlEqualTo("/rdf4j-server/repositories/test")) <del> .withRequestBody(matching("^BRDF.*")) <del> .withHeader("Content-Type", equalTo("application/x-binary-rdf"))); <add> wireMockRule.verify( <add> putRequestedFor(urlEqualTo("/rdf4j-server/repositories/test")).withRequestBody(matching("^BRDF.*")) <add> .withHeader("Content-Type", equalTo("application/x-binary-rdf"))); <ide> } <ide> <ide> @Test <ide> public void testAddRepositoryConfigLegacy() throws Exception { <del> wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/protocol")) <del> .willReturn(aResponse().withStatus(200).withBody("8"))); <add> wireMockRule.stubFor( <add> get(urlEqualTo("/rdf4j-server/protocol")).willReturn(aResponse().withStatus(200).withBody("8"))); <ide> wireMockRule.stubFor(post(urlPathEqualTo("/rdf4j-server/repositories/SYSTEM/statements")) <del> .willReturn(aResponse() <del> .withStatus(204))); <add> .willReturn(aResponse().withStatus(204))); <ide> wireMockRule.stubFor(get(urlEqualTo("/rdf4j-server/repositories")) <del> .willReturn(aResponse() <del> .withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType()) <add> .willReturn(aResponse().withHeader("Content-type", TupleQueryResultFormat.SPARQL.getDefaultMIMEType()) <ide> .withBodyFile("repository-list-response.srx") <ide> .withStatus(200))); <ide>
Java
mit
8033f07b83123c3399393d6ab307c01b56a9fe65
0
berryma4/diirt,berryma4/diirt,richardfearn/diirt,richardfearn/diirt,diirt/diirt,ControlSystemStudio/diirt,diirt/diirt,richardfearn/diirt,diirt/diirt,ControlSystemStudio/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,berryma4/diirt,ControlSystemStudio/diirt
/** * Copyright (C) 2012 Brookhaven National Laboratory * All rights reserved. Use is subject to license terms. */ package org.epics.graphene; import java.util.ArrayList; import java.awt.Color; /** * * @author carcassi */ public class ValueColorSchemes { /** * Creates a new gray scale color scheme based on the range. * The color red will be used for NaNs. * * @param range range for the color scheme; never null * @return the new color scheme; never null */ public static ValueColorScheme grayScale(final Range range) { return singleRangeGradient(range, Color.BLACK, Color.WHITE, Color.RED); } public static ValueColorScheme jetScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(new Color(0,0,138)); //Dark Blue colors.add(Color.BLUE); colors.add(Color.CYAN); colors.add(Color.YELLOW); colors.add(Color.RED); colors.add(new Color(138,0,0)); //Dark Red colors.add(Color.BLACK); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme hotScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(new Color(30,0,0)); //Very Dark Red colors.add(Color.RED); colors.add(Color.YELLOW); colors.add(Color.WHITE); colors.add(Color.BLUE); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme coolScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.CYAN); colors.add(new Color(66, 189, 255)); //Light Blue colors.add(new Color(189, 66, 255)); //Purple colors.add(Color.MAGENTA); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme springScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.MAGENTA); colors.add(Color.YELLOW); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme boneScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.BLACK); colors.add(new Color(44, 37, 101)); //Dark Blue colors.add(new Color(107, 115, 140)); //Blue colors.add(new Color(158, 203, 205)); //Pale Blue colors.add(Color.WHITE); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme copperScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.BLACK); colors.add(new Color(66, 41, 24)); //Dark Brown colors.add(new Color(173, 107, 68)); //Brown colors.add(new Color(239, 148, 90)); //Light Brown colors.add(new Color(255, 198, 123)); //Tan colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme pinkScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(new Color(57, 0, 0)); //Dark Red colors.add(new Color(189, 123, 123)); //Dark Pink colors.add(new Color(214, 189, 156)); //Pale Pink colors.add(Color.WHITE); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme singleRangeGradient(final Range range, final Color minValueColor, final Color maxValueColor, final Color nanColor) { if (range == null) { throw new NullPointerException("Range should not be null"); } return new ValueColorScheme() { @Override public int colorFor(double value) { if (Double.isNaN(value)) { return nanColor.getRGB(); } double normalValue = NumberUtil.normalize(value, range.getMinimum().doubleValue(), range.getMaximum().doubleValue()); normalValue = Math.min(normalValue, 1.0); normalValue = Math.max(normalValue, 0.0); int alpha = 255; int red = (int) (minValueColor.getRed() + (maxValueColor.getRed() - minValueColor.getRed()) * normalValue); int green = (int) (minValueColor.getGreen() + (maxValueColor.getGreen() - minValueColor.getGreen()) * normalValue); int blue = (int) (minValueColor.getBlue() + (maxValueColor.getBlue() - minValueColor.getBlue()) * normalValue); return (alpha << 24) | (red << 16) | (green << 8) | blue; } }; } public static ValueColorScheme RangeGradient(final Range range, final ArrayList<Color> colors, final ArrayList<Double> percentages){ return new ValueColorScheme() { Color nanColor = colors.get(colors.size()-1); @Override public int colorFor(double value) { if (Double.isNaN(value)) { return nanColor.getRGB(); } double fullRange = range.getMaximum().doubleValue() - range.getMinimum().doubleValue(); int alpha = 0, red = 0, green = 0, blue = 0; if(fullRange>0){ for(int i = 0; i < percentages.size()-1;i++){ if(range.getMinimum().doubleValue()+percentages.get(i)*fullRange <= value && value <= range.getMinimum().doubleValue()+percentages.get(i+1)*fullRange){ double normalValue = NumberUtil.normalize(value, range.getMinimum().doubleValue()+percentages.get(i)*fullRange, range.getMinimum().doubleValue()+percentages.get(i+1)*fullRange); normalValue = Math.min(normalValue, 1.0); normalValue = Math.max(normalValue, 0.0); alpha = 255; red = (int) (colors.get(i).getRed() + (colors.get(i+1).getRed() - colors.get(i).getRed()) * normalValue); green = (int) (colors.get(i).getGreen() + (colors.get(i+1).getGreen() - colors.get(i).getGreen()) * normalValue); blue = (int) (colors.get(i).getBlue() + (colors.get(i+1).getBlue() - colors.get(i).getBlue()) * normalValue); } } } else{ for(int i = 0; i < percentages.size()-1;i++){ if(percentages.get(i) <= .5 && .5 <= percentages.get(i+1)){ double normalValue =0; normalValue = Math.min(normalValue, 1.0); normalValue = Math.max(normalValue, 0.0); alpha = 255; red = (int) (colors.get(i).getRed() + (colors.get(i+1).getRed() - colors.get(i).getRed()) * normalValue); green = (int) (colors.get(i).getGreen() + (colors.get(i+1).getGreen() - colors.get(i).getGreen()) * normalValue); blue = (int) (colors.get(i).getBlue() + (colors.get(i+1).getBlue() - colors.get(i).getBlue()) * normalValue); } } } return (alpha << 24) | (red << 16) | (green << 8) | blue; } }; } private static ArrayList<Double> percentageRange(int size){ ArrayList<Double> percentages = new ArrayList<>(); percentages.add(0.0); for (int i = 1; i <= size; i++){ percentages.add((double) i / size); } return percentages; } }
graphene/src/main/java/org/epics/graphene/ValueColorSchemes.java
/** * Copyright (C) 2012 Brookhaven National Laboratory * All rights reserved. Use is subject to license terms. */ package org.epics.graphene; import java.util.ArrayList; import java.awt.Color; /** * * @author carcassi */ public class ValueColorSchemes { public static ValueColorScheme grayScale(final Range range) { return singleRangeGradient(range, Color.BLACK, Color.WHITE, Color.RED); } public static ValueColorScheme jetScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(new Color(0,0,138)); //Dark Blue colors.add(Color.BLUE); colors.add(Color.CYAN); colors.add(Color.YELLOW); colors.add(Color.RED); colors.add(new Color(138,0,0)); //Dark Red colors.add(Color.BLACK); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme hotScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(new Color(30,0,0)); //Very Dark Red colors.add(Color.RED); colors.add(Color.YELLOW); colors.add(Color.WHITE); colors.add(Color.BLUE); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme coolScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.CYAN); colors.add(new Color(66, 189, 255)); //Light Blue colors.add(new Color(189, 66, 255)); //Purple colors.add(Color.MAGENTA); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme springScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.MAGENTA); colors.add(Color.YELLOW); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme boneScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.BLACK); colors.add(new Color(44, 37, 101)); //Dark Blue colors.add(new Color(107, 115, 140)); //Blue colors.add(new Color(158, 203, 205)); //Pale Blue colors.add(Color.WHITE); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme copperScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.BLACK); colors.add(new Color(66, 41, 24)); //Dark Brown colors.add(new Color(173, 107, 68)); //Brown colors.add(new Color(239, 148, 90)); //Light Brown colors.add(new Color(255, 198, 123)); //Tan colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme pinkScale(final Range range) { ArrayList<Color> colors = new ArrayList<>(); colors.add(new Color(57, 0, 0)); //Dark Red colors.add(new Color(189, 123, 123)); //Dark Pink colors.add(new Color(214, 189, 156)); //Pale Pink colors.add(Color.WHITE); colors.add(Color.RED); //NaN return RangeGradient(range, colors, percentageRange(colors.size() - 2)); } public static ValueColorScheme singleRangeGradient(final Range range, final Color minValueColor, final Color maxValueColor, final Color nanColor) { return new ValueColorScheme() { @Override public int colorFor(double value) { if (Double.isNaN(value)) { return nanColor.getRGB(); } double normalValue = NumberUtil.normalize(value, range.getMinimum().doubleValue(), range.getMaximum().doubleValue()); normalValue = Math.min(normalValue, 1.0); normalValue = Math.max(normalValue, 0.0); int alpha = 255; int red = (int) (minValueColor.getRed() + (maxValueColor.getRed() - minValueColor.getRed()) * normalValue); int green = (int) (minValueColor.getGreen() + (maxValueColor.getGreen() - minValueColor.getGreen()) * normalValue); int blue = (int) (minValueColor.getBlue() + (maxValueColor.getBlue() - minValueColor.getBlue()) * normalValue); return (alpha << 24) | (red << 16) | (green << 8) | blue; } }; } public static ValueColorScheme RangeGradient(final Range range, final ArrayList<Color> colors, final ArrayList<Double> percentages){ return new ValueColorScheme() { Color nanColor = colors.get(colors.size()-1); @Override public int colorFor(double value) { if (Double.isNaN(value)) { return nanColor.getRGB(); } double fullRange = range.getMaximum().doubleValue() - range.getMinimum().doubleValue(); int alpha = 0, red = 0, green = 0, blue = 0; if(fullRange>0){ for(int i = 0; i < percentages.size()-1;i++){ if(range.getMinimum().doubleValue()+percentages.get(i)*fullRange <= value && value <= range.getMinimum().doubleValue()+percentages.get(i+1)*fullRange){ double normalValue = NumberUtil.normalize(value, range.getMinimum().doubleValue()+percentages.get(i)*fullRange, range.getMinimum().doubleValue()+percentages.get(i+1)*fullRange); normalValue = Math.min(normalValue, 1.0); normalValue = Math.max(normalValue, 0.0); alpha = 255; red = (int) (colors.get(i).getRed() + (colors.get(i+1).getRed() - colors.get(i).getRed()) * normalValue); green = (int) (colors.get(i).getGreen() + (colors.get(i+1).getGreen() - colors.get(i).getGreen()) * normalValue); blue = (int) (colors.get(i).getBlue() + (colors.get(i+1).getBlue() - colors.get(i).getBlue()) * normalValue); } } } else{ for(int i = 0; i < percentages.size()-1;i++){ if(percentages.get(i) <= .5 && .5 <= percentages.get(i+1)){ double normalValue =0; normalValue = Math.min(normalValue, 1.0); normalValue = Math.max(normalValue, 0.0); alpha = 255; red = (int) (colors.get(i).getRed() + (colors.get(i+1).getRed() - colors.get(i).getRed()) * normalValue); green = (int) (colors.get(i).getGreen() + (colors.get(i+1).getGreen() - colors.get(i).getGreen()) * normalValue); blue = (int) (colors.get(i).getBlue() + (colors.get(i+1).getBlue() - colors.get(i).getBlue()) * normalValue); } } } return (alpha << 24) | (red << 16) | (green << 8) | blue; } }; } private static ArrayList<Double> percentageRange(int size){ ArrayList<Double> percentages = new ArrayList<>(); percentages.add(0.0); for (int i = 1; i <= size; i++){ percentages.add((double) i / size); } return percentages; } }
Javadoc update
graphene/src/main/java/org/epics/graphene/ValueColorSchemes.java
Javadoc update
<ide><path>raphene/src/main/java/org/epics/graphene/ValueColorSchemes.java <ide> */ <ide> public class ValueColorSchemes { <ide> <add> /** <add> * Creates a new gray scale color scheme based on the range. <add> * The color red will be used for NaNs. <add> * <add> * @param range range for the color scheme; never null <add> * @return the new color scheme; never null <add> */ <ide> public static ValueColorScheme grayScale(final Range range) { <ide> return singleRangeGradient(range, Color.BLACK, Color.WHITE, Color.RED); <ide> } <ide> <ide> <ide> public static ValueColorScheme singleRangeGradient(final Range range, final Color minValueColor, final Color maxValueColor, final Color nanColor) { <add> if (range == null) { <add> throw new NullPointerException("Range should not be null"); <add> } <ide> return new ValueColorScheme() { <ide> <ide> @Override
JavaScript
mit
cc20fccc8350759b46332343d391971eed8dad1e
0
abalabahaha/eris,briantanner/eris
"use strict"; const ChildProcess = require("child_process"); const Constants = require("../Constants"); const Dgram = require("dgram"); const DNS = require("dns"); const OPCodes = Constants.VoiceOPCodes; const Piper = require("./Piper"); const VoiceDataStream = require("./VoiceDataStream"); var WebSocket = typeof window !== "undefined" ? window.WebSocket : require("ws"); var EventEmitter; try { EventEmitter = require("eventemitter3"); } catch(err) { EventEmitter = require("events").EventEmitter; } var NodeOpus; try { NodeOpus = require("node-opus"); } catch(err) { // eslint-disable no-empty } var OpusScript; try { OpusScript = require("opusscript"); } catch(err) { // eslint-disable no-empty } var Sodium = false; var NaCl = false; try { Sodium = require("sodium-native"); } catch(err) { try { NaCl = require("tweetnacl"); } catch(err) { // eslint-disable no-empty } } try { WebSocket = require("uws"); } catch(err) { // eslint-disable no-empty } const MAX_FRAME_SIZE = 1276 * 3; const ENCRYPTION_MODE = "xsalsa20_poly1305"; var converterCommand = { cmd: null, libopus: false }; converterCommand.pickCommand = function pickCommand() { var tenative; for(var command of ["./ffmpeg", "./avconv", "ffmpeg", "avconv"]) { var res = ChildProcess.spawnSync(command, ["-encoders"]); if(!res.error) { if(!res.stdout.toString().includes("libopus")) { tenative = command; continue; } converterCommand.cmd = command; converterCommand.libopus = true; return; } } if(tenative) { converterCommand.cmd = tenative; return; } }; /** * Represents a voice connection * @extends EventEmitter * @prop {String} id The ID of the voice connection (guild ID) * @prop {String} channelID The ID of the voice connection's current channel * @prop {Boolean} connecting Whether the voice connection is connecting * @prop {Boolean} ready Whether the voice connection is ready * @prop {Boolean} playing Whether the voice connection is playing something * @prop {Boolean} paused Whether the voice connection is paused * @prop {Number} volume The current volume level of the connection * @prop {Object?} current The state of the currently playing stream * @prop {Number} current.startTime The timestamp of the start of the current stream * @prop {Number} current.playTime How long the current stream has been playing for, in milliseconds * @prop {Number} current.pausedTimestamp The timestamp of the most recent pause * @prop {Number} current.pausedTime How long the current stream has been paused for, in milliseconds * @prop {Options} current.options The custom options for the current stream */ class VoiceConnection extends EventEmitter { constructor(id, options) { super(); options = options || {}; if(typeof window !== "undefined") { throw new Error("Voice is not supported in browsers at this time"); } if(!Sodium && !NaCl) { throw new Error("Error loading tweetnacl/libsodium, voice not available"); } this.id = id; this.samplingRate = 48000; this.channels = 2; this.frameDuration = 20; this.frameSize = this.samplingRate * this.frameDuration / 1000; this.pcmSize = this.frameSize * this.channels * 2; this.bitrate = 64000; this.shared = !!options.shared; this.shard = options.shard || {}; this.opusOnly = !!options.opusOnly; if(!this.opusOnly && !this.shared) { if(NodeOpus) { this.opus = new NodeOpus.OpusEncoder(this.samplingRate, this.channels); } else if(OpusScript) { this.emit("debug", "node-opus not found, falling back to opusscript"); this.opus = new OpusScript(this.samplingRate, this.channels, OpusScript.Application.AUDIO); if(this.opus.setBitrate) { this.opus.setBitrate(this.bitrate); } else if(this.opus.encoderCTL) { this.opus.encoderCTL(4002, this.bitrate); } } else { throw new Error("No opus encoder found, playing non-opus audio will not work."); } } this.channelID = null; this.paused = true; this.speaking = false; this.sequence = 0; this.timestamp = 0; this.ssrcUserMap = {}; this.nonce = new Buffer(24); this.nonce.fill(0); this.packetBuffer = new Buffer(12 + 16 + MAX_FRAME_SIZE); this.packetBuffer.fill(0); this.packetBuffer[0] = 0x80; this.packetBuffer[1] = 0x78; if(!options.shared) { if(!converterCommand.cmd) { converterCommand.pickCommand(); } this.piper = new Piper(converterCommand.cmd, this.opus); /** * Fired when the voice connection encounters an error. This event should be handled by users * @event VoiceConnection#error * @prop {Error} err The error object */ this.piper.on("error", (e) => this.emit("error", e)); if(!converterCommand.libopus) { this.piper.libopus = false; } } this._send = this._send.bind(this); } _destroy() { if(this.opus && this.opus.delete) { this.opus.delete(); delete this.opus; } delete this.piper; if(this.receiveStreamOpus) { this.receiveStreamOpus.destroy(); } if(this.receiveStreamPCM) { this.receiveStreamPCM.destroy(); } } connect(data) { if(this.connecting) { return; } this.connecting = true; if(this.ws && this.ws.readyState !== WebSocket.CLOSED) { this.disconnect(undefined, true); return setTimeout(() => this.connect(data), 500); } if(!data.endpoint || !data.token || !data.session_id || !data.user_id) { this.disconnect(new Error("Malformed voice server update: " + JSON.stringify(data))); return; } this.channelID = data.channel_id; this.endpoint = data.endpoint.split(":")[0]; this.ws = new WebSocket("wss://" + this.endpoint); var connectionTimeout = setTimeout(() => { if(this.connecting) { this.disconnect(new Error("Voice connection timeout")); } connectionTimeout = null; }, this.shard.client ? this.shard.client.options.connectionTimeout : 30000); /** * Fired when stuff happens and gives more info * @event VoiceConnection#debug * @prop {String} message The debug message */ this.emit("debug", "Connection: " + JSON.stringify(data)); this.ws.on("open", () => { /** * Fired when the voice connection connects * @event VoiceConnection#connect */ this.emit("connect"); if(connectionTimeout) { clearTimeout(connectionTimeout); connectionTimeout = null; } this.sendWS(OPCodes.IDENTIFY, { server_id: this.id === "call" ? data.channel_id : this.id, user_id: data.user_id, session_id: data.session_id, token: data.token }); }); this.ws.on("message", (m) => { var packet = JSON.parse(m); if(this.listeners("debug").length > 0) { this.emit("debug", "Rec: " + JSON.stringify(packet)); } switch(packet.op) { case OPCodes.HELLO: { if(packet.d.heartbeat_interval > 0) { if(this.heartbeatInterval) { clearInterval(this.heartbeatInterval); } this.heartbeatInterval = setInterval(() => { this.heartbeat(); }, packet.d.heartbeat_interval); this.heartbeat(); } this.ssrc = packet.d.ssrc; this.packetBuffer.writeUIntBE(this.ssrc, 8, 4); if(!~packet.d.modes.indexOf(ENCRYPTION_MODE)) { throw new Error("No supported voice mode found"); } this.modes = packet.d.modes; this.udpPort = packet.d.port; DNS.lookup(this.endpoint, (err, address) => { // RIP DNS if(err) { this.emit("error", err); return; } this.udpIP = address; this.emit("debug", "Connecting to UDP: " + this.udpIP + ":" + this.udpPort); this.udpSocket = Dgram.createSocket("udp4"); this.udpSocket.once("message", (packet) => { this.emit("debug", packet.toString()); var localIP = ""; var i = 3; while(++i < packet.indexOf(0, i)) { localIP += String.fromCharCode(packet[i]); } var localPort = parseInt(packet.readUIntLE(packet.length - 2, 2).toString(10)); this.sendWS(OPCodes.SELECT_PROTOCOL, { protocol: "udp", data: { address: localIP, port: localPort, mode: ENCRYPTION_MODE } }); }); this.udpSocket.on("error", (err, msg) => { this.emit("error", err); if(msg) { this.emit("debug", "Voice UDP error: " + msg); } if(this.ready || this.connecting) { this.disconnect(err); } }); this.udpSocket.on("close", (err) => { if(err) { this.emit("warn", "Voice UDP close: " + err); } if(this.ready || this.connecting) { this.disconnect(err); } }); var udpMessage = new Buffer(70); udpMessage.fill(0); udpMessage.writeUIntBE(this.ssrc, 0, 4); this._sendPacket(udpMessage); }); break; } case OPCodes.SESSION_DESCRIPTION: { this.mode = packet.d.mode; this.secret = new Uint8Array(new ArrayBuffer(packet.d.secret_key.length)); for (var i = 0; i < packet.d.secret_key.length; ++i) { this.secret[i] = packet.d.secret_key[i]; } this.connecting = false; this.ready = true; /** * Fired when the voice connection turns ready * @event VoiceConnection#ready */ this.emit("ready"); this.resume(); break; } case OPCodes.HEARTBEAT: { /** * Fired when the voice connection receives a pong * @event VoiceConnection#pong * @prop {Number} latency The current latency in milliseconds */ this.emit("pong", Date.now() - packet.d); break; } case OPCodes.SPEAKING: { this.ssrcUserMap[packet.d.ssrc] = packet.d.user_id; /** * Fired when a user begins speaking * @event VoiceConnection#speakingStart * @prop {String} userID The ID of the user that began speaking */ /** * Fired when a user stops speaking * @event VoiceConnection#speakingStop * @prop {String} userID The ID of the user that stopped speaking */ this.emit(packet.d.speaking ? "speakingStart" : "speakingStop", packet.d.user_id); break; } default: { this.emit("unknown", packet); break; } } }); this.ws.on("error", (err) => { this.emit("error", err); }); this.ws.on("close", (code, reason) => { var err = !code || code === 1000 ? null : new Error(code + ": " + reason); this.emit("warn", `Voice WS close ${code}: ${reason}`); if(this.connecting || this.ready) { var reconnecting = true; if(code === 4006) { reconnecting = false; } else if(code === 1000) { reconnecting = false; } this.disconnect(err, reconnecting); if(reconnecting) { setTimeout(() => this.connect(data), 500); } } }); } disconnect(error, reconnecting) { this.connecting = false; this.ready = false; this.speaking = false; this.timestamp = 0; this.sequence = 0; if(reconnecting) { this.pause(); } else { this.stopPlaying(); } if(this.heartbeatInterval) { clearInterval(this.heartbeatInterval); this.heartbeatInterval = null; } if(this.udpSocket) { try { this.udpSocket.close(); } catch(err) { if(err.message !== "Not running") { this.emit("error", err); } } this.udpSocket = null; } if(this.ws) { try { this.ws.close(); } catch(err) { this.emit("error", err); } this.ws = null; } if(reconnecting) { if(error) { this.emit("error", error); } } else { this.channelID = null; this.updateVoiceState(); /** * Fired when the voice connection disconnects * @event VoiceConnection#disconnect * @prop {Error?} err The error, if any */ this.emit("disconnect", error); } } heartbeat() { this.sendWS(OPCodes.HEARTBEAT, Date.now()); } /** * Play an audio or video resource. If playing from a non-opus resource, FFMPEG should be compiled with --enable-libopus for best performance. If playing from HTTPS, FFMPEG must be compiled with --enable-openssl * @arg {ReadableStream | String} resource The audio or video resource, either a ReadableStream, URL, or file path * @arg {Object} [options] Music options * @arg {Boolean} [options.inlineVolume=false] Whether to enable on-the-fly volume changing. Note that enabling this leads to increased CPU usage * @arg {Number} [options.voiceDataTimeout=2000] Timeout when waiting for voice data (-1 for no timeout) * @arg {Array<String>} [options.inputArgs] Additional input parameters to pass to ffmpeg/avconv (before -i) * @arg {Array<String>} [options.encoderArgs] Additional encoder parameters to pass to ffmpeg/avconv (after -i) * @arg {String} [options.format] The format of the resource. If null, FFmpeg will attempt to guess and play the format. Available options: "dca", "ogg", "webm", "pcm", null * @arg {Number} [options.frameDuration=20] The resource opus frame duration (required for DCA/Ogg) * @arg {Number} [options.frameSize=2880] The resource opus frame size * @arg {Number} [options.sampleRate=48000] The resource audio sampling rate */ play(source, options) { if(this.shared) { throw new Error("Cannot play stream on shared voice connection"); } if(!this.ready) { throw new Error("Not ready yet"); } options = options || {}; options.format = options.format || null; options.voiceDataTimeout = !isNaN(options.voiceDataTimeout) ? options.voiceDataTimeout : 2000; options.inlineVolume = !!options.inlineVolume; options.inputArgs = options.inputArgs || []; options.encoderArgs = options.encoderArgs || []; options.samplingRate = options.samplingRate || this.samplingRate; options.frameDuration = options.frameDuration || this.frameDuration; options.frameSize = options.frameSize || options.samplingRate * options.frameDuration / 1000; options.pcmSize = options.pcmSize || options.frameSize * 2 * this.channels; if(!this.piper.encode(source, options)) { this.emit("error", new Error("Unable to encode source")); return; } this.ended = false; this.current = { startTime: 0, // later playTime: 0, pausedTimestamp: 0, pausedTime: 0, bufferingTicks: 0, options: options, timeout: null, buffer: null }; this.playing = true; /** * Fired when the voice connection starts playing a stream * @event SharedStream#start */ this.emit("start"); this._send(); } _send() { if(!this.piper.encoding && this.piper.dataPacketCount === 0) { return this.stopPlaying(); } this.timestamp += this.current.options.frameSize; if(this.timestamp >= 4294967295) { this.timestamp -= 4294967295; } if(++this.sequence >= 65536) { this.sequence -= 65536; } if((this.current.buffer = this.piper.getDataPacket())) { if(this.current.startTime === 0) { this.current.startTime = Date.now(); } if(this.current.bufferingTicks > 0) { this.current.bufferingTicks = 0; this.setSpeaking(true); } } else if(this.current.options.voiceDataTimeout === -1 || this.current.bufferingTicks < this.current.options.voiceDataTimeout / this.current.options.frameDuration) { // wait for data if(++this.current.bufferingTicks <= 0) { this.setSpeaking(false); } this.current.pausedTime += 4 * this.current.options.frameDuration; this.timestamp += 3 * this.current.options.frameSize; if(this.timestamp >= 4294967295) { this.timestamp -= 4294967295; } this.current.timeout = setTimeout(this._send, 4 * this.current.options.frameDuration); return; } else { return this.stopPlaying(); } this._sendPacket(this._createPacket(this.current.buffer)); this.current.playTime += this.current.options.frameDuration; this.current.timeout = setTimeout(this._send, this.current.startTime + this.current.pausedTime + this.current.playTime - Date.now()); } /** * Stop the bot from sending audio */ stopPlaying() { if(this.ended) { return; } this.ended = true; if(this.current && this.current.timeout) { clearTimeout(this.current.timeout); this.current.timeout = null; } this.current = null; if(this.piper) { this.piper.stop(); this.piper.resetPackets(); } if(this.secret) { for(var i = 0; i < 5; i++) { this.timestamp += this.frameSize; if(this.timestamp >= 4294967295) { this.timestamp -= 4294967295; } if(++this.sequence >= 65536) { this.sequence -= 65536; } this._sendPacket(this._createPacket(new Buffer([0xF8, 0xFF, 0xFE]))); } } this.setSpeaking(this.playing = false); /** * Fired when the voice connection finishes playing a stream * @event VoiceConnection#end */ this.emit("end"); } _createPacket(_buffer) { this.packetBuffer.writeUIntBE(this.sequence, 2, 2); this.packetBuffer.writeUIntBE(this.timestamp, 4, 4); this.packetBuffer.copy(this.nonce, 0, 0, 12); var len = _buffer.length; if(!NaCl) { Sodium.crypto_secretbox_easy(this.packetBuffer.slice(12), _buffer, this.nonce, this.secret); len += Sodium.crypto_secretbox_MACBYTES; } else { var buffer = NaCl.secretbox(_buffer, this.nonce, this.secret); len += NaCl.lowlevel.crypto_secretbox_BOXZEROBYTES; this.packetBuffer.fill(0, 12, 12 + len); for (var i = 0; i < len; ++i) { this.packetBuffer[12 + i] = buffer[i]; } } return this.packetBuffer.slice(0, 12 + len); } _sendPacket(packet) { try { this.udpSocket.send(packet, 0, packet.length, this.udpPort, this.udpIP); } catch(e) { if(this.udpSocket) { this.emit("error", e); } } } /** * Generate a receive stream for the voice connection. * @arg {String} [type="pcm"] The desired vocie data type, either "opus" or "pcm" * @returns {VoiceDataStream} */ receive(type) { if(type === "pcm") { if(!this.receiveStreamPCM) { this.receiveStreamPCM = new VoiceDataStream(type); if(!this.receiveStreamOpus) { this.registerReceiveEventHandler(); } } } else if(type === "opus") { if(!this.receiveStreamOpus) { this.receiveStreamOpus = new VoiceDataStream(type); if(!this.receiveStreamPCM) { this.registerReceiveEventHandler(); } } } else { throw new Error(`Unsupported voice data type: ${type}`); } return type === "pcm" ? this.receiveStreamPCM : this.receiveStreamOpus; } registerReceiveEventHandler() { this.udpSocket.on("message", (msg) => { var nonce = new Buffer(24); nonce.fill(0); msg.copy(nonce, 0, 0, 12); var data; if(!NaCl) { data = new Buffer(msg.length - 12 - Sodium.crypto_secretbox_MACBYTES); Sodium.crypto_secretbox_open_easy(data, msg.slice(12), this.nonce, this.secret); } else { if(!(data = NaCl.secretbox.open(msg.slice(12), nonce, this.secret))) { /** * Fired to warn of something weird but non-breaking happening * @event VoiceConnection#warn * @prop {String} message The warning message */ this.emit("warn", "Failed to decrypt received packet"); return; } } if(data[0] === 0xBE && data[1] === 0xDE) { // RFC5285 Section 4.2: One-Byte Header var rtpHeaderExtensionLength = data[2] << 8 | data[3]; var index = 4; var byte; for(let i = 0; i < rtpHeaderExtensionLength; ++i) { byte = data[index]; ++index; let l = (byte & 0b1111) + 1; index += l; while(data[index] == 0) { ++index; } } data = data.slice(index); } // Have not received a RFC5285 Section 4.3: Two-Byte Header yet, so that is unimplemented for now if(this.receiveStreamOpus) { /** * Fired when a voice data packet is received * @event VoiceDataStream#data * @prop {Buffer} data The voice data * @prop {String} userID The user who sent the voice packet * @prop {Number} timestamp The intended timestamp of the packet * @prop {Number} sequence The intended sequence number of the packet */ this.receiveStreamOpus.emit("data", data, this.ssrcUserMap[nonce.readUIntBE(8, 4)], nonce.readUIntBE(4, 4), nonce.readUIntBE(2, 2)); } if(this.receiveStreamPCM) { data = this.opus.decode(data, this.frameSize); if(!data) { return this.emit("warn", "Failed to decode received packet"); } this.receiveStreamPCM.emit("data", data, this.ssrcUserMap[nonce.readUIntBE(8, 4)], nonce.readUIntBE(4, 4), nonce.readUIntBE(2, 2)); } }); } setSpeaking(value) { if((value = !!value) != this.speaking) { this.speaking = value; this.sendWS(OPCodes.SPEAKING, { speaking: value, delay: 0 }); } } /** * Switch the voice channel the bot is in. The channel to switch to must be in the same guild as the current voice channel * @arg {String} channelID The ID of the voice channel */ switchChannel(channelID, reactive) { if(this.channelID === channelID) { return; } this.channelID = channelID; if(!reactive) { this.updateVoiceState(); } } /** * Update the bot's voice state * @arg {Boolean} selfMute Whether the bot muted itself or not (audio sending is unaffected) * @arg {Boolean} selfDeaf Whether the bot deafened itself or not (audio receiving is unaffected) */ updateVoiceState(selfMute, selfDeaf) { if(this.shard.sendWS) { this.shard.sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, { guild_id: this.id === "call" ? null : this.id, channel_id: this.channelID || null, self_mute: !!selfMute, self_deaf: !!selfDeaf }); } } sendWS(op, data) { if(this.ws && this.ws.readyState === WebSocket.OPEN) { data = JSON.stringify({op: op, d: data}); this.ws.send(data); this.emit("debug", data); } } get volume() { return this.piper.volumeLevel; } /** * Modify the output volume of the current stream (if inlineVolume is enabled for the current stream) * @arg {Number} [volume=1.0] The desired volume. 0.0 is 0%, 1.0 is 100%, 2.0 is 200%, etc. It is not recommended to go above 2.0 */ setVolume(volume) { this.piper.setVolume(volume); } /** * Pause sending audio (if playing) */ pause() { this.paused = true; this.setSpeaking(false); if(this.current) { if(!this.current.pausedTimestamp) { this.current.pausedTimestamp = Date.now(); } if(this.current.timeout) { clearTimeout(this.current.timeout); this.current.timeout = null; } } } /** * Resume sending audio (if paused) */ resume() { this.paused = false; this.setSpeaking(true); if(this.current) { if(this.current.pausedTimestamp) { this.current.pausedTime += Date.now() - this.current.pausedTimestamp; this.current.pausedTimestamp = 0; } this._send(); } } toJSON() { var base = {}; for(var key in this) { if(this.hasOwnProperty(key) && !key.startsWith("_") && !key.endsWith("Interval") && !key.endsWith("Timeout") && !~["nonce", "packetBuffer", "piper", "shard", "udpSocket", "ws"].indexOf(key)) { if(!this[key]) { base[key] = this[key]; } else if(this[key] instanceof Set) { base[key] = Array.from(this[key]); } else if(this[key] instanceof Map) { base[key] = Array.from(this[key].values()); } else if(typeof this[key].toJSON === "function") { base[key] = this[key].toJSON(); } else { base[key] = this[key]; } } } if(base.current && base.current.timeout) { delete base.current.timeout; } return base; } } VoiceConnection._converterCommand = converterCommand; module.exports = VoiceConnection;
lib/voice/VoiceConnection.js
"use strict"; const ChildProcess = require("child_process"); const Constants = require("../Constants"); const Dgram = require("dgram"); const DNS = require("dns"); const OPCodes = Constants.VoiceOPCodes; const Piper = require("./Piper"); const VoiceDataStream = require("./VoiceDataStream"); var WebSocket = typeof window !== "undefined" ? window.WebSocket : require("ws"); var EventEmitter; try { EventEmitter = require("eventemitter3"); } catch(err) { EventEmitter = require("events").EventEmitter; } var NodeOpus; try { NodeOpus = require("node-opus"); } catch(err) { // eslint-disable no-empty } var OpusScript; try { OpusScript = require("opusscript"); } catch(err) { // eslint-disable no-empty } var Sodium = false; var NaCl = false; try { Sodium = require("sodium-native"); } catch(err) { try { NaCl = require("tweetnacl"); } catch(err) { // eslint-disable no-empty } } try { WebSocket = require("uws"); } catch(err) { // eslint-disable no-empty } const MAX_FRAME_SIZE = 1276 * 3; const ENCRYPTION_MODE = "xsalsa20_poly1305"; var converterCommand = { cmd: null, libopus: false }; converterCommand.pickCommand = function pickCommand() { var tenative; for(var command of ["./ffmpeg", "./avconv", "ffmpeg", "avconv"]) { var res = ChildProcess.spawnSync(command, ["-encoders"]); if(!res.error) { if(!res.stdout.toString().includes("libopus")) { tenative = command; continue; } converterCommand.cmd = command; converterCommand.libopus = true; return; } } if(tenative) { converterCommand.cmd = tenative; return; } throw new Error("Neither ffmpeg nor avconv was found. Make sure you installed either one, and check that it is in your PATH"); }; /** * Represents a voice connection * @extends EventEmitter * @prop {String} id The ID of the voice connection (guild ID) * @prop {String} channelID The ID of the voice connection's current channel * @prop {Boolean} connecting Whether the voice connection is connecting * @prop {Boolean} ready Whether the voice connection is ready * @prop {Boolean} playing Whether the voice connection is playing something * @prop {Boolean} paused Whether the voice connection is paused * @prop {Number} volume The current volume level of the connection * @prop {Object?} current The state of the currently playing stream * @prop {Number} current.startTime The timestamp of the start of the current stream * @prop {Number} current.playTime How long the current stream has been playing for, in milliseconds * @prop {Number} current.pausedTimestamp The timestamp of the most recent pause * @prop {Number} current.pausedTime How long the current stream has been paused for, in milliseconds * @prop {Options} current.options The custom options for the current stream */ class VoiceConnection extends EventEmitter { constructor(id, options) { super(); options = options || {}; if(typeof window !== "undefined") { throw new Error("Voice is not supported in browsers at this time"); } if(!Sodium && !NaCl) { throw new Error("Error loading tweetnacl/libsodium, voice not available"); } this.id = id; this.samplingRate = 48000; this.channels = 2; this.frameDuration = 20; this.frameSize = this.samplingRate * this.frameDuration / 1000; this.pcmSize = this.frameSize * this.channels * 2; this.bitrate = 64000; this.shared = !!options.shared; this.shard = options.shard || {}; this.opusOnly = !!options.opusOnly; if(!this.opusOnly && !this.shared) { if(NodeOpus) { this.opus = new NodeOpus.OpusEncoder(this.samplingRate, this.channels); } else if(OpusScript) { this.emit("debug", "node-opus not found, falling back to opusscript"); this.opus = new OpusScript(this.samplingRate, this.channels, OpusScript.Application.AUDIO); if(this.opus.setBitrate) { this.opus.setBitrate(this.bitrate); } else if(this.opus.encoderCTL) { this.opus.encoderCTL(4002, this.bitrate); } } else { throw new Error("No opus encoder found, playing non-opus audio will not work."); } } this.channelID = null; this.paused = true; this.speaking = false; this.sequence = 0; this.timestamp = 0; this.ssrcUserMap = {}; this.nonce = new Buffer(24); this.nonce.fill(0); this.packetBuffer = new Buffer(12 + 16 + MAX_FRAME_SIZE); this.packetBuffer.fill(0); this.packetBuffer[0] = 0x80; this.packetBuffer[1] = 0x78; if(!options.shared) { if(!converterCommand.cmd) { converterCommand.pickCommand(); } this.piper = new Piper(converterCommand.cmd, this.opus); /** * Fired when the voice connection encounters an error. This event should be handled by users * @event VoiceConnection#error * @prop {Error} err The error object */ this.piper.on("error", (e) => this.emit("error", e)); if(!converterCommand.libopus) { this.piper.libopus = false; } } this._send = this._send.bind(this); } _destroy() { if(this.opus && this.opus.delete) { this.opus.delete(); delete this.opus; } delete this.piper; if(this.receiveStreamOpus) { this.receiveStreamOpus.destroy(); } if(this.receiveStreamPCM) { this.receiveStreamPCM.destroy(); } } connect(data) { if(this.connecting) { return; } this.connecting = true; if(this.ws && this.ws.readyState !== WebSocket.CLOSED) { this.disconnect(undefined, true); return setTimeout(() => this.connect(data), 500); } if(!data.endpoint || !data.token || !data.session_id || !data.user_id) { this.disconnect(new Error("Malformed voice server update: " + JSON.stringify(data))); return; } this.channelID = data.channel_id; this.endpoint = data.endpoint.split(":")[0]; this.ws = new WebSocket("wss://" + this.endpoint); var connectionTimeout = setTimeout(() => { if(this.connecting) { this.disconnect(new Error("Voice connection timeout")); } connectionTimeout = null; }, this.shard.client ? this.shard.client.options.connectionTimeout : 30000); /** * Fired when stuff happens and gives more info * @event VoiceConnection#debug * @prop {String} message The debug message */ this.emit("debug", "Connection: " + JSON.stringify(data)); this.ws.on("open", () => { /** * Fired when the voice connection connects * @event VoiceConnection#connect */ this.emit("connect"); if(connectionTimeout) { clearTimeout(connectionTimeout); connectionTimeout = null; } this.sendWS(OPCodes.IDENTIFY, { server_id: this.id === "call" ? data.channel_id : this.id, user_id: data.user_id, session_id: data.session_id, token: data.token }); }); this.ws.on("message", (m) => { var packet = JSON.parse(m); if(this.listeners("debug").length > 0) { this.emit("debug", "Rec: " + JSON.stringify(packet)); } switch(packet.op) { case OPCodes.HELLO: { if(packet.d.heartbeat_interval > 0) { if(this.heartbeatInterval) { clearInterval(this.heartbeatInterval); } this.heartbeatInterval = setInterval(() => { this.heartbeat(); }, packet.d.heartbeat_interval); this.heartbeat(); } this.ssrc = packet.d.ssrc; this.packetBuffer.writeUIntBE(this.ssrc, 8, 4); if(!~packet.d.modes.indexOf(ENCRYPTION_MODE)) { throw new Error("No supported voice mode found"); } this.modes = packet.d.modes; this.udpPort = packet.d.port; DNS.lookup(this.endpoint, (err, address) => { // RIP DNS if(err) { this.emit("error", err); return; } this.udpIP = address; this.emit("debug", "Connecting to UDP: " + this.udpIP + ":" + this.udpPort); this.udpSocket = Dgram.createSocket("udp4"); this.udpSocket.once("message", (packet) => { this.emit("debug", packet.toString()); var localIP = ""; var i = 3; while(++i < packet.indexOf(0, i)) { localIP += String.fromCharCode(packet[i]); } var localPort = parseInt(packet.readUIntLE(packet.length - 2, 2).toString(10)); this.sendWS(OPCodes.SELECT_PROTOCOL, { protocol: "udp", data: { address: localIP, port: localPort, mode: ENCRYPTION_MODE } }); }); this.udpSocket.on("error", (err, msg) => { this.emit("error", err); if(msg) { this.emit("debug", "Voice UDP error: " + msg); } if(this.ready || this.connecting) { this.disconnect(err); } }); this.udpSocket.on("close", (err) => { if(err) { this.emit("warn", "Voice UDP close: " + err); } if(this.ready || this.connecting) { this.disconnect(err); } }); var udpMessage = new Buffer(70); udpMessage.fill(0); udpMessage.writeUIntBE(this.ssrc, 0, 4); this._sendPacket(udpMessage); }); break; } case OPCodes.SESSION_DESCRIPTION: { this.mode = packet.d.mode; this.secret = new Uint8Array(new ArrayBuffer(packet.d.secret_key.length)); for (var i = 0; i < packet.d.secret_key.length; ++i) { this.secret[i] = packet.d.secret_key[i]; } this.connecting = false; this.ready = true; /** * Fired when the voice connection turns ready * @event VoiceConnection#ready */ this.emit("ready"); this.resume(); break; } case OPCodes.HEARTBEAT: { /** * Fired when the voice connection receives a pong * @event VoiceConnection#pong * @prop {Number} latency The current latency in milliseconds */ this.emit("pong", Date.now() - packet.d); break; } case OPCodes.SPEAKING: { this.ssrcUserMap[packet.d.ssrc] = packet.d.user_id; /** * Fired when a user begins speaking * @event VoiceConnection#speakingStart * @prop {String} userID The ID of the user that began speaking */ /** * Fired when a user stops speaking * @event VoiceConnection#speakingStop * @prop {String} userID The ID of the user that stopped speaking */ this.emit(packet.d.speaking ? "speakingStart" : "speakingStop", packet.d.user_id); break; } default: { this.emit("unknown", packet); break; } } }); this.ws.on("error", (err) => { this.emit("error", err); }); this.ws.on("close", (code, reason) => { var err = !code || code === 1000 ? null : new Error(code + ": " + reason); this.emit("warn", `Voice WS close ${code}: ${reason}`); if(this.connecting || this.ready) { var reconnecting = true; if(code === 4006) { reconnecting = false; } else if(code === 1000) { reconnecting = false; } this.disconnect(err, reconnecting); if(reconnecting) { setTimeout(() => this.connect(data), 500); } } }); } disconnect(error, reconnecting) { this.connecting = false; this.ready = false; this.speaking = false; this.timestamp = 0; this.sequence = 0; if(reconnecting) { this.pause(); } else { this.stopPlaying(); } if(this.heartbeatInterval) { clearInterval(this.heartbeatInterval); this.heartbeatInterval = null; } if(this.udpSocket) { try { this.udpSocket.close(); } catch(err) { if(err.message !== "Not running") { this.emit("error", err); } } this.udpSocket = null; } if(this.ws) { try { this.ws.close(); } catch(err) { this.emit("error", err); } this.ws = null; } if(reconnecting) { if(error) { this.emit("error", error); } } else { this.channelID = null; this.updateVoiceState(); /** * Fired when the voice connection disconnects * @event VoiceConnection#disconnect * @prop {Error?} err The error, if any */ this.emit("disconnect", error); } } heartbeat() { this.sendWS(OPCodes.HEARTBEAT, Date.now()); } /** * Play an audio or video resource. If playing from a non-opus resource, FFMPEG should be compiled with --enable-libopus for best performance. If playing from HTTPS, FFMPEG must be compiled with --enable-openssl * @arg {ReadableStream | String} resource The audio or video resource, either a ReadableStream, URL, or file path * @arg {Object} [options] Music options * @arg {Boolean} [options.inlineVolume=false] Whether to enable on-the-fly volume changing. Note that enabling this leads to increased CPU usage * @arg {Number} [options.voiceDataTimeout=2000] Timeout when waiting for voice data (-1 for no timeout) * @arg {Array<String>} [options.inputArgs] Additional input parameters to pass to ffmpeg/avconv (before -i) * @arg {Array<String>} [options.encoderArgs] Additional encoder parameters to pass to ffmpeg/avconv (after -i) * @arg {String} [options.format] The format of the resource. If null, FFmpeg will attempt to guess and play the format. Available options: "dca", "ogg", "webm", "pcm", null * @arg {Number} [options.frameDuration=20] The resource opus frame duration (required for DCA/Ogg) * @arg {Number} [options.frameSize=2880] The resource opus frame size * @arg {Number} [options.sampleRate=48000] The resource audio sampling rate */ play(source, options) { if(this.shared) { throw new Error("Cannot play stream on shared voice connection"); } if(!this.ready) { throw new Error("Not ready yet"); } options = options || {}; options.format = options.format || null; options.voiceDataTimeout = !isNaN(options.voiceDataTimeout) ? options.voiceDataTimeout : 2000; options.inlineVolume = !!options.inlineVolume; options.inputArgs = options.inputArgs || []; options.encoderArgs = options.encoderArgs || []; options.samplingRate = options.samplingRate || this.samplingRate; options.frameDuration = options.frameDuration || this.frameDuration; options.frameSize = options.frameSize || options.samplingRate * options.frameDuration / 1000; options.pcmSize = options.pcmSize || options.frameSize * 2 * this.channels; if(!this.piper.encode(source, options)) { this.emit("error", new Error("Unable to encode source")); return; } this.ended = false; this.current = { startTime: 0, // later playTime: 0, pausedTimestamp: 0, pausedTime: 0, bufferingTicks: 0, options: options, timeout: null, buffer: null }; this.playing = true; /** * Fired when the voice connection starts playing a stream * @event SharedStream#start */ this.emit("start"); this._send(); } _send() { if(!this.piper.encoding && this.piper.dataPacketCount === 0) { return this.stopPlaying(); } this.timestamp += this.current.options.frameSize; if(this.timestamp >= 4294967295) { this.timestamp -= 4294967295; } if(++this.sequence >= 65536) { this.sequence -= 65536; } if((this.current.buffer = this.piper.getDataPacket())) { if(this.current.startTime === 0) { this.current.startTime = Date.now(); } if(this.current.bufferingTicks > 0) { this.current.bufferingTicks = 0; this.setSpeaking(true); } } else if(this.current.options.voiceDataTimeout === -1 || this.current.bufferingTicks < this.current.options.voiceDataTimeout / this.current.options.frameDuration) { // wait for data if(++this.current.bufferingTicks <= 0) { this.setSpeaking(false); } this.current.pausedTime += 4 * this.current.options.frameDuration; this.timestamp += 3 * this.current.options.frameSize; if(this.timestamp >= 4294967295) { this.timestamp -= 4294967295; } this.current.timeout = setTimeout(this._send, 4 * this.current.options.frameDuration); return; } else { return this.stopPlaying(); } this._sendPacket(this._createPacket(this.current.buffer)); this.current.playTime += this.current.options.frameDuration; this.current.timeout = setTimeout(this._send, this.current.startTime + this.current.pausedTime + this.current.playTime - Date.now()); } /** * Stop the bot from sending audio */ stopPlaying() { if(this.ended) { return; } this.ended = true; if(this.current && this.current.timeout) { clearTimeout(this.current.timeout); this.current.timeout = null; } this.current = null; if(this.piper) { this.piper.stop(); this.piper.resetPackets(); } if(this.secret) { for(var i = 0; i < 5; i++) { this.timestamp += this.frameSize; if(this.timestamp >= 4294967295) { this.timestamp -= 4294967295; } if(++this.sequence >= 65536) { this.sequence -= 65536; } this._sendPacket(this._createPacket(new Buffer([0xF8, 0xFF, 0xFE]))); } } this.setSpeaking(this.playing = false); /** * Fired when the voice connection finishes playing a stream * @event VoiceConnection#end */ this.emit("end"); } _createPacket(_buffer) { this.packetBuffer.writeUIntBE(this.sequence, 2, 2); this.packetBuffer.writeUIntBE(this.timestamp, 4, 4); this.packetBuffer.copy(this.nonce, 0, 0, 12); var len = _buffer.length; if(!NaCl) { Sodium.crypto_secretbox_easy(this.packetBuffer.slice(12), _buffer, this.nonce, this.secret); len += Sodium.crypto_secretbox_MACBYTES; } else { var buffer = NaCl.secretbox(_buffer, this.nonce, this.secret); len += NaCl.lowlevel.crypto_secretbox_BOXZEROBYTES; this.packetBuffer.fill(0, 12, 12 + len); for (var i = 0; i < len; ++i) { this.packetBuffer[12 + i] = buffer[i]; } } return this.packetBuffer.slice(0, 12 + len); } _sendPacket(packet) { try { this.udpSocket.send(packet, 0, packet.length, this.udpPort, this.udpIP); } catch(e) { if(this.udpSocket) { this.emit("error", e); } } } /** * Generate a receive stream for the voice connection. * @arg {String} [type="pcm"] The desired vocie data type, either "opus" or "pcm" * @returns {VoiceDataStream} */ receive(type) { if(type === "pcm") { if(!this.receiveStreamPCM) { this.receiveStreamPCM = new VoiceDataStream(type); if(!this.receiveStreamOpus) { this.registerReceiveEventHandler(); } } } else if(type === "opus") { if(!this.receiveStreamOpus) { this.receiveStreamOpus = new VoiceDataStream(type); if(!this.receiveStreamPCM) { this.registerReceiveEventHandler(); } } } else { throw new Error(`Unsupported voice data type: ${type}`); } return type === "pcm" ? this.receiveStreamPCM : this.receiveStreamOpus; } registerReceiveEventHandler() { this.udpSocket.on("message", (msg) => { var nonce = new Buffer(24); nonce.fill(0); msg.copy(nonce, 0, 0, 12); var data; if(!NaCl) { data = new Buffer(msg.length - 12 - Sodium.crypto_secretbox_MACBYTES); Sodium.crypto_secretbox_open_easy(data, msg.slice(12), this.nonce, this.secret); } else { if(!(data = NaCl.secretbox.open(msg.slice(12), nonce, this.secret))) { /** * Fired to warn of something weird but non-breaking happening * @event VoiceConnection#warn * @prop {String} message The warning message */ this.emit("warn", "Failed to decrypt received packet"); return; } } if(data[0] === 0xBE && data[1] === 0xDE) { // RFC5285 Section 4.2: One-Byte Header var rtpHeaderExtensionLength = data[2] << 8 | data[3]; var index = 4; var byte; for(let i = 0; i < rtpHeaderExtensionLength; ++i) { byte = data[index]; ++index; let l = (byte & 0b1111) + 1; index += l; while(data[index] == 0) { ++index; } } data = data.slice(index); } // Have not received a RFC5285 Section 4.3: Two-Byte Header yet, so that is unimplemented for now if(this.receiveStreamOpus) { /** * Fired when a voice data packet is received * @event VoiceDataStream#data * @prop {Buffer} data The voice data * @prop {String} userID The user who sent the voice packet * @prop {Number} timestamp The intended timestamp of the packet * @prop {Number} sequence The intended sequence number of the packet */ this.receiveStreamOpus.emit("data", data, this.ssrcUserMap[nonce.readUIntBE(8, 4)], nonce.readUIntBE(4, 4), nonce.readUIntBE(2, 2)); } if(this.receiveStreamPCM) { data = this.opus.decode(data, this.frameSize); if(!data) { return this.emit("warn", "Failed to decode received packet"); } this.receiveStreamPCM.emit("data", data, this.ssrcUserMap[nonce.readUIntBE(8, 4)], nonce.readUIntBE(4, 4), nonce.readUIntBE(2, 2)); } }); } setSpeaking(value) { if((value = !!value) != this.speaking) { this.speaking = value; this.sendWS(OPCodes.SPEAKING, { speaking: value, delay: 0 }); } } /** * Switch the voice channel the bot is in. The channel to switch to must be in the same guild as the current voice channel * @arg {String} channelID The ID of the voice channel */ switchChannel(channelID, reactive) { if(this.channelID === channelID) { return; } this.channelID = channelID; if(!reactive) { this.updateVoiceState(); } } /** * Update the bot's voice state * @arg {Boolean} selfMute Whether the bot muted itself or not (audio sending is unaffected) * @arg {Boolean} selfDeaf Whether the bot deafened itself or not (audio receiving is unaffected) */ updateVoiceState(selfMute, selfDeaf) { if(this.shard.sendWS) { this.shard.sendWS(Constants.GatewayOPCodes.VOICE_STATE_UPDATE, { guild_id: this.id === "call" ? null : this.id, channel_id: this.channelID || null, self_mute: !!selfMute, self_deaf: !!selfDeaf }); } } sendWS(op, data) { if(this.ws && this.ws.readyState === WebSocket.OPEN) { data = JSON.stringify({op: op, d: data}); this.ws.send(data); this.emit("debug", data); } } get volume() { return this.piper.volumeLevel; } /** * Modify the output volume of the current stream (if inlineVolume is enabled for the current stream) * @arg {Number} [volume=1.0] The desired volume. 0.0 is 0%, 1.0 is 100%, 2.0 is 200%, etc. It is not recommended to go above 2.0 */ setVolume(volume) { this.piper.setVolume(volume); } /** * Pause sending audio (if playing) */ pause() { this.paused = true; this.setSpeaking(false); if(this.current) { if(!this.current.pausedTimestamp) { this.current.pausedTimestamp = Date.now(); } if(this.current.timeout) { clearTimeout(this.current.timeout); this.current.timeout = null; } } } /** * Resume sending audio (if paused) */ resume() { this.paused = false; this.setSpeaking(true); if(this.current) { if(this.current.pausedTimestamp) { this.current.pausedTime += Date.now() - this.current.pausedTimestamp; this.current.pausedTimestamp = 0; } this._send(); } } toJSON() { var base = {}; for(var key in this) { if(this.hasOwnProperty(key) && !key.startsWith("_") && !key.endsWith("Interval") && !key.endsWith("Timeout") && !~["nonce", "packetBuffer", "piper", "shard", "udpSocket", "ws"].indexOf(key)) { if(!this[key]) { base[key] = this[key]; } else if(this[key] instanceof Set) { base[key] = Array.from(this[key]); } else if(this[key] instanceof Map) { base[key] = Array.from(this[key].values()); } else if(typeof this[key].toJSON === "function") { base[key] = this[key].toJSON(); } else { base[key] = this[key]; } } } if(base.current && base.current.timeout) { delete base.current.timeout; } return base; } } VoiceConnection._converterCommand = converterCommand; module.exports = VoiceConnection;
Remove missing converter error from VoiceConnection constructor I mean, Piper already throws a fit if play() is called without FFmpeg/avconv
lib/voice/VoiceConnection.js
Remove missing converter error from VoiceConnection constructor
<ide><path>ib/voice/VoiceConnection.js <ide> converterCommand.cmd = tenative; <ide> return; <ide> } <del> throw new Error("Neither ffmpeg nor avconv was found. Make sure you installed either one, and check that it is in your PATH"); <ide> }; <ide> <ide> /**
Java
apache-2.0
1e8a7782189cfc119469b58303ee3394f8c47b6e
0
matrix-org/matrix-android-console,matrix-org/matrix-android-console
/* * Copyright 2014 OpenMarket Ltd * * 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.matrix.console.activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.data.MyUser; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.ContentResponse; import org.matrix.androidsdk.util.ContentManager; import org.matrix.androidsdk.util.ImageUtils; import org.matrix.console.Matrix; import org.matrix.console.MyPresenceManager; import org.matrix.console.R; import org.matrix.console.fragments.AccountsSelectionDialogFragment; import org.matrix.console.gcm.GcmRegistrationManager; import org.matrix.console.util.ResourceUtils; import org.matrix.console.util.UIUtils; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutionException; public class SettingsActivity extends MXCActionBarActivity { private static final String LOG_TAG = "SettingsActivity"; private static final int REQUEST_IMAGE = 0; // stored the updated thumbnails URI by session private static HashMap<String, Uri> mTmpThumbnailUriByMatrixId = new HashMap<String, Uri>(); // linear layout by session // each profile has a dedicated session. private HashMap<String, LinearLayout> mLinearLayoutByMatrixId = new HashMap<String, LinearLayout>(); private static String mUpdatingSessionId = null; private MXMediasCache mMediasCache; void refreshProfileThumbnail(MXSession session, LinearLayout baseLayout) { ImageView avatarView = (ImageView) baseLayout.findViewById(R.id.imageView_avatar); Uri newAvatarUri = mTmpThumbnailUriByMatrixId.get(session.getCredentials().userId); String avatarUrl = session.getMyUser().getAvatarUrl(); if (null != newAvatarUri) { avatarView.setImageURI(newAvatarUri); } else if (avatarUrl == null) { avatarView.setImageResource(R.drawable.ic_contact_picture_holo_light); } else { int size = getResources().getDimensionPixelSize(R.dimen.profile_avatar_size); mMediasCache.loadAvatarThumbnail(session.getHomeserverConfig(), avatarView, avatarUrl, size); } } /** * Return the application cache size as formatted string. * @return the application cache size as formatted string. */ private String computeApplicationCacheSize() { long size = 0; size += mMediasCache.cacheSize(); for(MXSession session : Matrix.getMXSessions(SettingsActivity.this)) { if (session.isAlive()) { size += session.getDataHandler().getStore().diskUsage(); } } return android.text.format.Formatter.formatFileSize(SettingsActivity.this, size); } private void launchNotificationsActivity() { // one session if (Matrix.getMXSessions(this).size() == 1) { Intent intent = new Intent(SettingsActivity.this, NotificationSettingsActivity.class); intent.putExtra(NotificationSettingsActivity.EXTRA_MATRIX_ID, Matrix.getInstance(this).getDefaultSession().getMyUserId()); SettingsActivity.this.startActivity(intent); } else { // select the current session FragmentManager fm = getSupportFragmentManager(); AccountsSelectionDialogFragment fragment = (AccountsSelectionDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } fragment = AccountsSelectionDialogFragment.newInstance(Matrix.getMXSessions(getApplicationContext())); fragment.setListener(new AccountsSelectionDialogFragment.AccountsListener() { @Override public void onSelected(final MXSession session) { Intent intent = new Intent(SettingsActivity.this, NotificationSettingsActivity.class); intent.putExtra(NotificationSettingsActivity.EXTRA_MATRIX_ID, session.getMyUserId()); SettingsActivity.this.startActivity(intent); } }); fragment.show(fm, TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG); } } @Override protected void onCreate(Bundle savedInstanceState) { if (CommonActivityUtils.shouldRestartApp()) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); mMediasCache = Matrix.getInstance(this).getMediasCache(); // add any known session LinearLayout globalLayout = (LinearLayout)findViewById(R.id.settings_layout); TextView profileHeader = (TextView)findViewById(R.id.settings_profile_information_header); int pos = globalLayout.indexOfChild(profileHeader); for(MXSession session : Matrix.getMXSessions(this)) { final MXSession fSession = session; LinearLayout profileLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.account_section_settings, null); mLinearLayoutByMatrixId.put(session.getCredentials().userId, profileLayout); pos++; globalLayout.addView(profileLayout, pos); refreshProfileThumbnail(session, profileLayout); ImageView avatarView = (ImageView)profileLayout.findViewById(R.id.imageView_avatar); avatarView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mUpdatingSessionId = fSession.getCredentials().userId; Intent fileIntent = new Intent(Intent.ACTION_PICK); fileIntent.setType("image/*"); startActivityForResult(fileIntent, REQUEST_IMAGE); } catch (Exception e) { Toast.makeText(SettingsActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } }); MyUser myUser = session.getMyUser(); TextView matrixIdTextView = (TextView) profileLayout.findViewById(R.id.textView_matrix_id); matrixIdTextView.setText(myUser.user_id); final Button saveButton = (Button) profileLayout.findViewById(R.id.button_save); EditText displayNameEditText = (EditText) profileLayout.findViewById(R.id.editText_displayName); displayNameEditText.setText(myUser.displayname); displayNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateSaveButton(saveButton); } @Override public void afterTextChanged(Editable s) { } }); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveChanges(fSession); } }); } // Config information TextView consoleVersionTextView = (TextView) findViewById(R.id.textView_matrixConsoleVersion); consoleVersionTextView.setText(getString(R.string.settings_config_console_version, Matrix.getInstance(this).getVersion(false))); TextView sdkVersionTextView = (TextView) findViewById(R.id.textView_matrixSDKVersion); sdkVersionTextView.setText(getString(R.string.settings_config_sdk_version, Matrix.getInstance(this).getDefaultSession().getVersion(false))); TextView buildNumberTextView = (TextView) findViewById(R.id.textView_matrixBuildNumber); buildNumberTextView.setText(getString(R.string.settings_config_build_number, "")); TextView userIdTextView = (TextView) findViewById(R.id.textView_configUsers); String config = ""; int sessionIndex = 1; Collection<MXSession> sessions = Matrix.getMXSessions(this); for(MXSession session : sessions) { if (sessions.size() > 1) { config += "\nAccount " + sessionIndex + " : \n"; sessionIndex++; } config += String.format( getString(R.string.settings_config_home_server), session.getHomeserverConfig().getHomeserverUri().toString() ); config += "\n"; config += String.format(getString(R.string.settings_config_user_id), session.getMyUserId()); if (sessions.size() > 1) { config += "\n"; } } userIdTextView.setText(config); // room settings final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); listenBoxUpdate(preferences, R.id.checkbox_useGcm, getString(R.string.settings_key_use_google_cloud_messaging), true); listenBoxUpdate(preferences, R.id.checkbox_displayAllEvents, getString(R.string.settings_key_display_all_events), false); listenBoxUpdate(preferences, R.id.checkbox_hideUnsupportedEvenst, getString(R.string.settings_key_hide_unsupported_events), true); listenBoxUpdate(preferences, R.id.checkbox_sortByLastSeen, getString(R.string.settings_key_sort_by_last_seen), true); listenBoxUpdate(preferences, R.id.checkbox_displayLeftMembers, getString(R.string.settings_key_display_left_members), false); listenBoxUpdate(preferences, R.id.checkbox_displayPublicRooms, getString(R.string.settings_key_display_public_rooms_recents), true); listenBoxUpdate(preferences, R.id.checkbox_rageshake, getString(R.string.settings_key_use_rage_shake), true); final Button clearCacheButton = (Button) findViewById(R.id.button_clear_cache); clearCacheButton.setText(getString(R.string.clear_cache) + " (" + computeApplicationCacheSize() + ")"); clearCacheButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Matrix.getInstance(SettingsActivity.this).reloadSessions(SettingsActivity.this); } }); final Button notificationsRuleButton = (Button) findViewById(R.id.button_notifications_rule); notificationsRuleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchNotificationsActivity(); } }); final GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this).getSharedGcmRegistrationManager(); refreshGCMEntries(); managePedingGCMregistration(); } /** * A GCM registration could be in progress. * So disable the UI until the registration is done. */ private void managePedingGCMregistration() { GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(SettingsActivity.this).getSharedGcmRegistrationManager(); if (gcmRegistrationManager.isRegistrating()) { final View gcmLayout = findViewById(R.id.gcm_layout); gcmLayout.setEnabled(false); gcmLayout.setAlpha(0.25f); final GcmRegistrationManager.GcmSessionRegistration listener = new GcmRegistrationManager.GcmSessionRegistration() { @Override public void onSessionRegistred() { SettingsActivity.this.runOnUiThread(new Runnable() { @Override public void run() { gcmLayout.setEnabled(true); gcmLayout.setAlpha(1.0f); refreshGCMEntries(); CommonActivityUtils.onGcmUpdate(SettingsActivity.this); } }); } @Override public void onSessionRegistrationFailed() { onSessionRegistred(); } @Override public void onSessionUnregistred() { onSessionRegistred(); } @Override public void onSessionUnregistrationFailed() { onSessionRegistred(); } }; gcmRegistrationManager.addSessionsRegistrationListener(listener); } } private void listenBoxUpdate(final SharedPreferences preferences, final int boxId, final String preferenceKey, boolean defaultValue) { final CheckBox checkBox = (CheckBox) findViewById(boxId); checkBox.setChecked(preferences.getBoolean(preferenceKey, defaultValue)); checkBox.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(preferenceKey, checkBox.isChecked()); editor.commit(); // GCM case if (boxId == R.id.checkbox_useGcm) { final View gcmLayout = findViewById(R.id.gcm_layout); gcmLayout.setEnabled(false); gcmLayout.setAlpha(0.25f); GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(SettingsActivity.this).getSharedGcmRegistrationManager(); final GcmRegistrationManager.GcmSessionRegistration listener = new GcmRegistrationManager.GcmSessionRegistration() { @Override public void onSessionRegistred(){ SettingsActivity.this.runOnUiThread(new Runnable() { @Override public void run() { gcmLayout.setEnabled(true); gcmLayout.setAlpha(1.0f); refreshGCMEntries(); CommonActivityUtils.onGcmUpdate(SettingsActivity.this); } }); } @Override public void onSessionRegistrationFailed() { onSessionRegistred(); } @Override public void onSessionUnregistred() { onSessionRegistred(); } @Override public void onSessionUnregistrationFailed() { onSessionRegistred(); } }; if (checkBox.isChecked()) { gcmRegistrationManager.registerSessions(SettingsActivity.this, listener); } else { gcmRegistrationManager.unregisterSessions(listener); } } } } ); } private void refreshGCMEntries() { GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this).getSharedGcmRegistrationManager(); final CheckBox gcmBox = (CheckBox) findViewById(R.id.checkbox_useGcm); gcmBox.setChecked(gcmRegistrationManager.useGCM() && gcmRegistrationManager.is3rdPartyServerRegistred()); // check if the GCM registration has not been rejected. boolean gcmButEnabled = gcmRegistrationManager.useGCM() || gcmRegistrationManager.isGCMRegistred(); View parentView = (View)gcmBox.getParent(); parentView.setEnabled(gcmButEnabled); gcmBox.setEnabled(gcmButEnabled); parentView.setAlpha(gcmButEnabled ? 1.0f : 0.5f); } @Override protected void onResume() { super.onResume(); MyPresenceManager.advertiseAllOnline(); for(MXSession session : Matrix.getMXSessions(this)) { final MyUser myUser = session.getMyUser(); final MXSession fSession = session; final LinearLayout linearLayout = mLinearLayoutByMatrixId.get(fSession.getCredentials().userId); final View refreshingView = linearLayout.findViewById(R.id.profile_mask); refreshingView.setVisibility(View.VISIBLE); session.getProfileApiClient().displayname(myUser.user_id, new SimpleApiCallback<String>(this) { @Override public void onSuccess(String displayname) { if ((null != displayname) && !displayname.equals(myUser.displayname)) { myUser.displayname = displayname; EditText displayNameEditText = (EditText) linearLayout.findViewById(R.id.editText_displayName); displayNameEditText.setText(myUser.displayname); } if (fSession.isAlive()) { fSession.getProfileApiClient().avatarUrl(myUser.user_id, new SimpleApiCallback<String>(this) { @Override public void onSuccess(String avatarUrl) { if ((null != avatarUrl) && !avatarUrl.equals(myUser.getAvatarUrl())) { mTmpThumbnailUriByMatrixId.remove(fSession.getCredentials().userId); myUser.setAvatarUrl(avatarUrl); refreshProfileThumbnail(fSession, linearLayout); } refreshingView.setVisibility(View.GONE); } }); } } }); } // refresh the cache size Button clearCacheButton = (Button) findViewById(R.id.button_clear_cache); clearCacheButton.setText(getString(R.string.clear_cache) + " (" + computeApplicationCacheSize() + ")"); refreshGCMEntries(); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE) { if (resultCode == RESULT_OK) { this.runOnUiThread(new Runnable() { @Override public void run() { final LinearLayout linearLayout = mLinearLayoutByMatrixId.get(mUpdatingSessionId); // sanity checks if (null != linearLayout) { ImageView avatarView = (ImageView) linearLayout.findViewById(R.id.imageView_avatar); Uri imageUri = data.getData(); Bitmap thumbnailBitmap = null; Uri scaledImageUri = data.getData(); try { ResourceUtils.Resource resource = ResourceUtils.openResource(SettingsActivity.this, imageUri); // with jpg files // check exif parameter and reduce image size if ("image/jpg".equals(resource.mimeType) || "image/jpeg".equals(resource.mimeType)) { InputStream stream = resource.contentStream; int rotationAngle = ImageUtils .getRotationAngleForBitmap(SettingsActivity.this, imageUri); String mediaUrl = ImageUtils.scaleAndRotateImage(SettingsActivity.this, stream, resource.mimeType, 1024, rotationAngle, SettingsActivity.this.mMediasCache); scaledImageUri = Uri.parse(mediaUrl); } else { ContentResolver resolver = getContentResolver(); List uriPath = imageUri.getPathSegments(); long imageId = -1; String lastSegment = (String) uriPath.get(uriPath.size() - 1); // > Kitkat if (lastSegment.startsWith("image:")) { lastSegment = lastSegment.substring("image:".length()); } imageId = Long.parseLong(lastSegment); thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null); } resource.contentStream.close(); } catch (Exception e) { Log.e(LOG_TAG, "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage()); } if (null != thumbnailBitmap) { avatarView.setImageBitmap(thumbnailBitmap); } else { avatarView.setImageURI(scaledImageUri); } mTmpThumbnailUriByMatrixId.put(mUpdatingSessionId, scaledImageUri); final Button saveButton = (Button) linearLayout.findViewById(R.id.button_save); saveButton.setEnabled(true); // Enable the save button if it wasn't already } } }); } mUpdatingSessionId = null; } } @Override public void onBackPressed() { if (areChanges()) { // The user is trying to leave with unsaved changes. Warn about that new AlertDialog.Builder(this) .setMessage(R.string.message_unsaved_changes) .setPositiveButton(R.string.stay, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setNegativeButton(R.string.leave, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SettingsActivity.super.onBackPressed(); } }) .create() .show(); } else { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** * Return the edited username for a dedicated session. * @param session the session * @return the edited text */ private String getEditedUserName(final MXSession session) { LinearLayout linearLayout = mLinearLayoutByMatrixId.get(session.getCredentials().userId); EditText displayNameEditText = (EditText) linearLayout.findViewById(R.id.editText_displayName); if (!TextUtils.isEmpty(displayNameEditText.getText())) { // trim the text to avoid trailing /n after a c+p return displayNameEditText.getText().toString().trim(); } return ""; } private void saveChanges(final MXSession session) { LinearLayout linearLayout = mLinearLayoutByMatrixId.get(session.getCredentials().userId); final String nameFromForm = getEditedUserName(session); final ApiCallback<Void> changeCallback = UIUtils.buildOnChangeCallback(this); final MyUser myUser = session.getMyUser(); final Button saveButton = (Button) linearLayout.findViewById(R.id.button_save); // disable the save button to avoid unexpected behaviour saveButton.setEnabled(false); if (UIUtils.hasFieldChanged(myUser.displayname, nameFromForm)) { myUser.updateDisplayName(nameFromForm, new SimpleApiCallback<Void>(changeCallback) { @Override public void onSuccess(Void info) { super.onSuccess(info); updateSaveButton(saveButton); } }); } Uri newAvatarUri = mTmpThumbnailUriByMatrixId.get(session.getCredentials().userId); if (newAvatarUri != null) { Log.d(LOG_TAG, "Selected image to upload: " + newAvatarUri); ResourceUtils.Resource resource = ResourceUtils.openResource(this, newAvatarUri); if (resource == null) { Toast.makeText(SettingsActivity.this, getString(R.string.settings_failed_to_upload_avatar), Toast.LENGTH_LONG).show(); return; } final ProgressDialog progressDialog = ProgressDialog.show(this, null, getString(R.string.message_uploading), true); session.getContentManager().uploadContent(resource.contentStream, null, resource.mimeType, null, new ContentManager.UploadCallback() { @Override public void onUploadStart(String uploadId) { } @Override public void onUploadProgress(String anUploadId, int percentageProgress) { progressDialog.setMessage(getString(R.string.message_uploading) + " (" + percentageProgress + "%)"); } @Override public void onUploadComplete(String anUploadId, ContentResponse uploadResponse, final int serverResponseCode, String serverErrorMessage) { if (uploadResponse == null) { Toast.makeText(SettingsActivity.this, (null != serverErrorMessage) ? serverErrorMessage : getString(R.string.settings_failed_to_upload_avatar), Toast.LENGTH_LONG).show(); } else { Log.d(LOG_TAG, "Uploaded to " + uploadResponse.contentUri); myUser.updateAvatarUrl(uploadResponse.contentUri, new SimpleApiCallback<Void>(changeCallback) { @Override public void onSuccess(Void info) { super.onSuccess(info); // Reset this because its being set is how we know there's been a change mTmpThumbnailUriByMatrixId.remove(session.getCredentials().userId); updateSaveButton(saveButton); } }); } progressDialog.dismiss(); } }); } } private void updateSaveButton(final Button button) { runOnUiThread(new Runnable() { @Override public void run() { button.setEnabled(areChanges()); } }); } private boolean areChanges() { if (mTmpThumbnailUriByMatrixId.size() != 0) { return true; } Boolean res = false; for(MXSession session : Matrix.getMXSessions(this)) { res |= UIUtils.hasFieldChanged(session.getMyUser().displayname, getEditedUserName(session)); } return res; } }
console/src/main/java/org/matrix/console/activity/SettingsActivity.java
/* * Copyright 2014 OpenMarket Ltd * * 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.matrix.console.activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.data.MyUser; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.ContentResponse; import org.matrix.androidsdk.util.ContentManager; import org.matrix.androidsdk.util.ImageUtils; import org.matrix.console.Matrix; import org.matrix.console.MyPresenceManager; import org.matrix.console.R; import org.matrix.console.fragments.AccountsSelectionDialogFragment; import org.matrix.console.gcm.GcmRegistrationManager; import org.matrix.console.util.ResourceUtils; import org.matrix.console.util.UIUtils; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.List; public class SettingsActivity extends MXCActionBarActivity { private static final String LOG_TAG = "SettingsActivity"; private static final int REQUEST_IMAGE = 0; // stored the updated thumbnails URI by session private static HashMap<String, Uri> mTmpThumbnailUriByMatrixId = new HashMap<String, Uri>(); // linear layout by session // each profile has a dedicated session. private HashMap<String, LinearLayout> mLinearLayoutByMatrixId = new HashMap<String, LinearLayout>(); private static String mUpdatingSessionId = null; private MXMediasCache mMediasCache; void refreshProfileThumbnail(MXSession session, LinearLayout baseLayout) { ImageView avatarView = (ImageView) baseLayout.findViewById(R.id.imageView_avatar); Uri newAvatarUri = mTmpThumbnailUriByMatrixId.get(session.getCredentials().userId); String avatarUrl = session.getMyUser().getAvatarUrl(); if (null != newAvatarUri) { avatarView.setImageURI(newAvatarUri); } else if (avatarUrl == null) { avatarView.setImageResource(R.drawable.ic_contact_picture_holo_light); } else { int size = getResources().getDimensionPixelSize(R.dimen.profile_avatar_size); mMediasCache.loadAvatarThumbnail(session.getHomeserverConfig(), avatarView, avatarUrl, size); } } /** * Return the application cache size as formatted string. * @return the application cache size as formatted string. */ private String computeApplicationCacheSize() { long size = 0; size += mMediasCache.cacheSize(); for(MXSession session : Matrix.getMXSessions(SettingsActivity.this)) { if (session.isAlive()) { size += session.getDataHandler().getStore().diskUsage(); } } return android.text.format.Formatter.formatFileSize(SettingsActivity.this, size); } private void launchNotificationsActivity() { // one session if (Matrix.getMXSessions(this).size() == 1) { Intent intent = new Intent(SettingsActivity.this, NotificationSettingsActivity.class); intent.putExtra(NotificationSettingsActivity.EXTRA_MATRIX_ID, Matrix.getInstance(this).getDefaultSession().getMyUserId()); SettingsActivity.this.startActivity(intent); } else { // select the current session FragmentManager fm = getSupportFragmentManager(); AccountsSelectionDialogFragment fragment = (AccountsSelectionDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } fragment = AccountsSelectionDialogFragment.newInstance(Matrix.getMXSessions(getApplicationContext())); fragment.setListener(new AccountsSelectionDialogFragment.AccountsListener() { @Override public void onSelected(final MXSession session) { Intent intent = new Intent(SettingsActivity.this, NotificationSettingsActivity.class); intent.putExtra(NotificationSettingsActivity.EXTRA_MATRIX_ID, session.getMyUserId()); SettingsActivity.this.startActivity(intent); } }); fragment.show(fm, TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG); } } @Override protected void onCreate(Bundle savedInstanceState) { if (CommonActivityUtils.shouldRestartApp()) { Log.e(LOG_TAG, "Restart the application."); CommonActivityUtils.restartApp(this); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); mMediasCache = Matrix.getInstance(this).getMediasCache(); // add any known session LinearLayout globalLayout = (LinearLayout)findViewById(R.id.settings_layout); TextView profileHeader = (TextView)findViewById(R.id.settings_profile_information_header); int pos = globalLayout.indexOfChild(profileHeader); for(MXSession session : Matrix.getMXSessions(this)) { final MXSession fSession = session; LinearLayout profileLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.account_section_settings, null); mLinearLayoutByMatrixId.put(session.getCredentials().userId, profileLayout); pos++; globalLayout.addView(profileLayout, pos); refreshProfileThumbnail(session, profileLayout); ImageView avatarView = (ImageView)profileLayout.findViewById(R.id.imageView_avatar); avatarView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mUpdatingSessionId = fSession.getCredentials().userId; Intent fileIntent = new Intent(Intent.ACTION_PICK); fileIntent.setType("image/*"); startActivityForResult(fileIntent, REQUEST_IMAGE); } }); MyUser myUser = session.getMyUser(); TextView matrixIdTextView = (TextView) profileLayout.findViewById(R.id.textView_matrix_id); matrixIdTextView.setText(myUser.user_id); final Button saveButton = (Button) profileLayout.findViewById(R.id.button_save); EditText displayNameEditText = (EditText) profileLayout.findViewById(R.id.editText_displayName); displayNameEditText.setText(myUser.displayname); displayNameEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { updateSaveButton(saveButton); } @Override public void afterTextChanged(Editable s) { } }); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveChanges(fSession); } }); } // Config information TextView consoleVersionTextView = (TextView) findViewById(R.id.textView_matrixConsoleVersion); consoleVersionTextView.setText(getString(R.string.settings_config_console_version, Matrix.getInstance(this).getVersion(false))); TextView sdkVersionTextView = (TextView) findViewById(R.id.textView_matrixSDKVersion); sdkVersionTextView.setText(getString(R.string.settings_config_sdk_version, Matrix.getInstance(this).getDefaultSession().getVersion(false))); TextView buildNumberTextView = (TextView) findViewById(R.id.textView_matrixBuildNumber); buildNumberTextView.setText(getString(R.string.settings_config_build_number, "")); TextView userIdTextView = (TextView) findViewById(R.id.textView_configUsers); String config = ""; int sessionIndex = 1; Collection<MXSession> sessions = Matrix.getMXSessions(this); for(MXSession session : sessions) { if (sessions.size() > 1) { config += "\nAccount " + sessionIndex + " : \n"; sessionIndex++; } config += String.format( getString(R.string.settings_config_home_server), session.getHomeserverConfig().getHomeserverUri().toString() ); config += "\n"; config += String.format(getString(R.string.settings_config_user_id), session.getMyUserId()); if (sessions.size() > 1) { config += "\n"; } } userIdTextView.setText(config); // room settings final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); listenBoxUpdate(preferences, R.id.checkbox_useGcm, getString(R.string.settings_key_use_google_cloud_messaging), true); listenBoxUpdate(preferences, R.id.checkbox_displayAllEvents, getString(R.string.settings_key_display_all_events), false); listenBoxUpdate(preferences, R.id.checkbox_hideUnsupportedEvenst, getString(R.string.settings_key_hide_unsupported_events), true); listenBoxUpdate(preferences, R.id.checkbox_sortByLastSeen, getString(R.string.settings_key_sort_by_last_seen), true); listenBoxUpdate(preferences, R.id.checkbox_displayLeftMembers, getString(R.string.settings_key_display_left_members), false); listenBoxUpdate(preferences, R.id.checkbox_displayPublicRooms, getString(R.string.settings_key_display_public_rooms_recents), true); listenBoxUpdate(preferences, R.id.checkbox_rageshake, getString(R.string.settings_key_use_rage_shake), true); final Button clearCacheButton = (Button) findViewById(R.id.button_clear_cache); clearCacheButton.setText(getString(R.string.clear_cache) + " (" + computeApplicationCacheSize() + ")"); clearCacheButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Matrix.getInstance(SettingsActivity.this).reloadSessions(SettingsActivity.this); } }); final Button notificationsRuleButton = (Button) findViewById(R.id.button_notifications_rule); notificationsRuleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchNotificationsActivity(); } }); final GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this).getSharedGcmRegistrationManager(); refreshGCMEntries(); managePedingGCMregistration(); } /** * A GCM registration could be in progress. * So disable the UI until the registration is done. */ private void managePedingGCMregistration() { GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(SettingsActivity.this).getSharedGcmRegistrationManager(); if (gcmRegistrationManager.isRegistrating()) { final View gcmLayout = findViewById(R.id.gcm_layout); gcmLayout.setEnabled(false); gcmLayout.setAlpha(0.25f); final GcmRegistrationManager.GcmSessionRegistration listener = new GcmRegistrationManager.GcmSessionRegistration() { @Override public void onSessionRegistred() { SettingsActivity.this.runOnUiThread(new Runnable() { @Override public void run() { gcmLayout.setEnabled(true); gcmLayout.setAlpha(1.0f); refreshGCMEntries(); CommonActivityUtils.onGcmUpdate(SettingsActivity.this); } }); } @Override public void onSessionRegistrationFailed() { onSessionRegistred(); } @Override public void onSessionUnregistred() { onSessionRegistred(); } @Override public void onSessionUnregistrationFailed() { onSessionRegistred(); } }; gcmRegistrationManager.addSessionsRegistrationListener(listener); } } private void listenBoxUpdate(final SharedPreferences preferences, final int boxId, final String preferenceKey, boolean defaultValue) { final CheckBox checkBox = (CheckBox) findViewById(boxId); checkBox.setChecked(preferences.getBoolean(preferenceKey, defaultValue)); checkBox.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(preferenceKey, checkBox.isChecked()); editor.commit(); // GCM case if (boxId == R.id.checkbox_useGcm) { final View gcmLayout = findViewById(R.id.gcm_layout); gcmLayout.setEnabled(false); gcmLayout.setAlpha(0.25f); GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(SettingsActivity.this).getSharedGcmRegistrationManager(); final GcmRegistrationManager.GcmSessionRegistration listener = new GcmRegistrationManager.GcmSessionRegistration() { @Override public void onSessionRegistred(){ SettingsActivity.this.runOnUiThread(new Runnable() { @Override public void run() { gcmLayout.setEnabled(true); gcmLayout.setAlpha(1.0f); refreshGCMEntries(); CommonActivityUtils.onGcmUpdate(SettingsActivity.this); } }); } @Override public void onSessionRegistrationFailed() { onSessionRegistred(); } @Override public void onSessionUnregistred() { onSessionRegistred(); } @Override public void onSessionUnregistrationFailed() { onSessionRegistred(); } }; if (checkBox.isChecked()) { gcmRegistrationManager.registerSessions(SettingsActivity.this, listener); } else { gcmRegistrationManager.unregisterSessions(listener); } } } } ); } private void refreshGCMEntries() { GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this).getSharedGcmRegistrationManager(); final CheckBox gcmBox = (CheckBox) findViewById(R.id.checkbox_useGcm); gcmBox.setChecked(gcmRegistrationManager.useGCM() && gcmRegistrationManager.is3rdPartyServerRegistred()); // check if the GCM registration has not been rejected. boolean gcmButEnabled = gcmRegistrationManager.useGCM() || gcmRegistrationManager.isGCMRegistred(); View parentView = (View)gcmBox.getParent(); parentView.setEnabled(gcmButEnabled); gcmBox.setEnabled(gcmButEnabled); parentView.setAlpha(gcmButEnabled ? 1.0f : 0.5f); } @Override protected void onResume() { super.onResume(); MyPresenceManager.advertiseAllOnline(); for(MXSession session : Matrix.getMXSessions(this)) { final MyUser myUser = session.getMyUser(); final MXSession fSession = session; final LinearLayout linearLayout = mLinearLayoutByMatrixId.get(fSession.getCredentials().userId); final View refreshingView = linearLayout.findViewById(R.id.profile_mask); refreshingView.setVisibility(View.VISIBLE); session.getProfileApiClient().displayname(myUser.user_id, new SimpleApiCallback<String>(this) { @Override public void onSuccess(String displayname) { if ((null != displayname) && !displayname.equals(myUser.displayname)) { myUser.displayname = displayname; EditText displayNameEditText = (EditText) linearLayout.findViewById(R.id.editText_displayName); displayNameEditText.setText(myUser.displayname); } if (fSession.isAlive()) { fSession.getProfileApiClient().avatarUrl(myUser.user_id, new SimpleApiCallback<String>(this) { @Override public void onSuccess(String avatarUrl) { if ((null != avatarUrl) && !avatarUrl.equals(myUser.getAvatarUrl())) { mTmpThumbnailUriByMatrixId.remove(fSession.getCredentials().userId); myUser.setAvatarUrl(avatarUrl); refreshProfileThumbnail(fSession, linearLayout); } refreshingView.setVisibility(View.GONE); } }); } } }); } // refresh the cache size Button clearCacheButton = (Button) findViewById(R.id.button_clear_cache); clearCacheButton.setText(getString(R.string.clear_cache) + " (" + computeApplicationCacheSize() + ")"); refreshGCMEntries(); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE) { if (resultCode == RESULT_OK) { this.runOnUiThread(new Runnable() { @Override public void run() { final LinearLayout linearLayout = mLinearLayoutByMatrixId.get(mUpdatingSessionId); // sanity checks if (null != linearLayout) { ImageView avatarView = (ImageView) linearLayout.findViewById(R.id.imageView_avatar); Uri imageUri = data.getData(); Bitmap thumbnailBitmap = null; Uri scaledImageUri = data.getData(); try { ResourceUtils.Resource resource = ResourceUtils.openResource(SettingsActivity.this, imageUri); // with jpg files // check exif parameter and reduce image size if ("image/jpg".equals(resource.mimeType) || "image/jpeg".equals(resource.mimeType)) { InputStream stream = resource.contentStream; int rotationAngle = ImageUtils .getRotationAngleForBitmap(SettingsActivity.this, imageUri); String mediaUrl = ImageUtils.scaleAndRotateImage(SettingsActivity.this, stream, resource.mimeType, 1024, rotationAngle, SettingsActivity.this.mMediasCache); scaledImageUri = Uri.parse(mediaUrl); } else { ContentResolver resolver = getContentResolver(); List uriPath = imageUri.getPathSegments(); long imageId = -1; String lastSegment = (String) uriPath.get(uriPath.size() - 1); // > Kitkat if (lastSegment.startsWith("image:")) { lastSegment = lastSegment.substring("image:".length()); } imageId = Long.parseLong(lastSegment); thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null); } resource.contentStream.close(); } catch (Exception e) { Log.e(LOG_TAG, "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage()); } if (null != thumbnailBitmap) { avatarView.setImageBitmap(thumbnailBitmap); } else { avatarView.setImageURI(scaledImageUri); } mTmpThumbnailUriByMatrixId.put(mUpdatingSessionId, scaledImageUri); final Button saveButton = (Button) linearLayout.findViewById(R.id.button_save); saveButton.setEnabled(true); // Enable the save button if it wasn't already } } }); } mUpdatingSessionId = null; } } @Override public void onBackPressed() { if (areChanges()) { // The user is trying to leave with unsaved changes. Warn about that new AlertDialog.Builder(this) .setMessage(R.string.message_unsaved_changes) .setPositiveButton(R.string.stay, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setNegativeButton(R.string.leave, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SettingsActivity.super.onBackPressed(); } }) .create() .show(); } else { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } /** * Return the edited username for a dedicated session. * @param session the session * @return the edited text */ private String getEditedUserName(final MXSession session) { LinearLayout linearLayout = mLinearLayoutByMatrixId.get(session.getCredentials().userId); EditText displayNameEditText = (EditText) linearLayout.findViewById(R.id.editText_displayName); if (!TextUtils.isEmpty(displayNameEditText.getText())) { // trim the text to avoid trailing /n after a c+p return displayNameEditText.getText().toString().trim(); } return ""; } private void saveChanges(final MXSession session) { LinearLayout linearLayout = mLinearLayoutByMatrixId.get(session.getCredentials().userId); final String nameFromForm = getEditedUserName(session); final ApiCallback<Void> changeCallback = UIUtils.buildOnChangeCallback(this); final MyUser myUser = session.getMyUser(); final Button saveButton = (Button) linearLayout.findViewById(R.id.button_save); // disable the save button to avoid unexpected behaviour saveButton.setEnabled(false); if (UIUtils.hasFieldChanged(myUser.displayname, nameFromForm)) { myUser.updateDisplayName(nameFromForm, new SimpleApiCallback<Void>(changeCallback) { @Override public void onSuccess(Void info) { super.onSuccess(info); updateSaveButton(saveButton); } }); } Uri newAvatarUri = mTmpThumbnailUriByMatrixId.get(session.getCredentials().userId); if (newAvatarUri != null) { Log.d(LOG_TAG, "Selected image to upload: " + newAvatarUri); ResourceUtils.Resource resource = ResourceUtils.openResource(this, newAvatarUri); if (resource == null) { Toast.makeText(SettingsActivity.this, getString(R.string.settings_failed_to_upload_avatar), Toast.LENGTH_LONG).show(); return; } final ProgressDialog progressDialog = ProgressDialog.show(this, null, getString(R.string.message_uploading), true); session.getContentManager().uploadContent(resource.contentStream, null, resource.mimeType, null, new ContentManager.UploadCallback() { @Override public void onUploadStart(String uploadId) { } @Override public void onUploadProgress(String anUploadId, int percentageProgress) { progressDialog.setMessage(getString(R.string.message_uploading) + " (" + percentageProgress + "%)"); } @Override public void onUploadComplete(String anUploadId, ContentResponse uploadResponse, final int serverResponseCode, String serverErrorMessage) { if (uploadResponse == null) { Toast.makeText(SettingsActivity.this, (null != serverErrorMessage) ? serverErrorMessage : getString(R.string.settings_failed_to_upload_avatar), Toast.LENGTH_LONG).show(); } else { Log.d(LOG_TAG, "Uploaded to " + uploadResponse.contentUri); myUser.updateAvatarUrl(uploadResponse.contentUri, new SimpleApiCallback<Void>(changeCallback) { @Override public void onSuccess(Void info) { super.onSuccess(info); // Reset this because its being set is how we know there's been a change mTmpThumbnailUriByMatrixId.remove(session.getCredentials().userId); updateSaveButton(saveButton); } }); } progressDialog.dismiss(); } }); } } private void updateSaveButton(final Button button) { runOnUiThread(new Runnable() { @Override public void run() { button.setEnabled(areChanges()); } }); } private boolean areChanges() { if (mTmpThumbnailUriByMatrixId.size() != 0) { return true; } Boolean res = false; for(MXSession session : Matrix.getMXSessions(this)) { res |= UIUtils.hasFieldChanged(session.getMyUser().displayname, getEditedUserName(session)); } return res; } }
Some devices don't support the medias pick.
console/src/main/java/org/matrix/console/activity/SettingsActivity.java
Some devices don't support the medias pick.
<ide><path>onsole/src/main/java/org/matrix/console/activity/SettingsActivity.java <ide> import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.List; <add>import java.util.concurrent.ExecutionException; <ide> <ide> public class SettingsActivity extends MXCActionBarActivity { <ide> <ide> avatarView.setOnClickListener(new View.OnClickListener() { <ide> @Override <ide> public void onClick(View v) { <del> mUpdatingSessionId = fSession.getCredentials().userId; <del> Intent fileIntent = new Intent(Intent.ACTION_PICK); <del> fileIntent.setType("image/*"); <del> startActivityForResult(fileIntent, REQUEST_IMAGE); <add> try { <add> mUpdatingSessionId = fSession.getCredentials().userId; <add> <add> Intent fileIntent = new Intent(Intent.ACTION_PICK); <add> fileIntent.setType("image/*"); <add> startActivityForResult(fileIntent, REQUEST_IMAGE); <add> } catch (Exception e) { <add> Toast.makeText(SettingsActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); <add> } <ide> } <ide> }); <ide>
Java
apache-2.0
59373d002860fe59893b33aaec7e14a88165c624
0
SlideKB/SlideBar
/** Copyright 2017 John Kester (Jack Kester) 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.github.slidekb.back; import java.util.ArrayList; import java.util.ServiceLoader; import java.util.concurrent.CountDownLatch; import com.github.slidekb.api.PlatformSpecific; import com.github.slidekb.api.PluginVersion; import com.github.slidekb.api.SlideBarPlugin; import com.github.slidekb.api.Slider; import com.github.slidekb.util.CurrentWorkingDirectoryClassLoader; import com.github.slidekb.util.OsHelper; import com.github.slidekb.util.SettingsHelper; public class PluginManager { private ArrayList<SlideBarPlugin> proci = new ArrayList<>(); private CountDownLatch pluginsLoaded; private ServiceLoader<SlideBarPlugin> loader; public PluginManager() { } /** * Adds plugins into the list and instances each. * * @return true if successful. */ protected boolean loadProcesses(int programVersion) { proci.clear(); pluginsLoaded = new CountDownLatch(1); loader = ServiceLoader.load(SlideBarPlugin.class, CurrentWorkingDirectoryClassLoader.getCurrentWorkingDirectoryClassLoader()); for (SlideBarPlugin currentImplementation : loader) { PluginVersion currentVersion = currentImplementation.getClass().getAnnotation(PluginVersion.class); if (currentVersion == null) { System.out.println("Found plugin " + currentImplementation.getClass().getCanonicalName() + " but it has no version annotation! Skipping."); continue; } else if (currentVersion.value() != programVersion) { System.out.println("Found plugin " + currentImplementation.getClass().getCanonicalName() + " but its version " + currentVersion.value() + " doesn't match program version " + programVersion + "! Skipping."); continue; } else { PlatformSpecific currentOsAnnotation = currentImplementation.getClass().getAnnotation(PlatformSpecific.class); if (currentOsAnnotation != null) { // Annotation present -> platform specific plugin if (currentOsAnnotation.value() == OsHelper.getOS()) { System.out.println("Loading platform dependant plugin " + currentImplementation.getClass().getCanonicalName() + " for platform " + OsHelper.getOS()); } else { continue; } } else { // No Annotation -> platform independent plugin System.out.println("Loading platform independant plugin " + currentImplementation.getClass().getCanonicalName()); } } int totalSliders = currentImplementation.numberOfSlidersRequired(); Slider usedSlider; for (int i = 0; i < totalSliders; i++) { String sliderID = SettingsHelper.getUsedSliderAtIndex(currentImplementation.getClass().getCanonicalName(), i); if (sliderID == null) { usedSlider = MainBack.getSliderManager().getDefaultSliderByIndex(i); } else { usedSlider = MainBack.getSliderManager().getSliderByID(sliderID); if (usedSlider == null) { usedSlider = MainBack.getSliderManager().getDefaultSliderByIndex(i); } } currentImplementation.setSlider(usedSlider, i); } currentImplementation.setup(); proci.add(currentImplementation); } pluginsLoaded.countDown(); return true; } public void waitUntilProcessesLoaded() throws InterruptedException { pluginsLoaded.await(); } public ArrayList<SlideBarPlugin> getProci() { return proci; } protected void removeProci(boolean RemoveAll) { if (RemoveAll) { proci.clear(); } } }
src/main/java/com/github/slidekb/back/PluginManager.java
/** Copyright 2017 John Kester (Jack Kester) 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.github.slidekb.back; import java.util.ArrayList; import java.util.ServiceLoader; import java.util.concurrent.CountDownLatch; import com.github.slidekb.api.PlatformSpecific; import com.github.slidekb.api.PluginVersion; import com.github.slidekb.api.SlideBarPlugin; import com.github.slidekb.api.Slider; import com.github.slidekb.util.CurrentWorkingDirectoryClassLoader; import com.github.slidekb.util.OsHelper; import com.github.slidekb.util.SettingsHelper; public class PluginManager { private ArrayList<SlideBarPlugin> proci = new ArrayList<>(); private CountDownLatch pluginsLoaded; private ServiceLoader<SlideBarPlugin> loader; public PluginManager() { } /** * Adds plugins into the list and instances each. * * @return true if successful. */ protected boolean loadProcesses(int programVersion) { proci.clear(); pluginsLoaded = new CountDownLatch(1); if (loader == null) { loader = ServiceLoader.load(SlideBarPlugin.class, CurrentWorkingDirectoryClassLoader.getCurrentWorkingDirectoryClassLoader()); } else { loader.reload(); } for (SlideBarPlugin currentImplementation : loader) { PluginVersion currentVersion = currentImplementation.getClass().getAnnotation(PluginVersion.class); if (currentVersion == null) { System.out.println("Found plugin " + currentImplementation.getClass().getCanonicalName() + " but it has no version annotation! Skipping."); continue; } else if (currentVersion.value() != programVersion) { System.out.println("Found plugin " + currentImplementation.getClass().getCanonicalName() + " but its version " + currentVersion.value() + " doesn't match program version " + programVersion + "! Skipping."); continue; } else { PlatformSpecific currentOsAnnotation = currentImplementation.getClass().getAnnotation(PlatformSpecific.class); if (currentOsAnnotation != null) { // Annotation present -> platform specific plugin if (currentOsAnnotation.value() == OsHelper.getOS()) { System.out.println("Loading platform dependant plugin " + currentImplementation.getClass().getCanonicalName() + " for platform " + OsHelper.getOS()); } else { continue; } } else { // No Annotation -> platform independent plugin System.out.println("Loading platform independant plugin " + currentImplementation.getClass().getCanonicalName()); } } int totalSliders = currentImplementation.numberOfSlidersRequired(); Slider usedSlider; for (int i = 0; i < totalSliders; i++) { String sliderID = SettingsHelper.getUsedSliderAtIndex(currentImplementation.getClass().getCanonicalName(), i); if (sliderID == null) { usedSlider = MainBack.getSliderManager().getDefaultSliderByIndex(i); } else { usedSlider = MainBack.getSliderManager().getSliderByID(sliderID); if (usedSlider == null) { usedSlider = MainBack.getSliderManager().getDefaultSliderByIndex(i); } } currentImplementation.setSlider(usedSlider, i); } currentImplementation.setup(); proci.add(currentImplementation); } pluginsLoaded.countDown(); return true; } public void waitUntilProcessesLoaded() throws InterruptedException { pluginsLoaded.await(); } public ArrayList<SlideBarPlugin> getProci() { return proci; } protected void removeProci(boolean RemoveAll) { if (RemoveAll) { proci.clear(); } } }
Reinitialize ServiceLoader at every load to make sure it sees newly added jar files
src/main/java/com/github/slidekb/back/PluginManager.java
Reinitialize ServiceLoader at every load to make sure it sees newly added jar files
<ide><path>rc/main/java/com/github/slidekb/back/PluginManager.java <ide> protected boolean loadProcesses(int programVersion) { <ide> proci.clear(); <ide> pluginsLoaded = new CountDownLatch(1); <del> <del> if (loader == null) { <del> loader = ServiceLoader.load(SlideBarPlugin.class, CurrentWorkingDirectoryClassLoader.getCurrentWorkingDirectoryClassLoader()); <del> } else { <del> loader.reload(); <del> } <add> loader = ServiceLoader.load(SlideBarPlugin.class, CurrentWorkingDirectoryClassLoader.getCurrentWorkingDirectoryClassLoader()); <ide> <ide> for (SlideBarPlugin currentImplementation : loader) { <ide> PluginVersion currentVersion = currentImplementation.getClass().getAnnotation(PluginVersion.class);
JavaScript
mit
01bc17900399cd248ae20fa0dba891ff07c6d7f9
0
juli212/pub_gamer,juli212/pub_gamer,Darrow87/pub_gamer,juli212/pub_gamer,Darrow87/pub_gamer,Darrow87/pub_gamer
$(document).ready(function() { $( "#venues-search-txt" ).autocomplete({ minLength: 2, appendTo: "#venues-search-results", source: function(request, response) { $.ajax({ url: "/venues/search", dataType: "json", data: { term: request.term }, success: function(data) { response($.map(data, function(item) { console.log(data) return { label: item.name, value: item.name, id: item.id }; })) } }) }, select: function(event, ui) { $target = $(event.target) $('#venue-query').val(ui.item.value); }, focus: function(event, ui) { $('.ui-menu-item').css('background-color', "white"); $('.ui-menu-item').css('color', "green"); $('.ui-state-focus').css('background-color', "green"); $('.ui-state-focus').css('color', "white"); } }) // $('ul.ui-autocomplete').removeAttr('style'); // $('.ui-menu-item').css("background-color", "yellow"); // $("#venues-search-results ul li").hover(function(event){ // // debugger; // hovered_div = event.target // $(hovered_div).css("background-color","yellow"); // }) // $("#venue-search-button").on('click', function(event) { // event.preventDefault(); // alert('click!'); // }) $('#venues-search-form').on('submit', function(event) { event.preventDefault(); $target = $(event.target) $.ajax({ url: $target.attr('href'), data: $target.serialize() }).done(function(response){ console.log(response); $('#venue-index-main').html(response); }) }) });
pub-gamer/app/assets/javascripts/venue_search.js
$(document).ready(function() { $( "#venues-search-txt" ).autocomplete({ minLength: 2, appendTo: "#venues-search-results", source: function(request, response) { $.ajax({ url: "/venues/search", dataType: "json", data: { term: request.term }, success: function(data) { response($.map(data, function(item) { console.log(data) return { label: item.name, value: item.name, id: item.id }; })) } }) }, select: function(event, ui) { $target = $(event.target) $('#venue-query').val(ui.item.value); }, focus: function(event, ui) { $('.ui-menu-item').css('background-color', "white"); $('.ui-menu-item').css('color', "green"); $('.ui-state-focus').css('background-color', "green"); $('.ui-state-focus').css('color', "white"); } }) // $('ul.ui-autocomplete').removeAttr('style'); // $('.ui-menu-item').css("background-color", "yellow"); // $("#venues-search-results ul li").hover(function(event){ // // debugger; // hovered_div = event.target // $(hovered_div).css("background-color","yellow"); // }) // $("#venue-search-button").on('click', function(event) { // event.preventDefault(); // alert('click!'); // }) $('#venues-search-form').on('submit', function(event) { event.preventDefault(); $target = $(event.target) debugger; $.ajax({ url: $target.attr('href'), data: $target.serialize() }).done(function(response){ console.log(response); $('#venue-index-main').html(response); }) }) });
remove debugger
pub-gamer/app/assets/javascripts/venue_search.js
remove debugger
<ide><path>ub-gamer/app/assets/javascripts/venue_search.js <ide> $('#venues-search-form').on('submit', function(event) { <ide> event.preventDefault(); <ide> $target = $(event.target) <del> debugger; <ide> $.ajax({ <ide> url: $target.attr('href'), <ide> data: $target.serialize()
Java
mit
9d158b0fe7cf5467e100679f67cb0789ccb8d60b
0
drahot/Opentok-Java-SDK,Kwasniewski/Opentok-Java-SDK,CamioCam/Opentok-Java-SDK,opentok/Opentok-Java-SDK,drahot/Opentok-Java-SDK,opentok/Opentok-Java-SDK,mukesh-kum/Opentok-Java-SDK,mukesh-kum/Opentok-Java-SDK,CamioCam/Opentok-Java-SDK,Kwasniewski/Opentok-Java-SDK
/*! * OpenTok Java Library * http://www.tokbox.com/ * * Copyright 2010, TokBox, Inc. * */ package com.opentok.api; public class API_Config { public static final int API_KEY = 0; // Fill this in with generated API Key (http://tokbox.com/opentok/api/tools/js/apikey) public static final String API_SECRET = ""; // Fill this in with generated API Secret in email public static final String API_URL = "http://api.opentok.com"; }
src/main/java/com/opentok/api/API_Config.java
/*! * OpenTok Java Library * http://www.tokbox.com/ * * Copyright 2010, TokBox, Inc. * */ package com.opentok.api; public class API_Config { public static final int API_KEY = 0; // Fill this in with generated API Key (http://tokbox.com/opentok/api/tools/js/apikey) public static final String API_SECRET = ""; // Fill this in with generated API Secret in email public static final String API_URL = "https://api.opentok.com"; }
Updating the API_URL to not point to https by default
src/main/java/com/opentok/api/API_Config.java
Updating the API_URL to not point to https by default
<ide><path>rc/main/java/com/opentok/api/API_Config.java <ide> <ide> public static final String API_SECRET = ""; // Fill this in with generated API Secret in email <ide> <del> public static final String API_URL = "https://api.opentok.com"; <add> public static final String API_URL = "http://api.opentok.com"; <ide> } <ide>
JavaScript
bsd-3-clause
54f9d6a3ddfeb80dc82622120a44e81270a336df
0
ltilve/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,ltilve/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,dednal/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,dednal/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,ltilve/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,bright-sparks/chromium-spacewalk,Chilledheart/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ltilve/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Jonekee/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,chuan9/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (function() { /** @const */ var BookmarkList = bmm.BookmarkList; /** @const */ var BookmarkTree = bmm.BookmarkTree; /** @const */ var Command = cr.ui.Command; /** @const */ var CommandBinding = cr.ui.CommandBinding; /** @const */ var LinkKind = cr.LinkKind; /** @const */ var ListItem = cr.ui.ListItem; /** @const */ var Menu = cr.ui.Menu; /** @const */ var MenuButton = cr.ui.MenuButton; /** @const */ var Promise = cr.Promise; /** @const */ var Splitter = cr.ui.Splitter; /** @const */ var TreeItem = cr.ui.TreeItem; /** * An array containing the BookmarkTreeNodes that were deleted in the last * deletion action. This is used for implementing undo. * @type {Array.<BookmarkTreeNode>} */ var lastDeletedNodes; /** * * Holds the last DOMTimeStamp when mouse pointer hovers on folder in tree * view. Zero means pointer doesn't hover on folder. * @type {number} */ var lastHoverOnFolderTimeStamp = 0; /** * Holds a function that will undo that last action, if global undo is enabled. * @type {Function} */ var performGlobalUndo; /** * Holds a link controller singleton. Use getLinkController() rarther than * accessing this variabie. * @type {LinkController} */ var linkController; /** * New Windows are not allowed in Windows 8 metro mode. */ var canOpenNewWindows = true; /** * Incognito mode availability can take the following values: , * - 'enabled' for when both normal and incognito modes are available; * - 'disabled' for when incognito mode is disabled; * - 'forced' for when incognito mode is forced (normal mode is unavailable). */ var incognitoModeAvailability = 'enabled'; /** * Whether bookmarks can be modified. * @type {boolean} */ var canEdit = true; /** * @type {TreeItem} * @const */ var searchTreeItem = new TreeItem({ bookmarkId: 'q=' }); /** * @type {TreeItem} * @const */ var recentTreeItem = new TreeItem({ icon: 'images/bookmark_manager_recent.png', bookmarkId: 'recent' }); /** * Command shortcut mapping. * @const */ var commandShortcutMap = cr.isMac ? { 'edit': 'Enter', // On Mac we also allow Meta+Backspace. 'delete': 'U+007F U+0008 Meta-U+0008', 'open-in-background-tab': 'Meta-Enter', 'open-in-new-tab': 'Shift-Meta-Enter', 'open-in-same-window': 'Meta-Down', 'open-in-new-window': 'Shift-Enter', 'rename-folder': 'Enter', // Global undo is Command-Z. It is not in any menu. 'undo': 'Meta-U+005A', } : { 'edit': 'F2', 'delete': 'U+007F', 'open-in-background-tab': 'Ctrl-Enter', 'open-in-new-tab': 'Shift-Ctrl-Enter', 'open-in-same-window': 'Enter', 'open-in-new-window': 'Shift-Enter', 'rename-folder': 'F2', // Global undo is Ctrl-Z. It is not in any menu. 'undo': 'Ctrl-U+005A', }; /** * Adds an event listener to a node that will remove itself after firing once. * @param {!Element} node The DOM node to add the listener to. * @param {string} name The name of the event listener to add to. * @param {function(Event)} handler Function called when the event fires. */ function addOneShotEventListener(node, name, handler) { var f = function(e) { handler(e); node.removeEventListener(name, f); }; node.addEventListener(name, f); } // Get the localized strings from the backend via bookmakrManagerPrivate API. function loadLocalizedStrings(data) { // The strings may contain & which we need to strip. for (var key in data) { data[key] = data[key].replace(/&/, ''); } loadTimeData.data = data; i18nTemplate.process(document, loadTimeData); recentTreeItem.label = loadTimeData.getString('recent'); searchTreeItem.label = loadTimeData.getString('search'); searchTreeItem.icon = isRTL() ? 'images/bookmark_manager_search_rtl.png' : 'images/bookmark_manager_search.png'; } /** * Updates the location hash to reflect the current state of the application. */ function updateHash() { window.location.hash = tree.selectedItem.bookmarkId; } /** * Navigates to a bookmark ID. * @param {string} id The ID to navigate to. * @param {function()} callback Function called when list view loaded or * displayed specified folder. */ function navigateTo(id, callback) { if (list.parentId == id) { callback(); return; } addOneShotEventListener(list, 'load', callback); updateParentId(id); } /** * Updates the parent ID of the bookmark list and selects the correct tree item. * @param {string} id The id. */ function updateParentId(id) { // Setting list.parentId fires 'load' event. list.parentId = id; // When tree.selectedItem changed, tree view calls navigatTo() then it // calls updateHash() when list view displayed specified folder. tree.selectedItem = bmm.treeLookup[id] || tree.selectedItem; } // Process the location hash. This is called by onhashchange and when the page // is first loaded. function processHash() { var id = window.location.hash.slice(1); if (!id) { // If we do not have a hash, select first item in the tree. id = tree.items[0].bookmarkId; } var valid = false; if (/^e=/.test(id)) { id = id.slice(2); // If hash contains e=, edit the item specified. chrome.bookmarks.get(id, function(bookmarkNodes) { // Verify the node to edit is a valid node. if (!bookmarkNodes || bookmarkNodes.length != 1) return; var bookmarkNode = bookmarkNodes[0]; // After the list reloads, edit the desired bookmark. var editBookmark = function(e) { var index = list.dataModel.findIndexById(bookmarkNode.id); if (index != -1) { var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; scrollIntoViewAndMakeEditable(index); } }; navigateTo(bookmarkNode.parentId, editBookmark); }); // We handle the two cases of navigating to the bookmark to be edited // above. Don't run the standard navigation code below. return; } else if (/^q=/.test(id)) { // In case we got a search hash, update the text input and the // bmm.treeLookup to use the new id. setSearch(id.slice(2)); valid = true; } else if (id == 'recent') { valid = true; } // Navigate to bookmark 'id' (which may be a query of the form q=query). if (valid) { updateParentId(id); } else { // We need to verify that this is a correct ID. chrome.bookmarks.get(id, function(items) { if (items && items.length == 1) updateParentId(id); }); } } // Activate is handled by the open-in-same-window-command. function handleDoubleClickForList(e) { if (e.button == 0) $('open-in-same-window-command').execute(); } // The list dispatches an event when the user clicks on the URL or the Show in // folder part. function handleUrlClickedForList(e) { getLinkController().openUrlFromEvent(e.url, e.originalEvent); chrome.bookmarkManagerPrivate.recordLaunch(); } function handleSearch(e) { setSearch(this.value); } /** * Navigates to the search results for the search text. * @param {string} searchText The text to search for. */ function setSearch(searchText) { if (searchText) { // Only update search item if we have a search term. We never want the // search item to be for an empty search. delete bmm.treeLookup[searchTreeItem.bookmarkId]; var id = searchTreeItem.bookmarkId = 'q=' + searchText; bmm.treeLookup[searchTreeItem.bookmarkId] = searchTreeItem; } var input = $('term'); // Do not update the input if the user is actively using the text input. if (document.activeElement != input) input.value = searchText; if (searchText) { tree.add(searchTreeItem); tree.selectedItem = searchTreeItem; } else { // Go "home". tree.selectedItem = tree.items[0]; id = tree.selectedItem.bookmarkId; } // Navigate now and update hash immediately. navigateTo(id, updateHash); } // Handle the logo button UI. // When the user clicks the button we should navigate "home" and focus the list. function handleClickOnLogoButton(e) { setSearch(''); $('list').focus(); } /** * This returns the user visible path to the folder where the bookmark is * located. * @param {number} parentId The ID of the parent folder. * @return {string} The path to the the bookmark, */ function getFolder(parentId) { var parentNode = tree.getBookmarkNodeById(parentId); if (parentNode) { var s = parentNode.title; if (parentNode.parentId != bmm.ROOT_ID) { return getFolder(parentNode.parentId) + '/' + s; } return s; } } function handleLoadForTree(e) { // Add hard coded tree items. tree.add(recentTreeItem); processHash(); } /** * Returns the bookmark nodes that should be opened through the open context * menu commands. * @param {HTMLElement} target The target list or tree. * @return {!Array.<!BookmarkTreeNode>} . */ function getBookmarkNodesForOpenCommands(target) { if (target == tree) return tree.selectedFolders; var listItems = list.selectedItems; return listItems.length ? listItems : list.dataModel.slice(); } /** * Helper function that updates the canExecute and labels for the open-like * commands. * @param {!cr.ui.CanExecuteEvent} e The event fired by the command system. * @param {!cr.ui.Command} command The command we are currently processing. */ function updateOpenCommands(e, command) { var selectedItems = getBookmarkNodesForOpenCommands(e.target); var isFolder = selectedItems.length == 1 && bmm.isFolder(selectedItems[0]); var multiple = selectedItems.length != 1 || isFolder; function hasBookmarks(node) { for (var i = 0; i < node.children.length; i++) { if (!bmm.isFolder(node.children[i])) return true; } return false; } var commandDisabled = false; switch (command.id) { case 'open-in-new-tab-command': command.label = loadTimeData.getString(multiple ? 'open_all' : 'open_in_new_tab'); break; case 'open-in-new-window-command': command.label = loadTimeData.getString(multiple ? 'open_all_new_window' : 'open_in_new_window'); // Disabled when incognito is forced. commandDisabled = incognitoModeAvailability == 'forced' || !canOpenNewWindows; break; case 'open-incognito-window-command': command.label = loadTimeData.getString(multiple ? 'open_all_incognito' : 'open_incognito'); // Not available withn incognito is disabled. commandDisabled = incognitoModeAvailability == 'disabled'; break; } e.canExecute = selectedItems.length > 0 && !commandDisabled; if (isFolder && e.canExecute) { // We need to get all the bookmark items in this tree. If the tree does not // contain any non-folders, we need to disable the command. var p = bmm.loadSubtree(selectedItems[0].id); p.addListener(function(node) { command.disabled = !node || !hasBookmarks(node); }); } } /** * Calls the backend to figure out if we can paste the clipboard into the active * folder. * @param {Function=} opt_f Function to call after the state has been updated. */ function updatePasteCommand(opt_f) { function update(canPaste) { var organizeMenuCommand = $('paste-from-organize-menu-command'); var contextMenuCommand = $('paste-from-context-menu-command'); organizeMenuCommand.disabled = !canPaste; contextMenuCommand.disabled = !canPaste; if (opt_f) opt_f(); } // We cannot paste into search and recent view. if (list.isSearch() || list.isRecent()) { update(false); } else { chrome.bookmarkManagerPrivate.canPaste(list.parentId, update); } } function handleCanExecuteForDocument(e) { var command = e.command; switch (command.id) { case 'import-menu-command': e.canExecute = canEdit; break; case 'export-menu-command': // We can always execute the export-menu command. e.canExecute = true; break; case 'sort-command': e.canExecute = !list.isRecent() && !list.isSearch() && list.dataModel.length > 1; break; case 'undo-command': // The global undo command has no visible UI, so always enable it, and // just make it a no-op if undo is not possible. e.canExecute = true; break; default: canExecuteForList(e); break; } } /** * Helper function for handling canExecute for the list and the tree. * @param {!Event} e Can execute event object. * @param {boolean} isRecentOrSearch Whether the user is trying to do a command * on recent or search. */ function canExecuteShared(e, isRecentOrSearch) { var command = e.command; var commandId = command.id; switch (commandId) { case 'paste-from-organize-menu-command': case 'paste-from-context-menu-command': updatePasteCommand(); break; case 'add-new-bookmark-command': case 'new-folder-command': e.canExecute = !isRecentOrSearch && canEdit; break; case 'open-in-new-tab-command': case 'open-in-background-tab-command': case 'open-in-new-window-command': case 'open-incognito-window-command': updateOpenCommands(e, command); break; case 'undo-delete-command': e.canExecute = !!lastDeletedNodes; break; } } /** * Helper function for handling canExecute for the list and document. * @param {!Event} e Can execute event object. */ function canExecuteForList(e) { var command = e.command; var commandId = command.id; function hasSelected() { return !!list.selectedItem; } function hasSingleSelected() { return list.selectedItems.length == 1; } function canCopyItem(item) { return item.id != 'new'; } function canCopyItems() { var selectedItems = list.selectedItems; return selectedItems && selectedItems.some(canCopyItem); } function isRecentOrSearch() { return list.isRecent() || list.isSearch(); } switch (commandId) { case 'rename-folder-command': // Show rename if a single folder is selected. var items = list.selectedItems; if (items.length != 1) { e.canExecute = false; command.hidden = true; } else { var isFolder = bmm.isFolder(items[0]); e.canExecute = isFolder && canEdit; command.hidden = !isFolder; } break; case 'edit-command': // Show the edit command if not a folder. var items = list.selectedItems; if (items.length != 1) { e.canExecute = false; command.hidden = false; } else { var isFolder = bmm.isFolder(items[0]); e.canExecute = !isFolder && canEdit; command.hidden = isFolder; } break; case 'show-in-folder-command': e.canExecute = isRecentOrSearch() && hasSingleSelected(); break; case 'delete-command': case 'cut-command': e.canExecute = canCopyItems() && canEdit; break; case 'copy-command': e.canExecute = canCopyItems(); break; case 'open-in-same-window-command': e.canExecute = hasSelected(); break; default: canExecuteShared(e, isRecentOrSearch()); } } // Update canExecute for the commands when the list is the active element. function handleCanExecuteForList(e) { if (e.target != list) return; canExecuteForList(e); } // Update canExecute for the commands when the tree is the active element. function handleCanExecuteForTree(e) { if (e.target != tree) return; var command = e.command; var commandId = command.id; function hasSelected() { return !!e.target.selectedItem; } function isRecentOrSearch() { var item = e.target.selectedItem; return item == recentTreeItem || item == searchTreeItem; } function isTopLevelItem() { return e.target.selectedItem.parentNode == tree; } switch (commandId) { case 'rename-folder-command': command.hidden = false; e.canExecute = hasSelected() && !isTopLevelItem() && canEdit; break; case 'edit-command': command.hidden = true; e.canExecute = false; break; case 'delete-command': case 'cut-command': e.canExecute = hasSelected() && !isTopLevelItem() && canEdit; break; case 'copy-command': e.canExecute = hasSelected() && !isTopLevelItem(); break; default: canExecuteShared(e, isRecentOrSearch()); } } /** * Update the canExecute state of the commands when the selection changes. * @param {Event} e The change event object. */ function updateCommandsBasedOnSelection(e) { if (e.target == document.activeElement) { // Paste only needs to be updated when the tree selection changes. var commandNames = ['copy', 'cut', 'delete', 'rename-folder', 'edit', 'add-new-bookmark', 'new-folder', 'open-in-new-tab', 'open-in-new-window', 'open-incognito-window', 'open-in-same-window', 'show-in-folder']; if (e.target == tree) { commandNames.push('paste-from-context-menu', 'paste-from-organize-menu', 'sort'); } commandNames.forEach(function(baseId) { $(baseId + '-command').canExecuteChange(); }); } } function updateEditingCommands() { var editingCommands = ['cut', 'delete', 'rename-folder', 'edit', 'add-new-bookmark', 'new-folder', 'sort', 'paste-from-context-menu', 'paste-from-organize-menu']; chrome.bookmarkManagerPrivate.canEdit(function(result) { if (result != canEdit) { canEdit = result; editingCommands.forEach(function(baseId) { $(baseId + '-command').canExecuteChange(); }); } }); } function handleChangeForTree(e) { updateCommandsBasedOnSelection(e); navigateTo(tree.selectedItem.bookmarkId, updateHash); } function handleOrganizeButtonClick(e) { updateEditingCommands(); $('add-new-bookmark-command').canExecuteChange(); $('new-folder-command').canExecuteChange(); $('sort-command').canExecuteChange(); } function handleRename(e) { var item = e.target; var bookmarkNode = item.bookmarkNode; chrome.bookmarks.update(bookmarkNode.id, {title: item.label}); performGlobalUndo = null; // This can't be undone, so disable global undo. } function handleEdit(e) { var item = e.target; var bookmarkNode = item.bookmarkNode; var context = { title: bookmarkNode.title }; if (!bmm.isFolder(bookmarkNode)) context.url = bookmarkNode.url; if (bookmarkNode.id == 'new') { selectItemsAfterUserAction(list); // New page context.parentId = bookmarkNode.parentId; chrome.bookmarks.create(context, function(node) { // A new node was created and will get added to the list due to the // handler. var dataModel = list.dataModel; var index = dataModel.indexOf(bookmarkNode); dataModel.splice(index, 1); // Select new item. var newIndex = dataModel.findIndexById(node.id); if (newIndex != -1) { var sm = list.selectionModel; list.scrollIndexIntoView(newIndex); sm.leadIndex = sm.anchorIndex = sm.selectedIndex = newIndex; } }); } else { // Edit chrome.bookmarks.update(bookmarkNode.id, context); } performGlobalUndo = null; // This can't be undone, so disable global undo. } function handleCancelEdit(e) { var item = e.target; var bookmarkNode = item.bookmarkNode; if (bookmarkNode.id == 'new') { var dataModel = list.dataModel; var index = dataModel.findIndexById('new'); dataModel.splice(index, 1); } } /** * Navigates to the folder that the selected item is in and selects it. This is * used for the show-in-folder command. */ function showInFolder() { var bookmarkNode = list.selectedItem; if (!bookmarkNode) return; var parentId = bookmarkNode.parentId; // After the list is loaded we should select the revealed item. function selectItem() { var index = list.dataModel.findIndexById(bookmarkNode.id); if (index == -1) return; var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; list.scrollIndexIntoView(index); } var treeItem = bmm.treeLookup[parentId]; treeItem.reveal(); navigateTo(parentId, selectItem); } /** * @return {!cr.LinkController} The link controller used to open links based on * user clicks and keyboard actions. */ function getLinkController() { return linkController || (linkController = new cr.LinkController(loadTimeData)); } /** * Returns the selected bookmark nodes of the provided tree or list. * If |opt_target| is not provided or null the active element is used. * Only call this if the list or the tree is focused. * @param {BookmarkList|BookmarkTree} opt_target The target list or tree. * @return {!Array} Array of bookmark nodes. */ function getSelectedBookmarkNodes(opt_target) { return (opt_target || document.activeElement) == tree ? tree.selectedFolders : list.selectedItems; } /** * @return {!Array.<string>} An array of the selected bookmark IDs. */ function getSelectedBookmarkIds() { return getSelectedBookmarkNodes().map(function(node) { return node.id; }); } /** * Opens the selected bookmarks. * @param {LinkKind} kind The kind of link we want to open. * @param {HTMLElement} opt_eventTarget The target of the user initiated event. */ function openBookmarks(kind, opt_eventTarget) { // If we have selected any folders, we need to find all items recursively. // We use multiple async calls to getSubtree instead of getting the whole // tree since we would like to minimize the amount of data sent. var urls = []; // Adds the node and all its children. function addNodes(node) { if (node.children) { node.children.forEach(function(child) { if (!bmm.isFolder(child)) urls.push(child.url); }); } else { urls.push(node.url); } } var nodes = getBookmarkNodesForOpenCommands(opt_eventTarget); // Get a future promise for every selected item. var promises = nodes.map(function(node) { if (bmm.isFolder(node)) return bmm.loadSubtree(node.id); // Not a folder so we already have all the data we need. return new Promise(node.url); }); var p = Promise.all.apply(null, promises); p.addListener(function(values) { values.forEach(function(v) { if (typeof v == 'string') urls.push(v); else addNodes(v); }); getLinkController().openUrls(urls, kind); chrome.bookmarkManagerPrivate.recordLaunch(); }); } /** * Opens an item in the list. */ function openItem() { var bookmarkNodes = getSelectedBookmarkNodes(); // If we double clicked or pressed enter on a single folder, navigate to it. if (bookmarkNodes.length == 1 && bmm.isFolder(bookmarkNodes[0])) { navigateTo(bookmarkNodes[0].id, updateHash); } else { openBookmarks(LinkKind.FOREGROUND_TAB); } } /** * Deletes the selected bookmarks. The bookmarks are saved in memory in case * the user needs to undo the deletion. */ function deleteBookmarks() { var selectedIds = getSelectedBookmarkIds(); lastDeletedNodes = []; function performDelete() { selectedIds.forEach(function(id) { chrome.bookmarks.removeTree(id); }); $('undo-delete-command').canExecuteChange(); performGlobalUndo = undoDelete; } // First, store information about the bookmarks being deleted. selectedIds.forEach(function(id) { chrome.bookmarks.getSubTree(id, function(results) { lastDeletedNodes.push(results); // When all nodes have been saved, perform the deletion. if (lastDeletedNodes.length === selectedIds.length) performDelete(); }); }); } /** * Restores a tree of bookmarks under a specified folder. * @param {BookmarkTreeNode} node The node to restore. * @param {=string} parentId The ID of the folder to restore under. If not * specified, the original parentId of the node will be used. */ function restoreTree(node, parentId) { var bookmarkInfo = { parentId: parentId || node.parentId, title: node.title, index: node.index, url: node.url }; chrome.bookmarks.create(bookmarkInfo, function(result) { if (!result) { console.error('Failed to restore bookmark.'); return; } if (node.children) { // Restore the children using the new ID for this node. node.children.forEach(function(child) { restoreTree(child, result.id); }); } }); } /** * Restores the last set of bookmarks that was deleted. */ function undoDelete() { lastDeletedNodes.forEach(function(arr) { arr.forEach(restoreTree); }); lastDeletedNodes = null; $('undo-delete-command').canExecuteChange(); // Only a single level of undo is supported, so disable global undo now. performGlobalUndo = null; } /** * Computes folder for "Add Page" and "Add Folder". * @return {string} The id of folder node where we'll create new page/folder. */ function computeParentFolderForNewItem() { if (document.activeElement == tree) return list.parentId; var selectedItem = list.selectedItem; return selectedItem && bmm.isFolder(selectedItem) ? selectedItem.id : list.parentId; } /** * Callback for rename folder and edit command. This starts editing for * selected item. */ function editSelectedItem() { if (document.activeElement == tree) { tree.selectedItem.editing = true; } else { var li = list.getListItem(list.selectedItem); if (li) li.editing = true; } } /** * Callback for the new folder command. This creates a new folder and starts * a rename of it. */ function newFolder() { performGlobalUndo = null; // This can't be undone, so disable global undo. var parentId = computeParentFolderForNewItem(); // Callback is called after tree and list data model updated. function createFolder(callback) { chrome.bookmarks.create({ title: loadTimeData.getString('new_folder_name'), parentId: parentId }, callback); } if (document.activeElement == tree) { createFolder(function(newNode) { navigateTo(newNode.id, function() { bmm.treeLookup[newNode.id].editing = true; }); }); return; } function editNewFolderInList() { createFolder(function() { var index = list.dataModel.length - 1; var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; scrollIntoViewAndMakeEditable(index); }); } navigateTo(parentId, editNewFolderInList); } /** * Scrolls the list item into view and makes it editable. * @param {number} index The index of the item to make editable. */ function scrollIntoViewAndMakeEditable(index) { list.scrollIndexIntoView(index); // onscroll is now dispatched asynchronously so we have to postpone // the rest. setTimeout(function() { var item = list.getListItemByIndex(index); if (item) item.editing = true; }); } /** * Adds a page to the current folder. This is called by the * add-new-bookmark-command handler. */ function addPage() { var parentId = computeParentFolderForNewItem(); function editNewBookmark() { var fakeNode = { title: '', url: '', parentId: parentId, id: 'new' }; var dataModel = list.dataModel; var length = dataModel.length; dataModel.splice(length, 0, fakeNode); var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = length; scrollIntoViewAndMakeEditable(length); }; navigateTo(parentId, editNewBookmark); } /** * This function is used to select items after a user action such as paste, drop * add page etc. * @param {BookmarkList|BookmarkTree} target The target of the user action. * @param {=string} opt_selectedTreeId If provided, then select that tree id. */ function selectItemsAfterUserAction(target, opt_selectedTreeId) { // We get one onCreated event per item so we delay the handling until we get // no more events coming. var ids = []; var timer; function handle(id, bookmarkNode) { clearTimeout(timer); if (opt_selectedTreeId || list.parentId == bookmarkNode.parentId) ids.push(id); timer = setTimeout(handleTimeout, 50); } function handleTimeout() { chrome.bookmarks.onCreated.removeListener(handle); chrome.bookmarks.onMoved.removeListener(handle); if (opt_selectedTreeId && ids.indexOf(opt_selectedTreeId) != -1) { var index = ids.indexOf(opt_selectedTreeId); if (index != -1 && opt_selectedTreeId in bmm.treeLookup) { tree.selectedItem = bmm.treeLookup[opt_selectedTreeId]; } } else if (target == list) { var dataModel = list.dataModel; var firstIndex = dataModel.findIndexById(ids[0]); var lastIndex = dataModel.findIndexById(ids[ids.length - 1]); if (firstIndex != -1 && lastIndex != -1) { var selectionModel = list.selectionModel; selectionModel.selectedIndex = -1; selectionModel.selectRange(firstIndex, lastIndex); selectionModel.anchorIndex = selectionModel.leadIndex = lastIndex; list.focus(); } } list.endBatchUpdates(); } list.startBatchUpdates(); chrome.bookmarks.onCreated.addListener(handle); chrome.bookmarks.onMoved.addListener(handle); timer = setTimeout(handleTimeout, 300); } /** * Record user action. * @param {string} name An user action name. */ function recordUserAction(name) { chrome.metricsPrivate.recordUserAction('BookmarkManager_Command_' + name); } /** * The currently selected bookmark, based on where the user is clicking. * @return {string} The ID of the currently selected bookmark (could be from * tree view or list view). */ function getSelectedId() { if (document.activeElement == tree) return tree.selectedItem.bookmarkId; var selectedItem = list.selectedItem; return selectedItem && bmm.isFolder(selectedItem) ? selectedItem.id : tree.selectedItem.bookmarkId; } /** * Pastes the copied/cutted bookmark into the right location depending whether * if it was called from Organize Menu or from Context Menu. * @param {string} id The id of the element being pasted from. */ function pasteBookmark(id) { recordUserAction('Paste'); selectItemsAfterUserAction(list); chrome.bookmarkManagerPrivate.paste(id, getSelectedBookmarkIds()); } /** * Handler for the command event. This is used for context menu of list/tree * and organized menu. * @param {!Event} e The event object. */ function handleCommand(e) { var command = e.command; var commandId = command.id; switch (commandId) { case 'import-menu-command': recordUserAction('Import'); chrome.bookmarks.import(); break; case 'export-menu-command': recordUserAction('Export'); chrome.bookmarks.export(); break; case 'undo-command': if (performGlobalUndo) { recordUserAction('UndoGlobal'); performGlobalUndo(); } else { recordUserAction('UndoNone'); } break; case 'show-in-folder-command': recordUserAction('ShowInFolder'); showInFolder(); break; case 'open-in-new-tab-command': case 'open-in-background-tab-command': recordUserAction('OpenInNewTab'); openBookmarks(LinkKind.BACKGROUND_TAB, e.target); break; case 'open-in-new-window-command': recordUserAction('OpenInNewWindow'); openBookmarks(LinkKind.WINDOW, e.target); break; case 'open-incognito-window-command': recordUserAction('OpenIncognito'); openBookmarks(LinkKind.INCOGNITO, e.target); break; case 'delete-command': recordUserAction('Delete'); deleteBookmarks(); break; case 'copy-command': recordUserAction('Copy'); chrome.bookmarkManagerPrivate.copy(getSelectedBookmarkIds(), updatePasteCommand); break; case 'cut-command': recordUserAction('Cut'); chrome.bookmarkManagerPrivate.cut(getSelectedBookmarkIds(), updatePasteCommand); break; case 'paste-from-organize-menu-command': pasteBookmark(list.parentId); break; case 'paste-from-context-menu-command': pasteBookmark(getSelectedId()); break; case 'sort-command': recordUserAction('Sort'); chrome.bookmarkManagerPrivate.sortChildren(list.parentId); break; case 'rename-folder-command': editSelectedItem(); break; case 'edit-command': recordUserAction('Edit'); editSelectedItem(); break; case 'new-folder-command': recordUserAction('NewFolder'); newFolder(); break; case 'add-new-bookmark-command': recordUserAction('AddPage'); addPage(); break; case 'open-in-same-window-command': recordUserAction('OpenInSame'); openItem(); break; case 'undo-delete-command': recordUserAction('UndoDelete'); undoDelete(); break; } } // Execute the copy, cut and paste commands when those events are dispatched by // the browser. This allows us to rely on the browser to handle the keyboard // shortcuts for these commands. function installEventHandlerForCommand(eventName, commandId) { function handle(e) { if (document.activeElement != list && document.activeElement != tree) return; var command = $(commandId); if (!command.disabled) { command.execute(); if (e) e.preventDefault(); // Prevent the system beep. } } if (eventName == 'paste') { // Paste is a bit special since we need to do an async call to see if we // can paste because the paste command might not be up to date. document.addEventListener(eventName, function(e) { updatePasteCommand(handle); }); } else { document.addEventListener(eventName, handle); } } function initializeSplitter() { var splitter = document.querySelector('.main > .splitter'); Splitter.decorate(splitter); // The splitter persists the size of the left component in the local store. if ('treeWidth' in localStorage) splitter.previousElementSibling.style.width = localStorage['treeWidth']; splitter.addEventListener('resize', function(e) { localStorage['treeWidth'] = splitter.previousElementSibling.style.width; }); } function initializeBookmarkManager() { // Sometimes the extension API is not initialized. if (!chrome.bookmarks) console.error('Bookmarks extension API is not available'); chrome.bookmarkManagerPrivate.getStrings(loadLocalizedStrings); bmm.treeLookup[searchTreeItem.bookmarkId] = searchTreeItem; bmm.treeLookup[recentTreeItem.bookmarkId] = recentTreeItem; cr.ui.decorate('menu', Menu); cr.ui.decorate('button[menu]', MenuButton); cr.ui.decorate('command', Command); BookmarkList.decorate(list); BookmarkTree.decorate(tree); list.addEventListener('canceledit', handleCancelEdit); list.addEventListener('canExecute', handleCanExecuteForList); list.addEventListener('change', updateCommandsBasedOnSelection); list.addEventListener('contextmenu', updateEditingCommands); list.addEventListener('dblclick', handleDoubleClickForList); list.addEventListener('edit', handleEdit); list.addEventListener('rename', handleRename); list.addEventListener('urlClicked', handleUrlClickedForList); tree.addEventListener('canExecute', handleCanExecuteForTree); tree.addEventListener('change', handleChangeForTree); tree.addEventListener('contextmenu', updateEditingCommands); tree.addEventListener('rename', handleRename); tree.addEventListener('load', handleLoadForTree); cr.ui.contextMenuHandler.addContextMenuProperty(tree); list.contextMenu = $('context-menu'); tree.contextMenu = $('context-menu'); // We listen to hashchange so that we can update the currently shown folder // when // the user goes back and forward in the history. window.addEventListener('hashchange', processHash); document.querySelector('.header form').onsubmit = function(e) { setSearch($('term').value); e.preventDefault(); }; $('term').addEventListener('search', handleSearch); document.querySelector('.summary > button').addEventListener( 'click', handleOrganizeButtonClick); document.querySelector('button.logo').addEventListener( 'click', handleClickOnLogoButton); document.addEventListener('canExecute', handleCanExecuteForDocument); document.addEventListener('command', handleCommand); // Listen to copy, cut and paste events and execute the associated commands. installEventHandlerForCommand('copy', 'copy-command'); installEventHandlerForCommand('cut', 'cut-command'); installEventHandlerForCommand('paste', 'paste-from-organize-menu-command'); // Install shortcuts for (var name in commandShortcutMap) { $(name + '-command').shortcut = commandShortcutMap[name]; } // Disable almost all commands at startup. var commands = document.querySelectorAll('command'); for (var i = 0, command; command = commands[i]; ++i) { if (command.id != 'import-menu-command' && command.id != 'export-menu-command') { command.disabled = true; } } chrome.bookmarkManagerPrivate.canEdit(function(result) { canEdit = result; }); chrome.systemPrivate.getIncognitoModeAvailability(function(result) { // TODO(rustema): propagate policy value to the bookmark manager when it // changes. incognitoModeAvailability = result; }); chrome.bookmarkManagerPrivate.canOpenNewWindows(function(result) { canOpenNewWindows = result; }); initializeSplitter(); bmm.addBookmarkModelListeners(); dnd.init(selectItemsAfterUserAction); tree.reload(); } initializeBookmarkManager(); })();
chrome/browser/resources/bookmark_manager/js/main.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (function() { /** @const */ var BookmarkList = bmm.BookmarkList; /** @const */ var BookmarkTree = bmm.BookmarkTree; /** @const */ var Command = cr.ui.Command; /** @const */ var CommandBinding = cr.ui.CommandBinding; /** @const */ var LinkKind = cr.LinkKind; /** @const */ var ListItem = cr.ui.ListItem; /** @const */ var Menu = cr.ui.Menu; /** @const */ var MenuButton = cr.ui.MenuButton; /** @const */ var Promise = cr.Promise; /** @const */ var Splitter = cr.ui.Splitter; /** @const */ var TreeItem = cr.ui.TreeItem; /** * An array containing the BookmarkTreeNodes that were deleted in the last * deletion action. This is used for implementing undo. * @type {Array.<BookmarkTreeNode>} */ var lastDeletedNodes; /** * * Holds the last DOMTimeStamp when mouse pointer hovers on folder in tree * view. Zero means pointer doesn't hover on folder. * @type {number} */ var lastHoverOnFolderTimeStamp = 0; /** * Holds a function that will undo that last action, if global undo is enabled. * @type {Function} */ var performGlobalUndo; /** * Holds a link controller singleton. Use getLinkController() rarther than * accessing this variabie. * @type {LinkController} */ var linkController; /** * New Windows are not allowed in Windows 8 metro mode. */ var canOpenNewWindows = true; /** * Incognito mode availability can take the following values: , * - 'enabled' for when both normal and incognito modes are available; * - 'disabled' for when incognito mode is disabled; * - 'forced' for when incognito mode is forced (normal mode is unavailable). */ var incognitoModeAvailability = 'enabled'; /** * Whether bookmarks can be modified. * @type {boolean} */ var canEdit = true; /** * @type {TreeItem} * @const */ var searchTreeItem = new TreeItem({ bookmarkId: 'q=' }); /** * @type {TreeItem} * @const */ var recentTreeItem = new TreeItem({ icon: 'images/bookmark_manager_recent.png', bookmarkId: 'recent' }); /** * Command shortcut mapping. * @const */ var commandShortcutMap = cr.isMac ? { 'edit': 'Enter', // On Mac we also allow Meta+Backspace. 'delete': 'U+007F U+0008 Meta-U+0008', 'open-in-background-tab': 'Meta-Enter', 'open-in-new-tab': 'Shift-Meta-Enter', 'open-in-same-window': 'Meta-Down', 'open-in-new-window': 'Shift-Enter', 'rename-folder': 'Enter', // Global undo is Command-Z. It is not in any menu. 'undo': 'Meta-U+005A', } : { 'edit': 'F2', 'delete': 'U+007F', 'open-in-background-tab': 'Ctrl-Enter', 'open-in-new-tab': 'Shift-Ctrl-Enter', 'open-in-same-window': 'Enter', 'open-in-new-window': 'Shift-Enter', 'rename-folder': 'F2', // Global undo is Ctrl-Z. It is not in any menu. 'undo': 'Ctrl-U+005A', }; /** * Adds an event listener to a node that will remove itself after firing once. * @param {!Element} node The DOM node to add the listener to. * @param {string} name The name of the event listener to add to. * @param {function(Event)} handler Function called when the event fires. */ function addOneShotEventListener(node, name, handler) { var f = function(e) { handler(e); node.removeEventListener(name, f); }; node.addEventListener(name, f); } // Get the localized strings from the backend via bookmakrManagerPrivate API. function loadLocalizedStrings(data) { // The strings may contain & which we need to strip. for (var key in data) { data[key] = data[key].replace(/&/, ''); } loadTimeData.data = data; i18nTemplate.process(document, loadTimeData); recentTreeItem.label = loadTimeData.getString('recent'); searchTreeItem.label = loadTimeData.getString('search'); searchTreeItem.icon = isRTL() ? 'images/bookmark_manager_search_rtl.png' : 'images/bookmark_manager_search.png'; } /** * Updates the location hash to reflect the current state of the application. */ function updateHash() { window.location.hash = tree.selectedItem.bookmarkId; } /** * Navigates to a bookmark ID. * @param {string} id The ID to navigate to. * @param {function()} callback Function called when list view loaded or * displayed specified folder. */ function navigateTo(id, callback) { if (list.parentId == id) { callback(); return; } addOneShotEventListener(list, 'load', callback); updateParentId(id); } /** * Updates the parent ID of the bookmark list and selects the correct tree item. * @param {string} id The id. */ function updateParentId(id) { // Setting list.parentId fires 'load' event. list.parentId = id; // When tree.selectedItem changed, tree view calls navigatTo() then it // calls updateHash() when list view displayed specified folder. tree.selectedItem = bmm.treeLookup[id] || tree.selectedItem; } // Process the location hash. This is called by onhashchange and when the page // is first loaded. function processHash() { var id = window.location.hash.slice(1); if (!id) { // If we do not have a hash, select first item in the tree. id = tree.items[0].bookmarkId; } var valid = false; if (/^e=/.test(id)) { id = id.slice(2); // If hash contains e=, edit the item specified. chrome.bookmarks.get(id, function(bookmarkNodes) { // Verify the node to edit is a valid node. if (!bookmarkNodes || bookmarkNodes.length != 1) return; var bookmarkNode = bookmarkNodes[0]; // After the list reloads, edit the desired bookmark. var editBookmark = function(e) { var index = list.dataModel.findIndexById(bookmarkNode.id); if (index != -1) { var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; scrollIntoViewAndMakeEditable(index); } }; navigateTo(bookmarkNode.parentId, editBookmark); }); // We handle the two cases of navigating to the bookmark to be edited // above. Don't run the standard navigation code below. return; } else if (/^q=/.test(id)) { // In case we got a search hash, update the text input and the // bmm.treeLookup to use the new id. setSearch(id.slice(2)); valid = true; } else if (id == 'recent') { valid = true; } // Navigate to bookmark 'id' (which may be a query of the form q=query). if (valid) { updateParentId(id); } else { // We need to verify that this is a correct ID. chrome.bookmarks.get(id, function(items) { if (items && items.length == 1) updateParentId(id); }); } } // Activate is handled by the open-in-same-window-command. function handleDoubleClickForList(e) { if (e.button == 0) $('open-in-same-window-command').execute(); } // The list dispatches an event when the user clicks on the URL or the Show in // folder part. function handleUrlClickedForList(e) { getLinkController().openUrlFromEvent(e.url, e.originalEvent); chrome.bookmarkManagerPrivate.recordLaunch(); } function handleSearch(e) { setSearch(this.value); } /** * Navigates to the search results for the search text. * @param {string} searchText The text to search for. */ function setSearch(searchText) { if (searchText) { // Only update search item if we have a search term. We never want the // search item to be for an empty search. delete bmm.treeLookup[searchTreeItem.bookmarkId]; var id = searchTreeItem.bookmarkId = 'q=' + searchText; bmm.treeLookup[searchTreeItem.bookmarkId] = searchTreeItem; } var input = $('term'); // Do not update the input if the user is actively using the text input. if (document.activeElement != input) input.value = searchText; if (searchText) { tree.add(searchTreeItem); tree.selectedItem = searchTreeItem; } else { // Go "home". tree.selectedItem = tree.items[0]; id = tree.selectedItem.bookmarkId; } // Navigate now and update hash immediately. navigateTo(id, updateHash); } // Handle the logo button UI. // When the user clicks the button we should navigate "home" and focus the list. function handleClickOnLogoButton(e) { setSearch(''); $('list').focus(); } /** * This returns the user visible path to the folder where the bookmark is * located. * @param {number} parentId The ID of the parent folder. * @return {string} The path to the the bookmark, */ function getFolder(parentId) { var parentNode = tree.getBookmarkNodeById(parentId); if (parentNode) { var s = parentNode.title; if (parentNode.parentId != bmm.ROOT_ID) { return getFolder(parentNode.parentId) + '/' + s; } return s; } } function handleLoadForTree(e) { // Add hard coded tree items. tree.add(recentTreeItem); processHash(); } /** * Helper function that updates the canExecute and labels for the open-like * commands. * @param {!cr.ui.CanExecuteEvent} e The event fired by the command system. * @param {!cr.ui.Command} command The command we are currently processing. */ function updateOpenCommands(e, command) { var selectedItems = getSelectedBookmarkNodes(e.target); var isFolder = selectedItems.length == 1 && bmm.isFolder(selectedItems[0]); var multiple = selectedItems.length != 1 || isFolder; function hasBookmarks(node) { for (var i = 0; i < node.children.length; i++) { if (!bmm.isFolder(node.children[i])) return true; } return false; } var commandDisabled = false; switch (command.id) { case 'open-in-new-tab-command': command.label = loadTimeData.getString(multiple ? 'open_all' : 'open_in_new_tab'); break; case 'open-in-new-window-command': command.label = loadTimeData.getString(multiple ? 'open_all_new_window' : 'open_in_new_window'); // Disabled when incognito is forced. commandDisabled = incognitoModeAvailability == 'forced' || !canOpenNewWindows; break; case 'open-incognito-window-command': command.label = loadTimeData.getString(multiple ? 'open_all_incognito' : 'open_incognito'); // Not available withn incognito is disabled. commandDisabled = incognitoModeAvailability == 'disabled'; break; } e.canExecute = selectedItems.length > 0 && !commandDisabled; if (isFolder && e.canExecute) { // We need to get all the bookmark items in this tree. If the tree does not // contain any non-folders, we need to disable the command. var p = bmm.loadSubtree(selectedItems[0].id); p.addListener(function(node) { command.disabled = !node || !hasBookmarks(node); }); } } /** * Calls the backend to figure out if we can paste the clipboard into the active * folder. * @param {Function=} opt_f Function to call after the state has been updated. */ function updatePasteCommand(opt_f) { function update(canPaste) { var organizeMenuCommand = $('paste-from-organize-menu-command'); var contextMenuCommand = $('paste-from-context-menu-command'); organizeMenuCommand.disabled = !canPaste; contextMenuCommand.disabled = !canPaste; if (opt_f) opt_f(); } // We cannot paste into search and recent view. if (list.isSearch() || list.isRecent()) { update(false); } else { chrome.bookmarkManagerPrivate.canPaste(list.parentId, update); } } function handleCanExecuteForDocument(e) { var command = e.command; switch (command.id) { case 'import-menu-command': e.canExecute = canEdit; break; case 'export-menu-command': // We can always execute the export-menu command. e.canExecute = true; break; case 'sort-command': e.canExecute = !list.isRecent() && !list.isSearch() && list.dataModel.length > 1; break; case 'undo-command': // The global undo command has no visible UI, so always enable it, and // just make it a no-op if undo is not possible. e.canExecute = true; break; default: canExecuteForList(e); break; } } /** * Helper function for handling canExecute for the list and the tree. * @param {!Event} e Can execute event object. * @param {boolean} isRecentOrSearch Whether the user is trying to do a command * on recent or search. */ function canExecuteShared(e, isRecentOrSearch) { var command = e.command; var commandId = command.id; switch (commandId) { case 'paste-from-organize-menu-command': case 'paste-from-context-menu-command': updatePasteCommand(); break; case 'add-new-bookmark-command': case 'new-folder-command': e.canExecute = !isRecentOrSearch && canEdit; break; case 'open-in-new-tab-command': case 'open-in-background-tab-command': case 'open-in-new-window-command': case 'open-incognito-window-command': updateOpenCommands(e, command); break; case 'undo-delete-command': e.canExecute = !!lastDeletedNodes; break; } } /** * Helper function for handling canExecute for the list and document. * @param {!Event} e Can execute event object. */ function canExecuteForList(e) { var command = e.command; var commandId = command.id; function hasSelected() { return !!list.selectedItem; } function hasSingleSelected() { return list.selectedItems.length == 1; } function canCopyItem(item) { return item.id != 'new'; } function canCopyItems() { var selectedItems = list.selectedItems; return selectedItems && selectedItems.some(canCopyItem); } function isRecentOrSearch() { return list.isRecent() || list.isSearch(); } switch (commandId) { case 'rename-folder-command': // Show rename if a single folder is selected. var items = list.selectedItems; if (items.length != 1) { e.canExecute = false; command.hidden = true; } else { var isFolder = bmm.isFolder(items[0]); e.canExecute = isFolder && canEdit; command.hidden = !isFolder; } break; case 'edit-command': // Show the edit command if not a folder. var items = list.selectedItems; if (items.length != 1) { e.canExecute = false; command.hidden = false; } else { var isFolder = bmm.isFolder(items[0]); e.canExecute = !isFolder && canEdit; command.hidden = isFolder; } break; case 'show-in-folder-command': e.canExecute = isRecentOrSearch() && hasSingleSelected(); break; case 'delete-command': case 'cut-command': e.canExecute = canCopyItems() && canEdit; break; case 'copy-command': e.canExecute = canCopyItems(); break; case 'open-in-same-window-command': e.canExecute = hasSelected(); break; default: canExecuteShared(e, isRecentOrSearch()); } } // Update canExecute for the commands when the list is the active element. function handleCanExecuteForList(e) { if (e.target != list) return; canExecuteForList(e); } // Update canExecute for the commands when the tree is the active element. function handleCanExecuteForTree(e) { if (e.target != tree) return; var command = e.command; var commandId = command.id; function hasSelected() { return !!e.target.selectedItem; } function isRecentOrSearch() { var item = e.target.selectedItem; return item == recentTreeItem || item == searchTreeItem; } function isTopLevelItem() { return e.target.selectedItem.parentNode == tree; } switch (commandId) { case 'rename-folder-command': command.hidden = false; e.canExecute = hasSelected() && !isTopLevelItem() && canEdit; break; case 'edit-command': command.hidden = true; e.canExecute = false; break; case 'delete-command': case 'cut-command': e.canExecute = hasSelected() && !isTopLevelItem() && canEdit; break; case 'copy-command': e.canExecute = hasSelected() && !isTopLevelItem(); break; default: canExecuteShared(e, isRecentOrSearch()); } } /** * Update the canExecute state of the commands when the selection changes. * @param {Event} e The change event object. */ function updateCommandsBasedOnSelection(e) { if (e.target == document.activeElement) { // Paste only needs to be updated when the tree selection changes. var commandNames = ['copy', 'cut', 'delete', 'rename-folder', 'edit', 'add-new-bookmark', 'new-folder', 'open-in-new-tab', 'open-in-new-window', 'open-incognito-window', 'open-in-same-window', 'show-in-folder']; if (e.target == tree) { commandNames.push('paste-from-context-menu', 'paste-from-organize-menu', 'sort'); } commandNames.forEach(function(baseId) { $(baseId + '-command').canExecuteChange(); }); } } function updateEditingCommands() { var editingCommands = ['cut', 'delete', 'rename-folder', 'edit', 'add-new-bookmark', 'new-folder', 'sort', 'paste-from-context-menu', 'paste-from-organize-menu']; chrome.bookmarkManagerPrivate.canEdit(function(result) { if (result != canEdit) { canEdit = result; editingCommands.forEach(function(baseId) { $(baseId + '-command').canExecuteChange(); }); } }); } function handleChangeForTree(e) { updateCommandsBasedOnSelection(e); navigateTo(tree.selectedItem.bookmarkId, updateHash); } function handleOrganizeButtonClick(e) { updateEditingCommands(); $('add-new-bookmark-command').canExecuteChange(); $('new-folder-command').canExecuteChange(); $('sort-command').canExecuteChange(); } function handleRename(e) { var item = e.target; var bookmarkNode = item.bookmarkNode; chrome.bookmarks.update(bookmarkNode.id, {title: item.label}); performGlobalUndo = null; // This can't be undone, so disable global undo. } function handleEdit(e) { var item = e.target; var bookmarkNode = item.bookmarkNode; var context = { title: bookmarkNode.title }; if (!bmm.isFolder(bookmarkNode)) context.url = bookmarkNode.url; if (bookmarkNode.id == 'new') { selectItemsAfterUserAction(list); // New page context.parentId = bookmarkNode.parentId; chrome.bookmarks.create(context, function(node) { // A new node was created and will get added to the list due to the // handler. var dataModel = list.dataModel; var index = dataModel.indexOf(bookmarkNode); dataModel.splice(index, 1); // Select new item. var newIndex = dataModel.findIndexById(node.id); if (newIndex != -1) { var sm = list.selectionModel; list.scrollIndexIntoView(newIndex); sm.leadIndex = sm.anchorIndex = sm.selectedIndex = newIndex; } }); } else { // Edit chrome.bookmarks.update(bookmarkNode.id, context); } performGlobalUndo = null; // This can't be undone, so disable global undo. } function handleCancelEdit(e) { var item = e.target; var bookmarkNode = item.bookmarkNode; if (bookmarkNode.id == 'new') { var dataModel = list.dataModel; var index = dataModel.findIndexById('new'); dataModel.splice(index, 1); } } /** * Navigates to the folder that the selected item is in and selects it. This is * used for the show-in-folder command. */ function showInFolder() { var bookmarkNode = list.selectedItem; if (!bookmarkNode) return; var parentId = bookmarkNode.parentId; // After the list is loaded we should select the revealed item. function selectItem() { var index = list.dataModel.findIndexById(bookmarkNode.id); if (index == -1) return; var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; list.scrollIndexIntoView(index); } var treeItem = bmm.treeLookup[parentId]; treeItem.reveal(); navigateTo(parentId, selectItem); } /** * @return {!cr.LinkController} The link controller used to open links based on * user clicks and keyboard actions. */ function getLinkController() { return linkController || (linkController = new cr.LinkController(loadTimeData)); } /** * Returns the selected bookmark nodes of the provided tree or list. * If |opt_target| is not provided or null the active element is used. * Only call this if the list or the tree is focused. * @param {BookmarkList|BookmarkTree} opt_target The target list or tree. * @return {!Array} Array of bookmark nodes. */ function getSelectedBookmarkNodes(opt_target) { return (opt_target || document.activeElement) == tree ? tree.selectedFolders : list.selectedItems; } /** * @return {!Array.<string>} An array of the selected bookmark IDs. */ function getSelectedBookmarkIds() { return getSelectedBookmarkNodes().map(function(node) { return node.id; }); } /** * Opens the selected bookmarks. * @param {LinkKind} kind The kind of link we want to open. */ function openBookmarks(kind) { // If we have selected any folders, we need to find all items recursively. // We use multiple async calls to getSubtree instead of getting the whole // tree since we would like to minimize the amount of data sent. var urls = []; // Adds the node and all its children. function addNodes(node) { if (node.children) { node.children.forEach(function(child) { if (!bmm.isFolder(child)) urls.push(child.url); }); } else { urls.push(node.url); } } var nodes = getSelectedBookmarkNodes(); // Get a future promise for every selected item. var promises = nodes.map(function(node) { if (bmm.isFolder(node)) return bmm.loadSubtree(node.id); // Not a folder so we already have all the data we need. return new Promise(node.url); }); var p = Promise.all.apply(null, promises); p.addListener(function(values) { values.forEach(function(v) { if (typeof v == 'string') urls.push(v); else addNodes(v); }); getLinkController().openUrls(urls, kind); chrome.bookmarkManagerPrivate.recordLaunch(); }); } /** * Opens an item in the list. */ function openItem() { var bookmarkNodes = getSelectedBookmarkNodes(); // If we double clicked or pressed enter on a single folder, navigate to it. if (bookmarkNodes.length == 1 && bmm.isFolder(bookmarkNodes[0])) { navigateTo(bookmarkNodes[0].id, updateHash); } else { openBookmarks(LinkKind.FOREGROUND_TAB); } } /** * Deletes the selected bookmarks. The bookmarks are saved in memory in case * the user needs to undo the deletion. */ function deleteBookmarks() { var selectedIds = getSelectedBookmarkIds(); lastDeletedNodes = []; function performDelete() { selectedIds.forEach(function(id) { chrome.bookmarks.removeTree(id); }); $('undo-delete-command').canExecuteChange(); performGlobalUndo = undoDelete; } // First, store information about the bookmarks being deleted. selectedIds.forEach(function(id) { chrome.bookmarks.getSubTree(id, function(results) { lastDeletedNodes.push(results); // When all nodes have been saved, perform the deletion. if (lastDeletedNodes.length === selectedIds.length) performDelete(); }); }); } /** * Restores a tree of bookmarks under a specified folder. * @param {BookmarkTreeNode} node The node to restore. * @param {=string} parentId The ID of the folder to restore under. If not * specified, the original parentId of the node will be used. */ function restoreTree(node, parentId) { var bookmarkInfo = { parentId: parentId || node.parentId, title: node.title, index: node.index, url: node.url }; chrome.bookmarks.create(bookmarkInfo, function(result) { if (!result) { console.error('Failed to restore bookmark.'); return; } if (node.children) { // Restore the children using the new ID for this node. node.children.forEach(function(child) { restoreTree(child, result.id); }); } }); } /** * Restores the last set of bookmarks that was deleted. */ function undoDelete() { lastDeletedNodes.forEach(function(arr) { arr.forEach(restoreTree); }); lastDeletedNodes = null; $('undo-delete-command').canExecuteChange(); // Only a single level of undo is supported, so disable global undo now. performGlobalUndo = null; } /** * Computes folder for "Add Page" and "Add Folder". * @return {string} The id of folder node where we'll create new page/folder. */ function computeParentFolderForNewItem() { if (document.activeElement == tree) return list.parentId; var selectedItem = list.selectedItem; return selectedItem && bmm.isFolder(selectedItem) ? selectedItem.id : list.parentId; } /** * Callback for rename folder and edit command. This starts editing for * selected item. */ function editSelectedItem() { if (document.activeElement == tree) { tree.selectedItem.editing = true; } else { var li = list.getListItem(list.selectedItem); if (li) li.editing = true; } } /** * Callback for the new folder command. This creates a new folder and starts * a rename of it. */ function newFolder() { performGlobalUndo = null; // This can't be undone, so disable global undo. var parentId = computeParentFolderForNewItem(); // Callback is called after tree and list data model updated. function createFolder(callback) { chrome.bookmarks.create({ title: loadTimeData.getString('new_folder_name'), parentId: parentId }, callback); } if (document.activeElement == tree) { createFolder(function(newNode) { navigateTo(newNode.id, function() { bmm.treeLookup[newNode.id].editing = true; }); }); return; } function editNewFolderInList() { createFolder(function() { var index = list.dataModel.length - 1; var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = index; scrollIntoViewAndMakeEditable(index); }); } navigateTo(parentId, editNewFolderInList); } /** * Scrolls the list item into view and makes it editable. * @param {number} index The index of the item to make editable. */ function scrollIntoViewAndMakeEditable(index) { list.scrollIndexIntoView(index); // onscroll is now dispatched asynchronously so we have to postpone // the rest. setTimeout(function() { var item = list.getListItemByIndex(index); if (item) item.editing = true; }); } /** * Adds a page to the current folder. This is called by the * add-new-bookmark-command handler. */ function addPage() { var parentId = computeParentFolderForNewItem(); function editNewBookmark() { var fakeNode = { title: '', url: '', parentId: parentId, id: 'new' }; var dataModel = list.dataModel; var length = dataModel.length; dataModel.splice(length, 0, fakeNode); var sm = list.selectionModel; sm.anchorIndex = sm.leadIndex = sm.selectedIndex = length; scrollIntoViewAndMakeEditable(length); }; navigateTo(parentId, editNewBookmark); } /** * This function is used to select items after a user action such as paste, drop * add page etc. * @param {BookmarkList|BookmarkTree} target The target of the user action. * @param {=string} opt_selectedTreeId If provided, then select that tree id. */ function selectItemsAfterUserAction(target, opt_selectedTreeId) { // We get one onCreated event per item so we delay the handling until we get // no more events coming. var ids = []; var timer; function handle(id, bookmarkNode) { clearTimeout(timer); if (opt_selectedTreeId || list.parentId == bookmarkNode.parentId) ids.push(id); timer = setTimeout(handleTimeout, 50); } function handleTimeout() { chrome.bookmarks.onCreated.removeListener(handle); chrome.bookmarks.onMoved.removeListener(handle); if (opt_selectedTreeId && ids.indexOf(opt_selectedTreeId) != -1) { var index = ids.indexOf(opt_selectedTreeId); if (index != -1 && opt_selectedTreeId in bmm.treeLookup) { tree.selectedItem = bmm.treeLookup[opt_selectedTreeId]; } } else if (target == list) { var dataModel = list.dataModel; var firstIndex = dataModel.findIndexById(ids[0]); var lastIndex = dataModel.findIndexById(ids[ids.length - 1]); if (firstIndex != -1 && lastIndex != -1) { var selectionModel = list.selectionModel; selectionModel.selectedIndex = -1; selectionModel.selectRange(firstIndex, lastIndex); selectionModel.anchorIndex = selectionModel.leadIndex = lastIndex; list.focus(); } } list.endBatchUpdates(); } list.startBatchUpdates(); chrome.bookmarks.onCreated.addListener(handle); chrome.bookmarks.onMoved.addListener(handle); timer = setTimeout(handleTimeout, 300); } /** * Record user action. * @param {string} name An user action name. */ function recordUserAction(name) { chrome.metricsPrivate.recordUserAction('BookmarkManager_Command_' + name); } /** * The currently selected bookmark, based on where the user is clicking. * @return {string} The ID of the currently selected bookmark (could be from * tree view or list view). */ function getSelectedId() { if (document.activeElement == tree) return tree.selectedItem.bookmarkId; var selectedItem = list.selectedItem; return selectedItem && bmm.isFolder(selectedItem) ? selectedItem.id : tree.selectedItem.bookmarkId; } /** * Pastes the copied/cutted bookmark into the right location depending whether * if it was called from Organize Menu or from Context Menu. * @param {string} id The id of the element being pasted from. */ function pasteBookmark(id) { recordUserAction('Paste'); selectItemsAfterUserAction(list); chrome.bookmarkManagerPrivate.paste(id, getSelectedBookmarkIds()); } /** * Handler for the command event. This is used for context menu of list/tree * and organized menu. * @param {!Event} e The event object. */ function handleCommand(e) { var command = e.command; var commandId = command.id; switch (commandId) { case 'import-menu-command': recordUserAction('Import'); chrome.bookmarks.import(); break; case 'export-menu-command': recordUserAction('Export'); chrome.bookmarks.export(); break; case 'undo-command': if (performGlobalUndo) { recordUserAction('UndoGlobal'); performGlobalUndo(); } else { recordUserAction('UndoNone'); } break; case 'show-in-folder-command': recordUserAction('ShowInFolder'); showInFolder(); break; case 'open-in-new-tab-command': case 'open-in-background-tab-command': recordUserAction('OpenInNewTab'); openBookmarks(LinkKind.BACKGROUND_TAB); break; case 'open-in-new-window-command': recordUserAction('OpenInNewWindow'); openBookmarks(LinkKind.WINDOW); break; case 'open-incognito-window-command': recordUserAction('OpenIncognito'); openBookmarks(LinkKind.INCOGNITO); break; case 'delete-command': recordUserAction('Delete'); deleteBookmarks(); break; case 'copy-command': recordUserAction('Copy'); chrome.bookmarkManagerPrivate.copy(getSelectedBookmarkIds(), updatePasteCommand); break; case 'cut-command': recordUserAction('Cut'); chrome.bookmarkManagerPrivate.cut(getSelectedBookmarkIds(), updatePasteCommand); break; case 'paste-from-organize-menu-command': pasteBookmark(list.parentId); break; case 'paste-from-context-menu-command': pasteBookmark(getSelectedId()); break; case 'sort-command': recordUserAction('Sort'); chrome.bookmarkManagerPrivate.sortChildren(list.parentId); break; case 'rename-folder-command': editSelectedItem(); break; case 'edit-command': recordUserAction('Edit'); editSelectedItem(); break; case 'new-folder-command': recordUserAction('NewFolder'); newFolder(); break; case 'add-new-bookmark-command': recordUserAction('AddPage'); addPage(); break; case 'open-in-same-window-command': recordUserAction('OpenInSame'); openItem(); break; case 'undo-delete-command': recordUserAction('UndoDelete'); undoDelete(); break; } } // Execute the copy, cut and paste commands when those events are dispatched by // the browser. This allows us to rely on the browser to handle the keyboard // shortcuts for these commands. function installEventHandlerForCommand(eventName, commandId) { function handle(e) { if (document.activeElement != list && document.activeElement != tree) return; var command = $(commandId); if (!command.disabled) { command.execute(); if (e) e.preventDefault(); // Prevent the system beep. } } if (eventName == 'paste') { // Paste is a bit special since we need to do an async call to see if we // can paste because the paste command might not be up to date. document.addEventListener(eventName, function(e) { updatePasteCommand(handle); }); } else { document.addEventListener(eventName, handle); } } function initializeSplitter() { var splitter = document.querySelector('.main > .splitter'); Splitter.decorate(splitter); // The splitter persists the size of the left component in the local store. if ('treeWidth' in localStorage) splitter.previousElementSibling.style.width = localStorage['treeWidth']; splitter.addEventListener('resize', function(e) { localStorage['treeWidth'] = splitter.previousElementSibling.style.width; }); } function initializeBookmarkManager() { // Sometimes the extension API is not initialized. if (!chrome.bookmarks) console.error('Bookmarks extension API is not available'); chrome.bookmarkManagerPrivate.getStrings(loadLocalizedStrings); bmm.treeLookup[searchTreeItem.bookmarkId] = searchTreeItem; bmm.treeLookup[recentTreeItem.bookmarkId] = recentTreeItem; cr.ui.decorate('menu', Menu); cr.ui.decorate('button[menu]', MenuButton); cr.ui.decorate('command', Command); BookmarkList.decorate(list); BookmarkTree.decorate(tree); list.addEventListener('canceledit', handleCancelEdit); list.addEventListener('canExecute', handleCanExecuteForList); list.addEventListener('change', updateCommandsBasedOnSelection); list.addEventListener('contextmenu', updateEditingCommands); list.addEventListener('dblclick', handleDoubleClickForList); list.addEventListener('edit', handleEdit); list.addEventListener('rename', handleRename); list.addEventListener('urlClicked', handleUrlClickedForList); tree.addEventListener('canExecute', handleCanExecuteForTree); tree.addEventListener('change', handleChangeForTree); tree.addEventListener('contextmenu', updateEditingCommands); tree.addEventListener('rename', handleRename); tree.addEventListener('load', handleLoadForTree); cr.ui.contextMenuHandler.addContextMenuProperty(tree); list.contextMenu = $('context-menu'); tree.contextMenu = $('context-menu'); // We listen to hashchange so that we can update the currently shown folder // when // the user goes back and forward in the history. window.addEventListener('hashchange', processHash); document.querySelector('.header form').onsubmit = function(e) { setSearch($('term').value); e.preventDefault(); }; $('term').addEventListener('search', handleSearch); document.querySelector('.summary > button').addEventListener( 'click', handleOrganizeButtonClick); document.querySelector('button.logo').addEventListener( 'click', handleClickOnLogoButton); document.addEventListener('canExecute', handleCanExecuteForDocument); document.addEventListener('command', handleCommand); // Listen to copy, cut and paste events and execute the associated commands. installEventHandlerForCommand('copy', 'copy-command'); installEventHandlerForCommand('cut', 'cut-command'); installEventHandlerForCommand('paste', 'paste-from-organize-menu-command'); // Install shortcuts for (var name in commandShortcutMap) { $(name + '-command').shortcut = commandShortcutMap[name]; } // Disable almost all commands at startup. var commands = document.querySelectorAll('command'); for (var i = 0, command; command = commands[i]; ++i) { if (command.id != 'import-menu-command' && command.id != 'export-menu-command') { command.disabled = true; } } chrome.bookmarkManagerPrivate.canEdit(function(result) { canEdit = result; }); chrome.systemPrivate.getIncognitoModeAvailability(function(result) { // TODO(rustema): propagate policy value to the bookmark manager when it // changes. incognitoModeAvailability = result; }); chrome.bookmarkManagerPrivate.canOpenNewWindows(function(result) { canOpenNewWindows = result; }); initializeSplitter(); bmm.addBookmarkModelListeners(); dnd.init(selectItemsAfterUserAction); tree.reload(); } initializeBookmarkManager(); })();
In the bookmark manager, right clicking on an empty in the bookmark list should allow all displayed bookmarks to be opened. In the scenario where the user has initiated the context menu in the bookmark list without any bookmarks selection the target bookmarks for open commands will be the entire contents of the Bookmark List (the folder selected). The change involves modifying the |canExecute| and the |handleCommand| so that the entire list is considered in the above scenario. Note that the menu items that are actionable are only the 'Open all...' commands and not 'Cut', 'Copy', and 'Delete'. BUG=225005 TEST=Follow reproductions steps; right click on a blank area of the Bookmark List to see the now actionable 'Open all..." command and that they indeed launch the proper bookmarks. There is a (seemingly) unrelated feature that uses the modified code and that is double clicking on a bookmark or selecting bookmark(s) and pressing enter. These actions should remain unchanged. Review URL: https://chromiumcodereview.appspot.com/13373002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@193704 0039d316-1c4b-4281-b951-d872f2087c98
chrome/browser/resources/bookmark_manager/js/main.js
In the bookmark manager, right clicking on an empty in the bookmark list should allow all displayed bookmarks to be opened.
<ide><path>hrome/browser/resources/bookmark_manager/js/main.js <ide> } <ide> <ide> /** <add> * Returns the bookmark nodes that should be opened through the open context <add> * menu commands. <add> * @param {HTMLElement} target The target list or tree. <add> * @return {!Array.<!BookmarkTreeNode>} . <add> */ <add>function getBookmarkNodesForOpenCommands(target) { <add> if (target == tree) <add> return tree.selectedFolders; <add> var listItems = list.selectedItems; <add> return listItems.length ? listItems : list.dataModel.slice(); <add>} <add> <add>/** <ide> * Helper function that updates the canExecute and labels for the open-like <ide> * commands. <ide> * @param {!cr.ui.CanExecuteEvent} e The event fired by the command system. <ide> * @param {!cr.ui.Command} command The command we are currently processing. <ide> */ <ide> function updateOpenCommands(e, command) { <del> var selectedItems = getSelectedBookmarkNodes(e.target); <add> var selectedItems = getBookmarkNodesForOpenCommands(e.target); <ide> var isFolder = selectedItems.length == 1 && bmm.isFolder(selectedItems[0]); <ide> var multiple = selectedItems.length != 1 || isFolder; <ide> <ide> /** <ide> * Opens the selected bookmarks. <ide> * @param {LinkKind} kind The kind of link we want to open. <del> */ <del>function openBookmarks(kind) { <add> * @param {HTMLElement} opt_eventTarget The target of the user initiated event. <add> */ <add>function openBookmarks(kind, opt_eventTarget) { <ide> // If we have selected any folders, we need to find all items recursively. <ide> // We use multiple async calls to getSubtree instead of getting the whole <ide> // tree since we would like to minimize the amount of data sent. <ide> } <ide> } <ide> <del> var nodes = getSelectedBookmarkNodes(); <add> var nodes = getBookmarkNodesForOpenCommands(opt_eventTarget); <ide> <ide> // Get a future promise for every selected item. <ide> var promises = nodes.map(function(node) { <ide> case 'open-in-new-tab-command': <ide> case 'open-in-background-tab-command': <ide> recordUserAction('OpenInNewTab'); <del> openBookmarks(LinkKind.BACKGROUND_TAB); <add> openBookmarks(LinkKind.BACKGROUND_TAB, e.target); <ide> break; <ide> case 'open-in-new-window-command': <ide> recordUserAction('OpenInNewWindow'); <del> openBookmarks(LinkKind.WINDOW); <add> openBookmarks(LinkKind.WINDOW, e.target); <ide> break; <ide> case 'open-incognito-window-command': <ide> recordUserAction('OpenIncognito'); <del> openBookmarks(LinkKind.INCOGNITO); <add> openBookmarks(LinkKind.INCOGNITO, e.target); <ide> break; <ide> case 'delete-command': <ide> recordUserAction('Delete');
Java
apache-2.0
786d965992687a878b11557e1eca036adcf493f9
0
brettwooldridge/buck,JoelMarcey/buck,romanoid/buck,rmaz/buck,zpao/buck,Addepar/buck,romanoid/buck,brettwooldridge/buck,kageiit/buck,brettwooldridge/buck,facebook/buck,rmaz/buck,SeleniumHQ/buck,SeleniumHQ/buck,JoelMarcey/buck,romanoid/buck,brettwooldridge/buck,Addepar/buck,nguyentruongtho/buck,zpao/buck,zpao/buck,rmaz/buck,brettwooldridge/buck,zpao/buck,kageiit/buck,SeleniumHQ/buck,brettwooldridge/buck,kageiit/buck,SeleniumHQ/buck,SeleniumHQ/buck,romanoid/buck,facebook/buck,brettwooldridge/buck,rmaz/buck,facebook/buck,Addepar/buck,JoelMarcey/buck,brettwooldridge/buck,rmaz/buck,JoelMarcey/buck,SeleniumHQ/buck,SeleniumHQ/buck,SeleniumHQ/buck,Addepar/buck,SeleniumHQ/buck,JoelMarcey/buck,rmaz/buck,nguyentruongtho/buck,romanoid/buck,Addepar/buck,kageiit/buck,Addepar/buck,JoelMarcey/buck,rmaz/buck,rmaz/buck,rmaz/buck,Addepar/buck,facebook/buck,nguyentruongtho/buck,nguyentruongtho/buck,zpao/buck,shs96c/buck,romanoid/buck,shs96c/buck,Addepar/buck,shs96c/buck,kageiit/buck,JoelMarcey/buck,zpao/buck,romanoid/buck,JoelMarcey/buck,shs96c/buck,SeleniumHQ/buck,JoelMarcey/buck,rmaz/buck,shs96c/buck,brettwooldridge/buck,romanoid/buck,brettwooldridge/buck,shs96c/buck,shs96c/buck,nguyentruongtho/buck,shs96c/buck,romanoid/buck,SeleniumHQ/buck,shs96c/buck,kageiit/buck,romanoid/buck,romanoid/buck,rmaz/buck,Addepar/buck,rmaz/buck,Addepar/buck,nguyentruongtho/buck,shs96c/buck,kageiit/buck,JoelMarcey/buck,facebook/buck,shs96c/buck,Addepar/buck,JoelMarcey/buck,facebook/buck,rmaz/buck,brettwooldridge/buck,nguyentruongtho/buck,brettwooldridge/buck,romanoid/buck,SeleniumHQ/buck,SeleniumHQ/buck,brettwooldridge/buck,Addepar/buck,shs96c/buck,JoelMarcey/buck,Addepar/buck,JoelMarcey/buck,zpao/buck,romanoid/buck,shs96c/buck,facebook/buck
/* * Copyright 2015-present Facebook, 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.facebook.buck.parser; import com.facebook.buck.core.cell.Cell; import com.facebook.buck.core.description.attr.ImplicitFlavorsInferringDescription; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.Flavor; import com.facebook.buck.core.model.HasDefaultFlavors; import com.facebook.buck.core.model.impl.ImmutableBuildTarget; import com.facebook.buck.core.model.targetgraph.TargetGraph; import com.facebook.buck.core.model.targetgraph.TargetGraphAndBuildTargets; import com.facebook.buck.core.model.targetgraph.TargetNode; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal; import com.facebook.buck.graph.GraphTraversable; import com.facebook.buck.graph.MutableDirectedGraph; import com.facebook.buck.log.Logger; import com.facebook.buck.parser.exceptions.BuildFileParseException; import com.facebook.buck.parser.exceptions.BuildTargetException; import com.facebook.buck.parser.exceptions.MissingBuildFileException; import com.facebook.buck.rules.coercer.TypeCoercerFactory; import com.facebook.buck.util.MoreMaps; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.Nullable; /** * High-level build file parsing machinery. Primarily responsible for producing a {@link * TargetGraph} based on a set of targets. Caches build rules to minimise the number of calls to * python and processes filesystem WatchEvents to invalidate the cache as files change. */ public class DefaultParser implements Parser { private static final Logger LOG = Logger.get(Parser.class); private final PerBuildStateFactory perBuildStateFactory; private final DaemonicParserState permState; private final TargetSpecResolver targetSpecResolver; public DefaultParser( PerBuildStateFactory perBuildStateFactory, ParserConfig parserConfig, TypeCoercerFactory typeCoercerFactory, TargetSpecResolver targetSpecResolver) { this.perBuildStateFactory = perBuildStateFactory; this.permState = new DaemonicParserState( typeCoercerFactory, parserConfig.getNumParsingThreads(), parserConfig.shouldIgnoreEnvironmentVariablesChanges()); this.targetSpecResolver = targetSpecResolver; } @Override public DaemonicParserState getPermState() { return permState; } @VisibleForTesting static ImmutableSet<Map<String, Object>> getTargetNodeRawAttributes( PerBuildState state, Cell cell, Path buildFile) throws BuildFileParseException { Preconditions.checkState(buildFile.isAbsolute()); Preconditions.checkState(buildFile.startsWith(cell.getRoot())); return state.getAllRawNodes(cell, buildFile); } @Override public ImmutableSet<TargetNode<?>> getAllTargetNodes( BuckEventBus eventBus, Cell cell, boolean enableProfiling, ListeningExecutorService executor, Path buildFile) throws BuildFileParseException { Preconditions.checkState( buildFile.isAbsolute(), "Build file should be referred to using an absolute path: %s", buildFile); Preconditions.checkState( buildFile.startsWith(cell.getRoot()), "Roots do not match %s -> %s", cell.getRoot(), buildFile); try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, cell, enableProfiling, SpeculativeParsing.ENABLED)) { return state.getAllTargetNodes(cell, buildFile); } } @Override public TargetNode<?> getTargetNode( BuckEventBus eventBus, Cell cell, boolean enableProfiling, ListeningExecutorService executor, BuildTarget target) throws BuildFileParseException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, cell, enableProfiling, SpeculativeParsing.DISABLED)) { return state.getTargetNode(target); } } @Override public TargetNode<?> getTargetNode(PerBuildState perBuildState, BuildTarget target) throws BuildFileParseException { return perBuildState.getTargetNode(target); } @Override public ListenableFuture<TargetNode<?>> getTargetNodeJob( PerBuildState perBuildState, BuildTarget target) throws BuildTargetException { return perBuildState.getTargetNodeJob(target); } @Nullable @Override public SortedMap<String, Object> getTargetNodeRawAttributes( PerBuildState state, Cell cell, TargetNode<?> targetNode) throws BuildFileParseException { try { Cell owningCell = cell.getCell(targetNode.getBuildTarget()); ImmutableSet<Map<String, Object>> allRawNodes = getTargetNodeRawAttributes( state, owningCell, cell.getAbsolutePathToBuildFile(targetNode.getBuildTarget())); String shortName = targetNode.getBuildTarget().getShortName(); for (Map<String, Object> rawNode : allRawNodes) { if (shortName.equals(rawNode.get("name"))) { SortedMap<String, Object> toReturn = new TreeMap<>(rawNode); toReturn.put( "buck.direct_dependencies", targetNode .getParseDeps() .stream() .map(Object::toString) .collect(ImmutableList.toImmutableList())); return toReturn; } } } catch (MissingBuildFileException e) { throw new RuntimeException("Deeply unlikely to be true: the cell is missing: " + targetNode); } return null; } /** * @deprecated Prefer {@link #getTargetNodeRawAttributes(PerBuildState, Cell, TargetNode)} and * reusing a PerBuildState instance, especially when calling in a loop. */ @Nullable @Deprecated @Override public SortedMap<String, Object> getTargetNodeRawAttributes( BuckEventBus eventBus, Cell cell, boolean enableProfiling, ListeningExecutorService executor, TargetNode<?> targetNode) throws BuildFileParseException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, cell, enableProfiling, SpeculativeParsing.DISABLED)) { return getTargetNodeRawAttributes(state, cell, targetNode); } } private RuntimeException propagateRuntimeCause(RuntimeException e) throws IOException, InterruptedException, BuildFileParseException { Throwables.throwIfInstanceOf(e, HumanReadableException.class); Throwable t = e.getCause(); if (t != null) { Throwables.throwIfInstanceOf(t, IOException.class); Throwables.throwIfInstanceOf(t, InterruptedException.class); Throwables.throwIfInstanceOf(t, BuildFileParseException.class); Throwables.throwIfInstanceOf(t, BuildTargetException.class); } return e; } @Override public TargetGraph buildTargetGraph( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<BuildTarget> toExplore) throws IOException, InterruptedException, BuildFileParseException { if (Iterables.isEmpty(toExplore)) { return TargetGraph.EMPTY; } try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, rootCell, enableProfiling, SpeculativeParsing.ENABLED)) { return buildTargetGraph(state, eventBus, toExplore); } } private TargetGraph buildTargetGraph( PerBuildState state, BuckEventBus eventBus, Iterable<BuildTarget> toExplore) throws IOException, InterruptedException, BuildFileParseException { if (Iterables.isEmpty(toExplore)) { return TargetGraph.EMPTY; } MutableDirectedGraph<TargetNode<?>> graph = new MutableDirectedGraph<>(); Map<BuildTarget, TargetNode<?>> index = new HashMap<>(); ParseEvent.Started parseStart = ParseEvent.started(toExplore); eventBus.post(parseStart); GraphTraversable<BuildTarget> traversable = target -> { TargetNode<?> node; try { node = state.getTargetNode(target); } catch (BuildFileParseException e) { throw new RuntimeException(e); } // this second lookup loop may *seem* pointless, but it allows us to report which node is // referring to a node we can't find - something that's very difficult in this Traversable // visitor pattern otherwise. // it's also work we need to do anyways. the getTargetNode() result is cached, so that // when we come around and re-visit that node there won't actually be any work performed. for (BuildTarget dep : node.getParseDeps()) { try { state.getTargetNode(dep); } catch (BuildFileParseException e) { throw ParserMessages.createReadableExceptionWithWhenSuffix(target, dep, e); } catch (HumanReadableException e) { throw ParserMessages.createReadableExceptionWithWhenSuffix(target, dep, e); } } return node.getParseDeps().iterator(); }; AcyclicDepthFirstPostOrderTraversal<BuildTarget> targetNodeTraversal = new AcyclicDepthFirstPostOrderTraversal<>(traversable); TargetGraph targetGraph = null; try { for (BuildTarget target : targetNodeTraversal.traverse(toExplore)) { TargetNode<?> targetNode = state.getTargetNode(target); Preconditions.checkNotNull(targetNode, "No target node found for %s", target); graph.addNode(targetNode); MoreMaps.putCheckEquals(index, target, targetNode); if (target.isFlavored()) { BuildTarget unflavoredTarget = ImmutableBuildTarget.of(target.getUnflavoredBuildTarget()); MoreMaps.putCheckEquals(index, unflavoredTarget, state.getTargetNode(unflavoredTarget)); } for (BuildTarget dep : targetNode.getParseDeps()) { graph.addEdge(targetNode, state.getTargetNode(dep)); } } targetGraph = new TargetGraph(graph, ImmutableMap.copyOf(index)); return targetGraph; } catch (AcyclicDepthFirstPostOrderTraversal.CycleException e) { throw new HumanReadableException(e.getMessage()); } catch (RuntimeException e) { throw propagateRuntimeCause(e); } finally { eventBus.post( ParseEvent.finished( parseStart, state.getParseProcessedBytes(), Optional.ofNullable(targetGraph))); } } /** * @param eventBus used to log events while parsing. * @param targetNodeSpecs the specs representing the build targets to generate a target graph for. * @return the target graph containing the build targets and their related targets. */ @Override public synchronized TargetGraphAndBuildTargets buildTargetGraphForTargetNodeSpecs( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<? extends TargetNodeSpec> targetNodeSpecs) throws BuildFileParseException, IOException, InterruptedException { return buildTargetGraphForTargetNodeSpecs( eventBus, rootCell, enableProfiling, executor, targetNodeSpecs, ParserConfig.ApplyDefaultFlavorsMode.DISABLED); } /** * @param eventBus used to log events while parsing. * @param targetNodeSpecs the specs representing the build targets to generate a target graph for. * @return the target graph containing the build targets and their related targets. */ @Override public synchronized TargetGraphAndBuildTargets buildTargetGraphForTargetNodeSpecs( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<? extends TargetNodeSpec> targetNodeSpecs, ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) throws BuildFileParseException, IOException, InterruptedException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, rootCell, enableProfiling, SpeculativeParsing.ENABLED)) { ImmutableSet<BuildTarget> buildTargets = ImmutableSet.copyOf( Iterables.concat( targetSpecResolver.resolveTargetSpecs( eventBus, rootCell, targetNodeSpecs, (buildTarget, targetNode, targetType) -> applyDefaultFlavors( buildTarget, targetNode, targetType, applyDefaultFlavorsMode), state.getTargetNodeProviderForSpecResolver(), (spec, nodes) -> spec.filter(nodes)))); TargetGraph graph = buildTargetGraph(state, eventBus, buildTargets); return TargetGraphAndBuildTargets.builder() .setBuildTargets(buildTargets) .setTargetGraph(graph) .build(); } } @Override public String toString() { return permState.toString(); } @Override public ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<? extends TargetNodeSpec> specs, SpeculativeParsing speculativeParsing, ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) throws BuildFileParseException, InterruptedException, IOException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, rootCell, enableProfiling, speculativeParsing)) { return targetSpecResolver.resolveTargetSpecs( eventBus, rootCell, specs, (buildTarget, targetNode, targetType) -> applyDefaultFlavors(buildTarget, targetNode, targetType, applyDefaultFlavorsMode), state.getTargetNodeProviderForSpecResolver(), (spec, nodes) -> spec.filter(nodes)); } } @VisibleForTesting static BuildTarget applyDefaultFlavors( BuildTarget target, Optional<TargetNode<?>> targetNode, TargetNodeSpec.TargetType targetType, ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) { if (target.isFlavored() || !targetNode.isPresent() || (targetType == TargetNodeSpec.TargetType.MULTIPLE_TARGETS && applyDefaultFlavorsMode == ParserConfig.ApplyDefaultFlavorsMode.SINGLE) || applyDefaultFlavorsMode == ParserConfig.ApplyDefaultFlavorsMode.DISABLED) { return target; } TargetNode<?> node = targetNode.get(); ImmutableSortedSet<Flavor> defaultFlavors = ImmutableSortedSet.of(); if (node.getConstructorArg() instanceof HasDefaultFlavors) { defaultFlavors = ((HasDefaultFlavors) node.getConstructorArg()).getDefaultFlavors(); LOG.debug("Got default flavors %s from args of %s", defaultFlavors, target); } if (node.getDescription() instanceof ImplicitFlavorsInferringDescription) { defaultFlavors = ((ImplicitFlavorsInferringDescription) node.getDescription()) .addImplicitFlavors(defaultFlavors); LOG.debug("Got default flavors %s from description of %s", defaultFlavors, target); } return target.withFlavors(defaultFlavors); } @Override public void register(EventBus eventBus) { eventBus.register(permState); } }
src/com/facebook/buck/parser/DefaultParser.java
/* * Copyright 2015-present Facebook, 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.facebook.buck.parser; import com.facebook.buck.core.cell.Cell; import com.facebook.buck.core.description.attr.ImplicitFlavorsInferringDescription; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.Flavor; import com.facebook.buck.core.model.HasDefaultFlavors; import com.facebook.buck.core.model.impl.ImmutableBuildTarget; import com.facebook.buck.core.model.targetgraph.TargetGraph; import com.facebook.buck.core.model.targetgraph.TargetGraphAndBuildTargets; import com.facebook.buck.core.model.targetgraph.TargetNode; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.graph.AcyclicDepthFirstPostOrderTraversal; import com.facebook.buck.graph.GraphTraversable; import com.facebook.buck.graph.MutableDirectedGraph; import com.facebook.buck.log.Logger; import com.facebook.buck.parser.exceptions.BuildFileParseException; import com.facebook.buck.parser.exceptions.BuildTargetException; import com.facebook.buck.parser.exceptions.MissingBuildFileException; import com.facebook.buck.rules.coercer.TypeCoercerFactory; import com.facebook.buck.util.MoreMaps; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.Nullable; /** * High-level build file parsing machinery. Primarily responsible for producing a {@link * TargetGraph} based on a set of targets. Caches build rules to minimise the number of calls to * python and processes filesystem WatchEvents to invalidate the cache as files change. */ public class DefaultParser implements Parser { private static final Logger LOG = Logger.get(Parser.class); private final PerBuildStateFactory perBuildStateFactory; private final DaemonicParserState permState; private final TargetSpecResolver targetSpecResolver; public DefaultParser( PerBuildStateFactory perBuildStateFactory, ParserConfig parserConfig, TypeCoercerFactory typeCoercerFactory, TargetSpecResolver targetSpecResolver) { this.perBuildStateFactory = perBuildStateFactory; this.permState = new DaemonicParserState( typeCoercerFactory, parserConfig.getNumParsingThreads(), parserConfig.shouldIgnoreEnvironmentVariablesChanges()); this.targetSpecResolver = targetSpecResolver; } @Override public DaemonicParserState getPermState() { return permState; } @VisibleForTesting static ImmutableSet<Map<String, Object>> getTargetNodeRawAttributes( PerBuildState state, Cell cell, Path buildFile) throws BuildFileParseException { Preconditions.checkState(buildFile.isAbsolute()); Preconditions.checkState(buildFile.startsWith(cell.getRoot())); return state.getAllRawNodes(cell, buildFile); } @Override public ImmutableSet<TargetNode<?>> getAllTargetNodes( BuckEventBus eventBus, Cell cell, boolean enableProfiling, ListeningExecutorService executor, Path buildFile) throws BuildFileParseException { Preconditions.checkState( buildFile.isAbsolute(), "Build file should be referred to using an absolute path: %s", buildFile); Preconditions.checkState( buildFile.startsWith(cell.getRoot()), "Roots do not match %s -> %s", cell.getRoot(), buildFile); try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, cell, enableProfiling, SpeculativeParsing.ENABLED)) { return state.getAllTargetNodes(cell, buildFile); } } @Override public TargetNode<?> getTargetNode( BuckEventBus eventBus, Cell cell, boolean enableProfiling, ListeningExecutorService executor, BuildTarget target) throws BuildFileParseException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, cell, enableProfiling, SpeculativeParsing.DISABLED)) { return state.getTargetNode(target); } } @Override public TargetNode<?> getTargetNode(PerBuildState perBuildState, BuildTarget target) throws BuildFileParseException { return perBuildState.getTargetNode(target); } @Override public ListenableFuture<TargetNode<?>> getTargetNodeJob( PerBuildState perBuildState, BuildTarget target) throws BuildTargetException { return perBuildState.getTargetNodeJob(target); } @Nullable @Override public SortedMap<String, Object> getTargetNodeRawAttributes( PerBuildState state, Cell cell, TargetNode<?> targetNode) throws BuildFileParseException { try { Cell owningCell = cell.getCell(targetNode.getBuildTarget()); ImmutableSet<Map<String, Object>> allRawNodes = getTargetNodeRawAttributes( state, owningCell, cell.getAbsolutePathToBuildFile(targetNode.getBuildTarget())); String shortName = targetNode.getBuildTarget().getShortName(); for (Map<String, Object> rawNode : allRawNodes) { if (shortName.equals(rawNode.get("name"))) { SortedMap<String, Object> toReturn = new TreeMap<>(); toReturn.putAll(rawNode); toReturn.put( "buck.direct_dependencies", targetNode .getParseDeps() .stream() .map(Object::toString) .collect(ImmutableList.toImmutableList())); return toReturn; } } } catch (MissingBuildFileException e) { throw new RuntimeException("Deeply unlikely to be true: the cell is missing: " + targetNode); } return null; } /** * @deprecated Prefer {@link #getTargetNodeRawAttributes(PerBuildState, Cell, TargetNode)} and * reusing a PerBuildState instance, especially when calling in a loop. */ @Nullable @Deprecated @Override public SortedMap<String, Object> getTargetNodeRawAttributes( BuckEventBus eventBus, Cell cell, boolean enableProfiling, ListeningExecutorService executor, TargetNode<?> targetNode) throws BuildFileParseException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, cell, enableProfiling, SpeculativeParsing.DISABLED)) { return getTargetNodeRawAttributes(state, cell, targetNode); } } private RuntimeException propagateRuntimeCause(RuntimeException e) throws IOException, InterruptedException, BuildFileParseException { Throwables.throwIfInstanceOf(e, HumanReadableException.class); Throwable t = e.getCause(); if (t != null) { Throwables.throwIfInstanceOf(t, IOException.class); Throwables.throwIfInstanceOf(t, InterruptedException.class); Throwables.throwIfInstanceOf(t, BuildFileParseException.class); Throwables.throwIfInstanceOf(t, BuildTargetException.class); } return e; } @Override public TargetGraph buildTargetGraph( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<BuildTarget> toExplore) throws IOException, InterruptedException, BuildFileParseException { if (Iterables.isEmpty(toExplore)) { return TargetGraph.EMPTY; } try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, rootCell, enableProfiling, SpeculativeParsing.ENABLED)) { return buildTargetGraph(state, eventBus, toExplore); } } private TargetGraph buildTargetGraph( PerBuildState state, BuckEventBus eventBus, Iterable<BuildTarget> toExplore) throws IOException, InterruptedException, BuildFileParseException { if (Iterables.isEmpty(toExplore)) { return TargetGraph.EMPTY; } MutableDirectedGraph<TargetNode<?>> graph = new MutableDirectedGraph<>(); Map<BuildTarget, TargetNode<?>> index = new HashMap<>(); ParseEvent.Started parseStart = ParseEvent.started(toExplore); eventBus.post(parseStart); GraphTraversable<BuildTarget> traversable = target -> { TargetNode<?> node; try { node = state.getTargetNode(target); } catch (BuildFileParseException e) { throw new RuntimeException(e); } // this second lookup loop may *seem* pointless, but it allows us to report which node is // referring to a node we can't find - something that's very difficult in this Traversable // visitor pattern otherwise. // it's also work we need to do anyways. the getTargetNode() result is cached, so that // when we come around and re-visit that node there won't actually be any work performed. for (BuildTarget dep : node.getParseDeps()) { try { state.getTargetNode(dep); } catch (BuildFileParseException e) { throw ParserMessages.createReadableExceptionWithWhenSuffix(target, dep, e); } catch (HumanReadableException e) { throw ParserMessages.createReadableExceptionWithWhenSuffix(target, dep, e); } } return node.getParseDeps().iterator(); }; AcyclicDepthFirstPostOrderTraversal<BuildTarget> targetNodeTraversal = new AcyclicDepthFirstPostOrderTraversal<>(traversable); TargetGraph targetGraph = null; try { for (BuildTarget target : targetNodeTraversal.traverse(toExplore)) { TargetNode<?> targetNode = state.getTargetNode(target); Preconditions.checkNotNull(targetNode, "No target node found for %s", target); graph.addNode(targetNode); MoreMaps.putCheckEquals(index, target, targetNode); if (target.isFlavored()) { BuildTarget unflavoredTarget = ImmutableBuildTarget.of(target.getUnflavoredBuildTarget()); MoreMaps.putCheckEquals(index, unflavoredTarget, state.getTargetNode(unflavoredTarget)); } for (BuildTarget dep : targetNode.getParseDeps()) { graph.addEdge(targetNode, state.getTargetNode(dep)); } } targetGraph = new TargetGraph(graph, ImmutableMap.copyOf(index)); return targetGraph; } catch (AcyclicDepthFirstPostOrderTraversal.CycleException e) { throw new HumanReadableException(e.getMessage()); } catch (RuntimeException e) { throw propagateRuntimeCause(e); } finally { eventBus.post( ParseEvent.finished( parseStart, state.getParseProcessedBytes(), Optional.ofNullable(targetGraph))); } } /** * @param eventBus used to log events while parsing. * @param targetNodeSpecs the specs representing the build targets to generate a target graph for. * @return the target graph containing the build targets and their related targets. */ @Override public synchronized TargetGraphAndBuildTargets buildTargetGraphForTargetNodeSpecs( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<? extends TargetNodeSpec> targetNodeSpecs) throws BuildFileParseException, IOException, InterruptedException { return buildTargetGraphForTargetNodeSpecs( eventBus, rootCell, enableProfiling, executor, targetNodeSpecs, ParserConfig.ApplyDefaultFlavorsMode.DISABLED); } /** * @param eventBus used to log events while parsing. * @param targetNodeSpecs the specs representing the build targets to generate a target graph for. * @return the target graph containing the build targets and their related targets. */ @Override public synchronized TargetGraphAndBuildTargets buildTargetGraphForTargetNodeSpecs( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<? extends TargetNodeSpec> targetNodeSpecs, ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) throws BuildFileParseException, IOException, InterruptedException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, rootCell, enableProfiling, SpeculativeParsing.ENABLED)) { ImmutableSet<BuildTarget> buildTargets = ImmutableSet.copyOf( Iterables.concat( targetSpecResolver.resolveTargetSpecs( eventBus, rootCell, targetNodeSpecs, (buildTarget, targetNode, targetType) -> applyDefaultFlavors( buildTarget, targetNode, targetType, applyDefaultFlavorsMode), state.getTargetNodeProviderForSpecResolver(), (spec, nodes) -> spec.filter(nodes)))); TargetGraph graph = buildTargetGraph(state, eventBus, buildTargets); return TargetGraphAndBuildTargets.builder() .setBuildTargets(buildTargets) .setTargetGraph(graph) .build(); } } @Override public String toString() { return permState.toString(); } @Override public ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs( BuckEventBus eventBus, Cell rootCell, boolean enableProfiling, ListeningExecutorService executor, Iterable<? extends TargetNodeSpec> specs, SpeculativeParsing speculativeParsing, ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) throws BuildFileParseException, InterruptedException, IOException { try (PerBuildState state = perBuildStateFactory.create( permState, eventBus, executor, rootCell, enableProfiling, speculativeParsing)) { return targetSpecResolver.resolveTargetSpecs( eventBus, rootCell, specs, (buildTarget, targetNode, targetType) -> applyDefaultFlavors(buildTarget, targetNode, targetType, applyDefaultFlavorsMode), state.getTargetNodeProviderForSpecResolver(), (spec, nodes) -> spec.filter(nodes)); } } @VisibleForTesting static BuildTarget applyDefaultFlavors( BuildTarget target, Optional<TargetNode<?>> targetNode, TargetNodeSpec.TargetType targetType, ParserConfig.ApplyDefaultFlavorsMode applyDefaultFlavorsMode) { if (target.isFlavored() || !targetNode.isPresent() || (targetType == TargetNodeSpec.TargetType.MULTIPLE_TARGETS && applyDefaultFlavorsMode == ParserConfig.ApplyDefaultFlavorsMode.SINGLE) || applyDefaultFlavorsMode == ParserConfig.ApplyDefaultFlavorsMode.DISABLED) { return target; } TargetNode<?> node = targetNode.get(); ImmutableSortedSet<Flavor> defaultFlavors = ImmutableSortedSet.of(); if (node.getConstructorArg() instanceof HasDefaultFlavors) { defaultFlavors = ((HasDefaultFlavors) node.getConstructorArg()).getDefaultFlavors(); LOG.debug("Got default flavors %s from args of %s", defaultFlavors, target); } if (node.getDescription() instanceof ImplicitFlavorsInferringDescription) { defaultFlavors = ((ImplicitFlavorsInferringDescription) node.getDescription()) .addImplicitFlavors(defaultFlavors); LOG.debug("Got default flavors %s from description of %s", defaultFlavors, target); } return target.withFlavors(defaultFlavors); } @Override public void register(EventBus eventBus) { eventBus.register(permState); } }
Provide expected size when creating a map. Reviewed By: bobyangyf fbshipit-source-id: 4fd47d8ace
src/com/facebook/buck/parser/DefaultParser.java
Provide expected size when creating a map.
<ide><path>rc/com/facebook/buck/parser/DefaultParser.java <ide> String shortName = targetNode.getBuildTarget().getShortName(); <ide> for (Map<String, Object> rawNode : allRawNodes) { <ide> if (shortName.equals(rawNode.get("name"))) { <del> SortedMap<String, Object> toReturn = new TreeMap<>(); <del> toReturn.putAll(rawNode); <add> SortedMap<String, Object> toReturn = new TreeMap<>(rawNode); <ide> toReturn.put( <ide> "buck.direct_dependencies", <ide> targetNode
Java
mpl-2.0
5d6547ea2c5fbbe635b4666d17b93d7d2283b0d7
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: Helper.java,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2007-11-06 15:07:18 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, Inc. * 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. Neither the name of Sun Microsystems, Inc. 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. * *************************************************************************/ // __________ Imports __________ import java.util.Random; // base classes import com.sun.star.uno.XInterface; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.lang.*; // factory for creating components import com.sun.star.comp.servicemanager.ServiceManager; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.bridge.XUnoUrlResolver; import com.sun.star.uno.XNamingService; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XComponentLoader; // property access import com.sun.star.beans.*; // container access import com.sun.star.container.*; // application specific classes import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.text.XTextDocument; import com.sun.star.document.XEmbeddedObjectSupplier; import com.sun.star.frame.XModel; import com.sun.star.frame.XController; // Exceptions import com.sun.star.uno.RuntimeException; import com.sun.star.container.NoSuchElementException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.lang.IndexOutOfBoundsException; // __________ Implementation __________ /** Helper for creating a calc document adding cell values and charts @author Bj&ouml;rn Milcke */ public class Helper { public Helper( String[] args ) { // connect to a running office and get the ServiceManager try { // get the remote office component context maContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); System.out.println("Connected to a running office ..."); // get the remote office service manager maMCFactory = maContext.getServiceManager(); } catch( Exception e) { System.out.println( "Couldn't get ServiceManager: " + e ); e.printStackTrace(); System.exit(1); } } // ____________________ public XSpreadsheetDocument createSpreadsheetDocument() { return (XSpreadsheetDocument) UnoRuntime.queryInterface( XSpreadsheetDocument.class, createDocument( "scalc" )); } // ____________________ public XModel createPresentationDocument() { return createDocument( "simpress" ); } // ____________________ public XModel createDrawingDocument() { return createDocument( "sdraw" ); } // ____________________ public XModel createTextDocument() { return createDocument( "swriter" ); } // ____________________ public XModel createDocument( String sDocType ) { XModel aResult = null; try { XComponentLoader aLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, maMCFactory.createInstanceWithContext("com.sun.star.frame.Desktop", maContext) ); aResult = (XModel) UnoRuntime.queryInterface( XModel.class, aLoader.loadComponentFromURL( "private:factory/" + sDocType, "_blank", 0, new PropertyValue[ 0 ] ) ); } catch( Exception e ) { System.err.println("Couldn't create Document of type "+ sDocType +": "+e); e.printStackTrace(); System.exit( 0 ); } return aResult; } public XComponentContext getComponentContext(){ return maContext; } // __________ private members and methods __________ private final String msDataSheetName = "Data"; private final String msChartSheetName = "Chart"; private final String msChartName = "SampleChart"; private XComponentContext maContext; private XMultiComponentFactory maMCFactory; private XSpreadsheetDocument maSpreadSheetDoc; }
odk/examples/DevelopersGuide/Charts/Helper.java
/************************************************************************* * * $RCSfile: Helper.java,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-01-31 16:10:43 $ * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright (c) 2003 by Sun Microsystems, Inc. * 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. Neither the name of Sun Microsystems, Inc. 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. * *************************************************************************/ // __________ Imports __________ import java.util.Random; // base classes import com.sun.star.uno.XInterface; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.lang.*; // factory for creating components import com.sun.star.comp.servicemanager.ServiceManager; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.bridge.XUnoUrlResolver; import com.sun.star.uno.XNamingService; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XComponentLoader; // property access import com.sun.star.beans.*; // container access import com.sun.star.container.*; // application specific classes import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.text.XTextDocument; import com.sun.star.document.XEmbeddedObjectSupplier; import com.sun.star.frame.XModel; import com.sun.star.frame.XController; // Exceptions import com.sun.star.uno.RuntimeException; import com.sun.star.container.NoSuchElementException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.lang.IndexOutOfBoundsException; // __________ Implementation __________ /** Helper for creating a calc document adding cell values and charts @author Bj&ouml;rn Milcke */ public class Helper { public Helper( String[] args ) { // connect to a running office and get the ServiceManager try { // get the remote office component context maContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); System.out.println("Connected to a running office ..."); // get the remote office service manager maMCFactory = maContext.getServiceManager(); } catch( Exception e) { System.out.println( "Couldn't get ServiceManager: " + e ); e.printStackTrace(); System.exit(1); } } // ____________________ public XSpreadsheetDocument createSpreadsheetDocument() { return (XSpreadsheetDocument) UnoRuntime.queryInterface( XSpreadsheetDocument.class, createDocument( "scalc" )); } // ____________________ public XModel createPresentationDocument() { return createDocument( "simpress" ); } // ____________________ public XModel createDrawingDocument() { return createDocument( "sdraw" ); } // ____________________ public XModel createTextDocument() { return createDocument( "swriter" ); } // ____________________ public XModel createDocument( String sDocType ) { XModel aResult = null; try { XComponentLoader aLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, maMCFactory.createInstanceWithContext("com.sun.star.frame.Desktop", maContext) ); aResult = (XModel) UnoRuntime.queryInterface( XModel.class, aLoader.loadComponentFromURL( "private:factory/" + sDocType, "_blank", 0, new PropertyValue[ 0 ] ) ); } catch( Exception e ) { System.err.println("Couldn't create Document of type "+ sDocType +": "+e); e.printStackTrace(); System.exit( 0 ); } return aResult; } // __________ private members and methods __________ private final String msDataSheetName = "Data"; private final String msChartSheetName = "Chart"; private final String msChartName = "SampleChart"; private XComponentContext maContext; private XMultiComponentFactory maMCFactory; private XSpreadsheetDocument maSpreadSheetDoc; }
INTEGRATION: CWS cn1 (1.5.150); FILE MERGED 2007/05/30 19:26:07 cn 1.5.150.1: #i77943# implement uno-awt messagebox into SelectionChangeListener
odk/examples/DevelopersGuide/Charts/Helper.java
INTEGRATION: CWS cn1 (1.5.150); FILE MERGED 2007/05/30 19:26:07 cn 1.5.150.1: #i77943# implement uno-awt messagebox into SelectionChangeListener
<ide><path>dk/examples/DevelopersGuide/Charts/Helper.java <ide> * <ide> * $RCSfile: Helper.java,v $ <ide> * <del> * $Revision: 1.5 $ <add> * $Revision: 1.6 $ <ide> * <del> * last change: $Author: rt $ $Date: 2005-01-31 16:10:43 $ <add> * last change: $Author: rt $ $Date: 2007-11-06 15:07:18 $ <ide> * <ide> * The Contents of this file are made available subject to the terms of <ide> * the BSD license. <ide> return aResult; <ide> } <ide> <add> public XComponentContext getComponentContext(){ <add> return maContext; <add> <add> } <add> <ide> // __________ private members and methods __________ <ide> <ide> private final String msDataSheetName = "Data";
Java
apache-2.0
b612351e5554eaeccb96f5f46cb322dee4a014f8
0
StraaS/StraaS-android-sdk-sample
package io.straas.android.sdk.streaming.demo.camera; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.session.MediaControllerCompat.Callback; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Tasks; import java.util.ArrayList; import io.straas.android.sdk.demo.R; import io.straas.android.sdk.media.StraasMediaCore; import io.straas.android.sdk.streaming.CameraController; import io.straas.android.sdk.streaming.LiveEventConfig; import io.straas.android.sdk.streaming.StreamConfig; import io.straas.android.sdk.streaming.StreamManager; import io.straas.android.sdk.streaming.StreamStatsReport; import io.straas.android.sdk.streaming.demo.Utils; import io.straas.android.sdk.streaming.demo.filter.GPUImageSupportFilter; import io.straas.android.sdk.streaming.demo.filter.GrayImageFilter; import io.straas.android.sdk.streaming.demo.qrcode.QrcodeActivity; import io.straas.android.sdk.streaming.error.StreamException.EventExpiredException; import io.straas.android.sdk.streaming.error.StreamException.LiveCountLimitException; import io.straas.android.sdk.streaming.interfaces.EventListener; import io.straas.sdk.demo.MemberIdentity; import jp.co.cyberagent.android.gpuimage.GPUImageColorInvertFilter; import static io.straas.android.sdk.demo.R.id.filter; import static io.straas.android.sdk.demo.R.id.flash; import static io.straas.android.sdk.demo.R.id.switch_camera; import static io.straas.android.sdk.demo.R.id.trigger; import static io.straas.android.sdk.streaming.StreamManager.STATE_CONNECTING; import static io.straas.android.sdk.streaming.StreamManager.STATE_STREAMING; public class MainActivity extends AppCompatActivity { private static final String TAG = "Streaming"; private StreamManager mStreamManager; private CameraController mCameraController; private TextureView mTextureView; private RadioGroup mStreamWaySwitcher; private EditText mEditTitle; private FrameLayout mStreamKeyPanel; private EditText mEditStreamKey; private TextView mStreamStats; private Button btn_trigger, btn_switch, btn_flash, btn_filter; private int mFilter = 0; private static final String[] STREAM_PERMISSIONS = { Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }; private static final int STREAM_PERMISSION_REQUEST = 1; // remove StraasMediaCore if you don't need to receive live event, e.g. CCU private StraasMediaCore mStraasMediaCore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_streaming); StreamManager.initialize(MemberIdentity.ME) .addOnCompleteListener(new OnCompleteListener<StreamManager>() { @Override public void onComplete(@NonNull Task<StreamManager> task) { if (!task.isSuccessful()) { Log.e(TAG, "init fail " + task.getException()); } mStreamManager = task.getResult(); mStreamManager.addEventListener(mEventListener); preview(); } }); mTextureView = findViewById(R.id.preview); mTextureView.setKeepScreenOn(true); btn_trigger = findViewById(trigger); btn_switch = findViewById(switch_camera); btn_flash = findViewById(flash); btn_filter = findViewById(filter); mEditTitle = findViewById(R.id.edit_title); mStreamStats = findViewById(R.id.stream_stats); mStreamWaySwitcher = findViewById(R.id.stream_way); mEditStreamKey = findViewById(R.id.edit_stream_key); mStreamKeyPanel = findViewById(R.id.stream_key_panel); initEditStreamKey(); initStreamWaySwitcher(); checkPermissions(); } private void initEditStreamKey() { final ImageView clearButton = findViewById(R.id.clear); final ImageView scanButton = findViewById(R.id.scan); mEditStreamKey.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) { clearButton.setVisibility(View.GONE); scanButton.setVisibility(View.VISIBLE); } else { scanButton.setVisibility(View.GONE); clearButton.setVisibility(View.VISIBLE); } } }); } private void initStreamWaySwitcher() { onCheckedStreamWay(mStreamWaySwitcher.getCheckedRadioButtonId()); mStreamWaySwitcher.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { onCheckedStreamWay(checkedId); } }); } @Override protected void onStart() { super.onStart(); if (checkPermissions() == 0) { preview(); } } @Override public void onStop() { super.onStop(); destroy(); } private int checkPermissions() { String[] requestPermissions = getPermissionsRequestArray(STREAM_PERMISSIONS); if (requestPermissions.length != 0) { ActivityCompat.requestPermissions(MainActivity.this, requestPermissions, STREAM_PERMISSION_REQUEST); } return requestPermissions.length; } private String[] getPermissionsRequestArray(String[] permissions) { ArrayList<String> requestArray = new ArrayList<>(); for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) { requestArray.add(permission); } } return requestArray.toArray(new String[0]); } private StreamConfig getConfig() { return new StreamConfig.Builder() .camera(StreamConfig.CAMERA_FRONT) .fitAllCamera(true) .build(); } private Task<CameraController> preview() { if (mStreamManager != null && mStreamManager.getStreamState() == StreamManager.STATE_IDLE) { return mStreamManager.prepare(getConfig(), mTextureView) .addOnCompleteListener(this, new OnCompleteListener<CameraController>() { @Override public void onComplete(@NonNull Task<CameraController> task) { if (task.isSuccessful()) { Log.d(TAG, "Prepare succeeds"); mCameraController = task.getResult(); enableAllButtons(); } else { Log.e(TAG, "Prepare fails " + task.getException()); } } }); } return Tasks.forException(new IllegalStateException()); } private void enableAllButtons() { btn_trigger.setEnabled(true); btn_switch.setEnabled(true); btn_flash.setEnabled(true); btn_filter.setEnabled(true); } private void createLiveEventAndStartStreaming(String title) { mStreamManager.createLiveEvent(new LiveEventConfig.Builder() .title(title) .build()) .addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String liveId) { Log.d(TAG, "Create live event succeeds: " + liveId); startStreamingWithLiveId(liveId); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception error) { if (error instanceof LiveCountLimitException){ String liveId = ((LiveCountLimitException)error).getLiveId(); Log.d(TAG, "Existing live event: " + liveId); startStreamingWithLiveId(liveId); } else { Log.e(TAG, "Create live event fails: " + error); showError(error); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } } }); } private void startStreamingWithLiveId(final String liveId) { mStreamManager.startStreamingWithLiveId(liveId).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Start streaming succeeds"); // remove StraasMediaCore if you don't need to receive live event, e.g. CCU mStraasMediaCore = new StraasMediaCore(MemberIdentity.ME, new MediaBrowserCompat.ConnectionCallback() { @Override public void onConnected() { mStraasMediaCore.getMediaController().getTransportControls() .prepareFromMediaId(StraasMediaCore.LIVE_ID_PREFIX + liveId, null); mStraasMediaCore.getMediaController().registerCallback(new Callback() { @Override public void onSessionEvent(String event, Bundle extras) { switch (event) { case StraasMediaCore.LIVE_EXTRA_STATISTICS_CCU: Log.d(TAG, "ccu: " + extras.getInt(event)); break; case StraasMediaCore.LIVE_EXTRA_STATISTICS_HIT_COUNT: Log.d(TAG, "hit count: " + extras.getInt(event)); break; } } }); } }); mStraasMediaCore.getMediaBrowser().connect(); } else { Exception error = task.getException(); if (error instanceof EventExpiredException) { Log.w(TAG, "Live event expires, set this event to ended and create " + "a new one."); mStreamManager.endLiveEvent(liveId).addOnSuccessListener( new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "End live event succeeds: " + liveId); createLiveEventAndStartStreaming(mEditTitle.getText().toString()); } }); } else { Log.e(TAG, "Start streaming fails " + error); showError(error); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } } } }); } private void startStreamingWithStreamKey(String streamKey) { mStreamManager.startStreamingWithStreamKey(streamKey).addOnCompleteListener( new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Start streaming succeeds"); } else { Log.e(TAG, "Start streaming fails " + task.getException()); showError(task.getException()); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } } }); } private void stopStreaming() { // remove StraasMediaCore if you don't need to receive live event, e.g. CCU if (mStraasMediaCore != null && mStraasMediaCore.getMediaBrowser().isConnected()) { mStraasMediaCore.getMediaBrowser().disconnect(); } mStreamManager.stopStreaming().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Stop succeeds"); resetViews(); } else { Log.e(TAG, "Stop fails: " + task.getException()); } } }); } private void destroy() { if (mStreamManager != null) { mStreamManager.destroy().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { resetViews(); } }); } } public void trigger(View view) { if (btn_trigger.getText().equals(getResources().getString(R.string.start))) { if (mStreamManager != null) { btn_trigger.setText(getResources().getString(R.string.stop)); switch (mStreamWaySwitcher.getCheckedRadioButtonId()) { case R.id.stream_way_live_event: createLiveEventAndStartStreaming(mEditTitle.getText().toString()); break; case R.id.stream_way_stream_key: startStreamingWithStreamKey(mEditStreamKey.getText().toString()); break; } } } else { btn_trigger.setEnabled(false); if (mStreamManager != null) { stopStreaming(); } } } public void switchCamera(View view) { if (mCameraController != null) { mCameraController.switchCamera(); } } public void flash(View view) { if (mCameraController != null) { mCameraController.toggleFlash(); } } public void changeFilter(View view) { if (mStreamManager != null) { switch(mFilter) { case 0: mFilter += mStreamManager.setFilter(new GrayImageFilter()) ? 1 : 0; break; case 1: mFilter += mStreamManager.setFilter(new GPUImageSupportFilter<>(new GPUImageColorInvertFilter())) ? 1 : 0; break; case 2: mFilter += mStreamManager.setFilter(null) ? 1 : 0; break; } mFilter %= 3; } } public void scanQrcode(View view) { if (checkPermissions() != 0) { return; } destroy(); Intent intent = new Intent(this, QrcodeActivity.class); startActivityForResult(intent, 1); } public void clearStreamKey(View view) { mEditStreamKey.getText().clear(); } private void onCheckedStreamWay(int checkedId) { switch (checkedId) { case R.id.stream_way_live_event: mStreamKeyPanel.setVisibility(View.GONE); mEditTitle.setVisibility(View.VISIBLE); break; case R.id.stream_way_stream_key: mEditTitle.setVisibility(View.GONE); mStreamKeyPanel.setVisibility(View.VISIBLE); break; } } private void resetViews() { btn_trigger.setText(getResources().getString(R.string.start)); btn_trigger.setEnabled(true); mStreamStats.setText(""); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { String streamKey = data.getStringExtra(QrcodeActivity.KEY_QR_CODE_VALUE); if (!isPureText(streamKey)) { Toast.makeText(this, R.string.error_wrong_format, Toast.LENGTH_LONG).show(); return; } mEditStreamKey.setText(streamKey); } } private static boolean isPureText(String string) { return string.matches("[A-Za-z0-9]+"); } private void showError(Exception exception) { Toast.makeText(this, exception.toString(), Toast.LENGTH_LONG).show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == STREAM_PERMISSION_REQUEST) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, getResources().getString(R.string.hint_need_permission), Toast.LENGTH_SHORT).show(); return; } } preview(); } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private EventListener mEventListener = new EventListener() { @Override public void onStreamStatsReportUpdate(StreamStatsReport streamStatsReport) { if (mStreamManager.getStreamState() == STATE_CONNECTING || mStreamManager.getStreamState() == STATE_STREAMING) { mStreamStats.setText(Utils.toDisplayText(MainActivity.this, streamStatsReport)); } } @Override public void onError(Exception error, @Nullable String liveId) { Log.e(TAG, "onError " + error); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } }; }
Streaming/src/main/java/io/straas/android/sdk/streaming/demo/camera/MainActivity.java
package io.straas.android.sdk.streaming.demo.camera; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.session.MediaControllerCompat.Callback; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Tasks; import java.util.ArrayList; import io.straas.android.sdk.demo.R; import io.straas.android.sdk.media.StraasMediaCore; import io.straas.android.sdk.streaming.CameraController; import io.straas.android.sdk.streaming.LiveEventConfig; import io.straas.android.sdk.streaming.StreamConfig; import io.straas.android.sdk.streaming.StreamManager; import io.straas.android.sdk.streaming.StreamStatsReport; import io.straas.android.sdk.streaming.demo.Utils; import io.straas.android.sdk.streaming.demo.filter.GPUImageSupportFilter; import io.straas.android.sdk.streaming.demo.filter.GrayImageFilter; import io.straas.android.sdk.streaming.demo.qrcode.QrcodeActivity; import io.straas.android.sdk.streaming.error.StreamException.LiveCountLimitException; import io.straas.android.sdk.streaming.interfaces.EventListener; import io.straas.sdk.demo.MemberIdentity; import jp.co.cyberagent.android.gpuimage.GPUImageColorInvertFilter; import static io.straas.android.sdk.demo.R.id.filter; import static io.straas.android.sdk.demo.R.id.flash; import static io.straas.android.sdk.demo.R.id.switch_camera; import static io.straas.android.sdk.demo.R.id.trigger; import static io.straas.android.sdk.streaming.StreamManager.STATE_CONNECTING; import static io.straas.android.sdk.streaming.StreamManager.STATE_STREAMING; public class MainActivity extends AppCompatActivity { private static final String TAG = "Streaming"; private StreamManager mStreamManager; private CameraController mCameraController; private TextureView mTextureView; private RadioGroup mStreamWaySwitcher; private EditText mEditTitle; private FrameLayout mStreamKeyPanel; private EditText mEditStreamKey; private TextView mStreamStats; private Button btn_trigger, btn_switch, btn_flash, btn_filter; private int mFilter = 0; private static final String[] STREAM_PERMISSIONS = { Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO }; private static final int STREAM_PERMISSION_REQUEST = 1; // remove StraasMediaCore if you don't need to receive live event, e.g. CCU private StraasMediaCore mStraasMediaCore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_streaming); StreamManager.initialize(MemberIdentity.ME) .addOnCompleteListener(new OnCompleteListener<StreamManager>() { @Override public void onComplete(@NonNull Task<StreamManager> task) { if (!task.isSuccessful()) { Log.e(TAG, "init fail " + task.getException()); } mStreamManager = task.getResult(); mStreamManager.addEventListener(mEventListener); preview(); } }); mTextureView = findViewById(R.id.preview); mTextureView.setKeepScreenOn(true); btn_trigger = findViewById(trigger); btn_switch = findViewById(switch_camera); btn_flash = findViewById(flash); btn_filter = findViewById(filter); mEditTitle = findViewById(R.id.edit_title); mStreamStats = findViewById(R.id.stream_stats); mStreamWaySwitcher = findViewById(R.id.stream_way); mEditStreamKey = findViewById(R.id.edit_stream_key); mStreamKeyPanel = findViewById(R.id.stream_key_panel); initEditStreamKey(); initStreamWaySwitcher(); checkPermissions(); } private void initEditStreamKey() { final ImageView clearButton = findViewById(R.id.clear); final ImageView scanButton = findViewById(R.id.scan); mEditStreamKey.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) { clearButton.setVisibility(View.GONE); scanButton.setVisibility(View.VISIBLE); } else { scanButton.setVisibility(View.GONE); clearButton.setVisibility(View.VISIBLE); } } }); } private void initStreamWaySwitcher() { onCheckedStreamWay(mStreamWaySwitcher.getCheckedRadioButtonId()); mStreamWaySwitcher.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { onCheckedStreamWay(checkedId); } }); } @Override protected void onStart() { super.onStart(); if (checkPermissions() == 0) { preview(); } } @Override public void onStop() { super.onStop(); destroy(); } private int checkPermissions() { String[] requestPermissions = getPermissionsRequestArray(STREAM_PERMISSIONS); if (requestPermissions.length != 0) { ActivityCompat.requestPermissions(MainActivity.this, requestPermissions, STREAM_PERMISSION_REQUEST); } return requestPermissions.length; } private String[] getPermissionsRequestArray(String[] permissions) { ArrayList<String> requestArray = new ArrayList<>(); for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) { requestArray.add(permission); } } return requestArray.toArray(new String[0]); } private StreamConfig getConfig() { return new StreamConfig.Builder() .camera(StreamConfig.CAMERA_FRONT) .fitAllCamera(true) .build(); } private Task<CameraController> preview() { if (mStreamManager != null && mStreamManager.getStreamState() == StreamManager.STATE_IDLE) { return mStreamManager.prepare(getConfig(), mTextureView) .addOnCompleteListener(this, new OnCompleteListener<CameraController>() { @Override public void onComplete(@NonNull Task<CameraController> task) { if (task.isSuccessful()) { Log.d(TAG, "Prepare succeeds"); mCameraController = task.getResult(); enableAllButtons(); } else { Log.e(TAG, "Prepare fails " + task.getException()); } } }); } return Tasks.forException(new IllegalStateException()); } private void enableAllButtons() { btn_trigger.setEnabled(true); btn_switch.setEnabled(true); btn_flash.setEnabled(true); btn_filter.setEnabled(true); } private void createLiveEventAndStartStreaming(String title) { mStreamManager.createLiveEvent(new LiveEventConfig.Builder() .title(title) .build()) .addOnSuccessListener(new OnSuccessListener<String>() { @Override public void onSuccess(String liveId) { Log.d(TAG, "Create live event succeeds: " + liveId); startStreamingWithLiveId(liveId); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception error) { if (error instanceof LiveCountLimitException){ String liveId = ((LiveCountLimitException)error).getLiveId(); Log.d(TAG, "Existing live event: " + liveId); startStreamingWithLiveId(liveId); } else { Log.e(TAG, "Create live event fails: " + error); showError(error); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } } }); } private void startStreamingWithLiveId(final String liveId) { mStreamManager.startStreamingWithLiveId(liveId).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Start streaming succeeds"); // remove StraasMediaCore if you don't need to receive live event, e.g. CCU mStraasMediaCore = new StraasMediaCore(MemberIdentity.ME, new MediaBrowserCompat.ConnectionCallback() { @Override public void onConnected() { mStraasMediaCore.getMediaController().getTransportControls() .prepareFromMediaId(StraasMediaCore.LIVE_ID_PREFIX + liveId, null); mStraasMediaCore.getMediaController().registerCallback(new Callback() { @Override public void onSessionEvent(String event, Bundle extras) { switch (event) { case StraasMediaCore.LIVE_EXTRA_STATISTICS_CCU: Log.d(TAG, "ccu: " + extras.getInt(event)); break; case StraasMediaCore.LIVE_EXTRA_STATISTICS_HIT_COUNT: Log.d(TAG, "hit count: " + extras.getInt(event)); break; } } }); } }); mStraasMediaCore.getMediaBrowser().connect(); } else { Log.e(TAG, "Start streaming fails " + task.getException()); showError(task.getException()); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } } }); } private void startStreamingWithStreamKey(String streamKey) { mStreamManager.startStreamingWithStreamKey(streamKey).addOnCompleteListener( new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Start streaming succeeds"); } else { Log.e(TAG, "Start streaming fails " + task.getException()); showError(task.getException()); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } } }); } private void stopStreaming() { // remove StraasMediaCore if you don't need to receive live event, e.g. CCU if (mStraasMediaCore != null && mStraasMediaCore.getMediaBrowser().isConnected()) { mStraasMediaCore.getMediaBrowser().disconnect(); } mStreamManager.stopStreaming().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Stop succeeds"); resetViews(); } else { Log.e(TAG, "Stop fails: " + task.getException()); } } }); } private void destroy() { if (mStreamManager != null) { mStreamManager.destroy().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { resetViews(); } }); } } private void endLiveEvent(final String liveId) { if (mStreamManager != null || !TextUtils.isEmpty(liveId)) { mStreamManager.endLiveEvent(liveId).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "End live event succeeds: " + liveId); } }); } } public void trigger(View view) { if (btn_trigger.getText().equals(getResources().getString(R.string.start))) { if (mStreamManager != null) { btn_trigger.setText(getResources().getString(R.string.stop)); switch (mStreamWaySwitcher.getCheckedRadioButtonId()) { case R.id.stream_way_live_event: createLiveEventAndStartStreaming(mEditTitle.getText().toString()); break; case R.id.stream_way_stream_key: startStreamingWithStreamKey(mEditStreamKey.getText().toString()); break; } } } else { btn_trigger.setEnabled(false); if (mStreamManager != null) { stopStreaming(); } } } public void switchCamera(View view) { if (mCameraController != null) { mCameraController.switchCamera(); } } public void flash(View view) { if (mCameraController != null) { mCameraController.toggleFlash(); } } public void changeFilter(View view) { if (mStreamManager != null) { switch(mFilter) { case 0: mFilter += mStreamManager.setFilter(new GrayImageFilter()) ? 1 : 0; break; case 1: mFilter += mStreamManager.setFilter(new GPUImageSupportFilter<>(new GPUImageColorInvertFilter())) ? 1 : 0; break; case 2: mFilter += mStreamManager.setFilter(null) ? 1 : 0; break; } mFilter %= 3; } } public void scanQrcode(View view) { if (checkPermissions() != 0) { return; } destroy(); Intent intent = new Intent(this, QrcodeActivity.class); startActivityForResult(intent, 1); } public void clearStreamKey(View view) { mEditStreamKey.getText().clear(); } private void onCheckedStreamWay(int checkedId) { switch (checkedId) { case R.id.stream_way_live_event: mStreamKeyPanel.setVisibility(View.GONE); mEditTitle.setVisibility(View.VISIBLE); break; case R.id.stream_way_stream_key: mEditTitle.setVisibility(View.GONE); mStreamKeyPanel.setVisibility(View.VISIBLE); break; } } private void resetViews() { btn_trigger.setText(getResources().getString(R.string.start)); btn_trigger.setEnabled(true); mStreamStats.setText(""); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { String streamKey = data.getStringExtra(QrcodeActivity.KEY_QR_CODE_VALUE); if (!isPureText(streamKey)) { Toast.makeText(this, R.string.error_wrong_format, Toast.LENGTH_LONG).show(); return; } mEditStreamKey.setText(streamKey); } } private static boolean isPureText(String string) { return string.matches("[A-Za-z0-9]+"); } private void showError(Exception exception) { Toast.makeText(this, exception.toString(), Toast.LENGTH_LONG).show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == STREAM_PERMISSION_REQUEST) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, getResources().getString(R.string.hint_need_permission), Toast.LENGTH_SHORT).show(); return; } } preview(); } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private EventListener mEventListener = new EventListener() { @Override public void onStreamStatsReportUpdate(StreamStatsReport streamStatsReport) { if (mStreamManager.getStreamState() == STATE_CONNECTING || mStreamManager.getStreamState() == STATE_STREAMING) { mStreamStats.setText(Utils.toDisplayText(MainActivity.this, streamStatsReport)); } } @Override public void onError(Exception error, @Nullable String liveId) { Log.e(TAG, "onError " + error); btn_trigger.setText(getResources().getString(R.string.start)); mStreamStats.setText(""); } }; }
change: Set live evevnt to ended only when live event expires.
Streaming/src/main/java/io/straas/android/sdk/streaming/demo/camera/MainActivity.java
change: Set live evevnt to ended only when live event expires.
<ide><path>treaming/src/main/java/io/straas/android/sdk/streaming/demo/camera/MainActivity.java <ide> import android.support.v4.media.session.MediaControllerCompat.Callback; <ide> import android.support.v7.app.AppCompatActivity; <ide> import android.text.Editable; <del>import android.text.TextUtils; <ide> import android.text.TextWatcher; <ide> import android.util.Log; <ide> import android.view.TextureView; <ide> import io.straas.android.sdk.streaming.demo.filter.GPUImageSupportFilter; <ide> import io.straas.android.sdk.streaming.demo.filter.GrayImageFilter; <ide> import io.straas.android.sdk.streaming.demo.qrcode.QrcodeActivity; <add>import io.straas.android.sdk.streaming.error.StreamException.EventExpiredException; <ide> import io.straas.android.sdk.streaming.error.StreamException.LiveCountLimitException; <ide> import io.straas.android.sdk.streaming.interfaces.EventListener; <ide> import io.straas.sdk.demo.MemberIdentity; <ide> }); <ide> mStraasMediaCore.getMediaBrowser().connect(); <ide> } else { <del> Log.e(TAG, "Start streaming fails " + task.getException()); <del> showError(task.getException()); <del> btn_trigger.setText(getResources().getString(R.string.start)); <del> mStreamStats.setText(""); <add> Exception error = task.getException(); <add> if (error instanceof EventExpiredException) { <add> Log.w(TAG, "Live event expires, set this event to ended and create " + <add> "a new one."); <add> mStreamManager.endLiveEvent(liveId).addOnSuccessListener( <add> new OnSuccessListener<Void>() { <add> @Override <add> public void onSuccess(Void aVoid) { <add> Log.d(TAG, "End live event succeeds: " + liveId); <add> createLiveEventAndStartStreaming(mEditTitle.getText().toString()); <add> } <add> }); <add> } else { <add> Log.e(TAG, "Start streaming fails " + error); <add> showError(error); <add> btn_trigger.setText(getResources().getString(R.string.start)); <add> mStreamStats.setText(""); <add> } <ide> } <ide> } <ide> }); <ide> @Override <ide> public void onComplete(@NonNull Task<Void> task) { <ide> resetViews(); <del> } <del> }); <del> } <del> } <del> <del> private void endLiveEvent(final String liveId) { <del> if (mStreamManager != null || !TextUtils.isEmpty(liveId)) { <del> mStreamManager.endLiveEvent(liveId).addOnSuccessListener(new OnSuccessListener<Void>() { <del> @Override <del> public void onSuccess(Void aVoid) { <del> Log.d(TAG, "End live event succeeds: " + liveId); <ide> } <ide> }); <ide> }
Java
apache-2.0
607ef813097284e46d92cf499c48d60f69893651
0
arifogel/batfish,batfish/batfish,batfish/batfish,dhalperi/batfish,arifogel/batfish,dhalperi/batfish,arifogel/batfish,intentionet/batfish,intentionet/batfish,dhalperi/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,batfish/batfish
package org.batfish.datamodel; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.util.Comparator; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import org.batfish.common.util.CommonUtil; /** * A BGP Route. Captures attributes of both iBGP and eBGP routes. * * <p>For computational efficiency may contain additional attributes (that would otherwise be * present only in BGP advertisements on the wire) */ @ParametersAreNonnullByDefault public class BgpRoute extends AbstractRoute { /** Builder for {@link BgpRoute} */ @ParametersAreNonnullByDefault public static class Builder extends AbstractRouteBuilder<Builder, BgpRoute> { @Nonnull private AsPath _asPath; @Nonnull private ImmutableSortedSet.Builder<Long> _clusterList; @Nonnull private SortedSet<Long> _communities; private boolean _discard; private long _localPreference; @Nullable private Ip _originatorIp; @Nullable private OriginType _originType; @Nullable private RoutingProtocol _protocol; @Nullable private Ip _receivedFromIp; private boolean _receivedFromRouteReflectorClient; @Nullable private RoutingProtocol _srcProtocol; private int _weight; public Builder() { _asPath = AsPath.empty(); _communities = new TreeSet<>(); _clusterList = new ImmutableSortedSet.Builder<>(Ordering.natural()); } @Override public BgpRoute build() { return new BgpRoute( getNetwork(), getNextHopIp(), getAdmin(), _asPath, _communities, _discard, _localPreference, getMetric(), _originatorIp, _clusterList.build(), _receivedFromRouteReflectorClient, _originType, _protocol, _receivedFromIp, _srcProtocol, _weight, getNonForwarding(), getNonRouting()); } @Nonnull public AsPath getAsPath() { return _asPath; } @Nonnull public SortedSet<Long> getClusterList() { return _clusterList.build(); } @Nonnull public SortedSet<Long> getCommunities() { return _communities; } public long getLocalPreference() { return _localPreference; } @Nullable public Ip getOriginatorIp() { return _originatorIp; } @Nullable public OriginType getOriginType() { return _originType; } @Nullable public RoutingProtocol getProtocol() { return _protocol; } @Override @Nonnull protected Builder getThis() { return this; } public int getWeight() { return _weight; } public Builder setAsPath(AsPath asPath) { _asPath = asPath; return getThis(); } /** Overwrite the clusterList attribute */ public Builder setClusterList(Set<Long> clusterList) { _clusterList = new ImmutableSortedSet.Builder<>(Ordering.natural()); _clusterList.addAll(clusterList); return getThis(); } /** Add to the cluster list attribute */ public Builder addClusterList(Set<Long> clusterList) { _clusterList.addAll(clusterList); return getThis(); } /** Add to the cluster list attribute */ public Builder addToClusterList(Long cluster) { _clusterList.add(cluster); return getThis(); } /** Overwrite communities */ public Builder setCommunities(Set<Long> communities) { _communities = new TreeSet<>(); _communities.addAll(communities); return getThis(); } /** Add communities */ public Builder addCommunities(Set<Long> communities) { _communities.addAll(communities); return getThis(); } /** Add a single community */ public Builder addCommunity(Long community) { _communities.add(community); return getThis(); } /** Add communities */ public Builder removeCommunities(Set<Long> communities) { _communities.removeAll(communities); return getThis(); } public Builder setDiscard(boolean discard) { _discard = discard; return getThis(); } public Builder setLocalPreference(long localPreference) { _localPreference = localPreference; return getThis(); } public Builder setOriginatorIp(Ip originatorIp) { _originatorIp = originatorIp; return getThis(); } public Builder setOriginType(OriginType originType) { _originType = originType; return getThis(); } public Builder setProtocol(RoutingProtocol protocol) { _protocol = protocol; return getThis(); } public Builder setReceivedFromIp(@Nullable Ip receivedFromIp) { _receivedFromIp = receivedFromIp; return getThis(); } public Builder setReceivedFromRouteReflectorClient(boolean receivedFromRouteReflectorClient) { _receivedFromRouteReflectorClient = receivedFromRouteReflectorClient; return getThis(); } public Builder setSrcProtocol(@Nullable RoutingProtocol srcProtocol) { _srcProtocol = srcProtocol; return getThis(); } public Builder setWeight(int weight) { _weight = weight; return getThis(); } } /** Default local preference for a BGP route if one is not set explicitly */ public static final long DEFAULT_LOCAL_PREFERENCE = 100L; private static final String PROP_AS_PATH = "asPath"; private static final String PROP_CLUSTER_LIST = "clusterList"; private static final String PROP_COMMUNITIES = "communities"; private static final String PROP_DISCARD = "discard"; private static final String PROP_LOCAL_PREFERENCE = "localPreference"; private static final String PROP_ORIGIN_TYPE = "originType"; private static final String PROP_ORIGINATOR_IP = "originatorIp"; private static final String PROP_RECEIVED_FROM_IP = "receivedFromIp"; private static final String PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT = "receivedFromRouteReflectorClient"; private static final String PROP_SRC_PROTOCOL = "srcProtocol"; private static final String PROP_WEIGHT = "weight"; private static final Comparator<BgpRoute> COMPARATOR = Comparator.comparing(BgpRoute::getAsPath) .thenComparing(BgpRoute::getClusterList, CommonUtil::compareCollection) .thenComparing(BgpRoute::getCommunities, CommonUtil::compareCollection) .thenComparing(BgpRoute::getDiscard) .thenComparing(BgpRoute::getLocalPreference) .thenComparing(BgpRoute::getOriginType) .thenComparing(BgpRoute::getOriginatorIp) .thenComparing(BgpRoute::getReceivedFromIp) .thenComparing(BgpRoute::getReceivedFromRouteReflectorClient) .thenComparing(BgpRoute::getSrcProtocol) .thenComparing(BgpRoute::getWeight); private static final long serialVersionUID = 1L; @Nonnull private final AsPath _asPath; @Nonnull private final SortedSet<Long> _clusterList; @Nonnull private final SortedSet<Long> _communities; private final boolean _discard; private final long _localPreference; private final long _med; @Nonnull private final Ip _nextHopIp; @Nonnull private final Ip _originatorIp; @Nonnull private final OriginType _originType; @Nonnull private final RoutingProtocol _protocol; @Nullable private final Ip _receivedFromIp; private final boolean _receivedFromRouteReflectorClient; @Nullable private final RoutingProtocol _srcProtocol; /* NOTE: Cisco-only attribute */ private final int _weight; /* Cache the hashcode */ private transient volatile int _hashCode = 0; @JsonCreator private static BgpRoute jsonCreator( @Nullable @JsonProperty(PROP_NETWORK) Prefix network, @Nullable @JsonProperty(PROP_NEXT_HOP_IP) Ip nextHopIp, @JsonProperty(PROP_ADMINISTRATIVE_COST) int admin, @Nullable @JsonProperty(PROP_AS_PATH) AsPath asPath, @Nullable @JsonProperty(PROP_COMMUNITIES) SortedSet<Long> communities, @JsonProperty(PROP_DISCARD) boolean discard, @JsonProperty(PROP_LOCAL_PREFERENCE) long localPreference, @JsonProperty(PROP_METRIC) long med, @Nullable @JsonProperty(PROP_ORIGINATOR_IP) Ip originatorIp, @Nullable @JsonProperty(PROP_CLUSTER_LIST) SortedSet<Long> clusterList, @JsonProperty(PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT) boolean receivedFromRouteReflectorClient, @Nullable @JsonProperty(PROP_ORIGIN_TYPE) OriginType originType, @Nullable @JsonProperty(PROP_PROTOCOL) RoutingProtocol protocol, @Nullable @JsonProperty(PROP_RECEIVED_FROM_IP) Ip receivedFromIp, @Nullable @JsonProperty(PROP_SRC_PROTOCOL) RoutingProtocol srcProtocol, @JsonProperty(PROP_WEIGHT) int weight) { checkArgument(originatorIp != null, "Missing %s", PROP_ORIGINATOR_IP); checkArgument(originType != null, "Missing %s", PROP_ORIGIN_TYPE); checkArgument(protocol != null, "Missing %s", PROP_PROTOCOL); return new BgpRoute( network, nextHopIp, admin, asPath, communities, discard, localPreference, med, originatorIp, clusterList, receivedFromRouteReflectorClient, originType, protocol, receivedFromIp, srcProtocol, weight, false, false); } private BgpRoute( @Nullable Prefix network, @Nullable Ip nextHopIp, int admin, @Nullable AsPath asPath, @Nullable SortedSet<Long> communities, boolean discard, long localPreference, long med, Ip originatorIp, @Nullable SortedSet<Long> clusterList, @JsonProperty(PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT) boolean receivedFromRouteReflectorClient, OriginType originType, RoutingProtocol protocol, @Nullable Ip receivedFromIp, @Nullable RoutingProtocol srcProtocol, int weight, boolean nonForwarding, boolean nonRouting) { super(network, admin, nonRouting, nonForwarding); _asPath = firstNonNull(asPath, AsPath.empty()); _clusterList = clusterList == null ? ImmutableSortedSet.of() : ImmutableSortedSet.copyOf(clusterList); _communities = communities == null ? ImmutableSortedSet.of() : ImmutableSortedSet.copyOf(communities); _discard = discard; _localPreference = localPreference; _med = med; _nextHopIp = firstNonNull(nextHopIp, Route.UNSET_ROUTE_NEXT_HOP_IP); _originatorIp = originatorIp; _originType = originType; _protocol = protocol; _receivedFromIp = receivedFromIp; _receivedFromRouteReflectorClient = receivedFromRouteReflectorClient; _srcProtocol = srcProtocol; _weight = weight; } public static Builder builder() { return new Builder(); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof BgpRoute)) { return false; } BgpRoute other = (BgpRoute) o; return Objects.equals(_network, other._network) && _admin == other._admin && _discard == other._discard && _localPreference == other._localPreference && _med == other._med && _receivedFromRouteReflectorClient == other._receivedFromRouteReflectorClient && _weight == other._weight && Objects.equals(_asPath, other._asPath) && Objects.equals(_clusterList, other._clusterList) && Objects.equals(_communities, other._communities) && Objects.equals(_nextHopIp, other._nextHopIp) && Objects.equals(_originatorIp, other._originatorIp) && _originType == other._originType && _protocol == other._protocol && Objects.equals(_receivedFromIp, other._receivedFromIp) && _srcProtocol == other._srcProtocol; } @Override public int hashCode() { if (_hashCode != 0) { return _hashCode; } _hashCode = Objects.hash( _admin, _asPath, _clusterList, _communities, _discard, _localPreference, _med, _network, _nextHopIp, _originatorIp, _originType.ordinal(), _protocol.ordinal(), _receivedFromIp, _receivedFromRouteReflectorClient, _srcProtocol == null ? 0 : _srcProtocol.ordinal(), _weight); return _hashCode; } @Nonnull @JsonProperty(PROP_AS_PATH) public AsPath getAsPath() { return _asPath; } @Nonnull @JsonProperty(PROP_CLUSTER_LIST) public SortedSet<Long> getClusterList() { return _clusterList; } @Nonnull @JsonProperty(PROP_COMMUNITIES) public SortedSet<Long> getCommunities() { return _communities; } @JsonProperty(PROP_DISCARD) public boolean getDiscard() { return _discard; } @JsonProperty(PROP_LOCAL_PREFERENCE) public long getLocalPreference() { return _localPreference; } @JsonIgnore(false) @JsonProperty(PROP_METRIC) @Override public Long getMetric() { return _med; } @Nonnull @Override public String getNextHopInterface() { return Route.UNSET_NEXT_HOP_INTERFACE; } @Nonnull @JsonIgnore(false) @JsonProperty(PROP_NEXT_HOP_IP) @Override public Ip getNextHopIp() { return _nextHopIp; } @Nonnull @JsonProperty(PROP_ORIGINATOR_IP) public Ip getOriginatorIp() { return _originatorIp; } @Nonnull @JsonProperty(PROP_ORIGIN_TYPE) public OriginType getOriginType() { return _originType; } @Nonnull @JsonIgnore(false) @JsonProperty(PROP_PROTOCOL) @Override public RoutingProtocol getProtocol() { return _protocol; } @Nullable @JsonProperty(PROP_RECEIVED_FROM_IP) public Ip getReceivedFromIp() { return _receivedFromIp; } @JsonProperty(PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT) public boolean getReceivedFromRouteReflectorClient() { return _receivedFromRouteReflectorClient; } @Nullable @JsonProperty(PROP_SRC_PROTOCOL) public RoutingProtocol getSrcProtocol() { return _srcProtocol; } @Override public int getTag() { return NO_TAG; } @JsonProperty(PROP_WEIGHT) public int getWeight() { return _weight; } @Override public int routeCompare(@Nonnull AbstractRoute rhs) { if (getClass() != rhs.getClass()) { return 0; } return COMPARATOR.compare(this, (BgpRoute) rhs); } }
projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/BgpRoute.java
package org.batfish.datamodel; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.util.Comparator; import java.util.Objects; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import org.batfish.common.util.CommonUtil; /** * A BGP Route. Captures attributes of both iBGP and eBGP routes. * * <p>For computational efficiency may contain additional attributes (that would otherwise be * present only in BGP advertisements on the wire) */ @ParametersAreNonnullByDefault public class BgpRoute extends AbstractRoute { /** Builder for {@link BgpRoute} */ @ParametersAreNonnullByDefault public static class Builder extends AbstractRouteBuilder<Builder, BgpRoute> { @Nonnull private AsPath _asPath; @Nonnull private ImmutableSortedSet.Builder<Long> _clusterList; @Nonnull private SortedSet<Long> _communities; private boolean _discard; private long _localPreference; @Nullable private Ip _originatorIp; @Nullable private OriginType _originType; @Nullable private RoutingProtocol _protocol; @Nullable private Ip _receivedFromIp; private boolean _receivedFromRouteReflectorClient; @Nullable private RoutingProtocol _srcProtocol; private int _weight; public Builder() { _asPath = AsPath.empty(); _communities = new TreeSet<>(); _clusterList = new ImmutableSortedSet.Builder<>(Ordering.natural()); } @Override public BgpRoute build() { return new BgpRoute( getNetwork(), getNextHopIp(), getAdmin(), _asPath, _communities, _discard, _localPreference, getMetric(), _originatorIp, _clusterList.build(), _receivedFromRouteReflectorClient, _originType, _protocol, _receivedFromIp, _srcProtocol, _weight, getNonForwarding(), getNonRouting()); } @Nonnull public AsPath getAsPath() { return _asPath; } @Nonnull public SortedSet<Long> getClusterList() { return _clusterList.build(); } @Nonnull public SortedSet<Long> getCommunities() { return _communities; } public long getLocalPreference() { return _localPreference; } @Nullable public Ip getOriginatorIp() { return _originatorIp; } @Nullable public OriginType getOriginType() { return _originType; } @Nullable public RoutingProtocol getProtocol() { return _protocol; } @Override @Nonnull protected Builder getThis() { return this; } public int getWeight() { return _weight; } public Builder setAsPath(AsPath asPath) { _asPath = asPath; return getThis(); } /** Overwrite the clusterList attribute */ public Builder setClusterList(Set<Long> clusterList) { _clusterList = new ImmutableSortedSet.Builder<>(Ordering.natural()); _clusterList.addAll(clusterList); return getThis(); } /** Add to the cluster list attribute */ public Builder addClusterList(Set<Long> clusterList) { _clusterList.addAll(clusterList); return getThis(); } /** Add to the cluster list attribute */ public Builder addToClusterList(Long cluster) { _clusterList.add(cluster); return getThis(); } /** Overwrite communities */ public Builder setCommunities(Set<Long> communities) { _communities = new TreeSet<>(); _communities.addAll(communities); return getThis(); } /** Add communities */ public Builder addCommunities(Set<Long> communities) { _communities.addAll(communities); return getThis(); } /** Add a single community */ public Builder addCommunity(Long community) { _communities.add(community); return getThis(); } /** Add communities */ public Builder removeCommunities(Set<Long> communities) { _communities.removeAll(communities); return getThis(); } public Builder setDiscard(boolean discard) { _discard = discard; return getThis(); } public Builder setLocalPreference(long localPreference) { _localPreference = localPreference; return getThis(); } public Builder setOriginatorIp(Ip originatorIp) { _originatorIp = originatorIp; return getThis(); } public Builder setOriginType(OriginType originType) { _originType = originType; return getThis(); } public Builder setProtocol(RoutingProtocol protocol) { _protocol = protocol; return getThis(); } public Builder setReceivedFromIp(@Nullable Ip receivedFromIp) { _receivedFromIp = receivedFromIp; return getThis(); } public Builder setReceivedFromRouteReflectorClient(boolean receivedFromRouteReflectorClient) { _receivedFromRouteReflectorClient = receivedFromRouteReflectorClient; return getThis(); } public Builder setSrcProtocol(@Nullable RoutingProtocol srcProtocol) { _srcProtocol = srcProtocol; return getThis(); } public Builder setWeight(int weight) { _weight = weight; return getThis(); } } /** Default local preference for a BGP route if one is not set explicitly */ public static final long DEFAULT_LOCAL_PREFERENCE = 100L; private static final String PROP_AS_PATH = "asPath"; private static final String PROP_CLUSTER_LIST = "clusterList"; private static final String PROP_COMMUNITIES = "communities"; private static final String PROP_DISCARD = "discard"; private static final String PROP_LOCAL_PREFERENCE = "localPreference"; private static final String PROP_ORIGIN_TYPE = "originType"; private static final String PROP_ORIGINATOR_IP = "originatorIp"; private static final String PROP_RECEIVED_FROM_IP = "receivedFromIp"; private static final String PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT = "receivedFromRouteReflectorClient"; private static final String PROP_SRC_PROTOCOL = "srcProtocol"; private static final String PROP_WEIGHT = "weight"; private static final Comparator<BgpRoute> COMPARATOR = Comparator.comparing(BgpRoute::getAsPath) .thenComparing(BgpRoute::getClusterList, CommonUtil::compareCollection) .thenComparing(BgpRoute::getCommunities, CommonUtil::compareCollection) .thenComparing(BgpRoute::getDiscard) .thenComparing(BgpRoute::getLocalPreference) .thenComparing(BgpRoute::getOriginType) .thenComparing(BgpRoute::getOriginatorIp) .thenComparing(BgpRoute::getReceivedFromIp) .thenComparing(BgpRoute::getReceivedFromRouteReflectorClient) .thenComparing(BgpRoute::getSrcProtocol) .thenComparing(BgpRoute::getWeight); private static final long serialVersionUID = 1L; @Nonnull private final AsPath _asPath; @Nonnull private final SortedSet<Long> _clusterList; @Nonnull private final SortedSet<Long> _communities; private final boolean _discard; private final long _localPreference; private final long _med; @Nonnull private final Ip _nextHopIp; @Nonnull private final Ip _originatorIp; @Nonnull private final OriginType _originType; @Nonnull private final RoutingProtocol _protocol; @Nullable private final Ip _receivedFromIp; private final boolean _receivedFromRouteReflectorClient; @Nullable private final RoutingProtocol _srcProtocol; /* NOTE: Cisco-only attribute */ private final int _weight; /* Cache the hashcode */ private int _hashCode = 0; @JsonCreator private static BgpRoute jsonCreator( @Nullable @JsonProperty(PROP_NETWORK) Prefix network, @Nullable @JsonProperty(PROP_NEXT_HOP_IP) Ip nextHopIp, @JsonProperty(PROP_ADMINISTRATIVE_COST) int admin, @Nullable @JsonProperty(PROP_AS_PATH) AsPath asPath, @Nullable @JsonProperty(PROP_COMMUNITIES) SortedSet<Long> communities, @JsonProperty(PROP_DISCARD) boolean discard, @JsonProperty(PROP_LOCAL_PREFERENCE) long localPreference, @JsonProperty(PROP_METRIC) long med, @Nullable @JsonProperty(PROP_ORIGINATOR_IP) Ip originatorIp, @Nullable @JsonProperty(PROP_CLUSTER_LIST) SortedSet<Long> clusterList, @JsonProperty(PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT) boolean receivedFromRouteReflectorClient, @Nullable @JsonProperty(PROP_ORIGIN_TYPE) OriginType originType, @Nullable @JsonProperty(PROP_PROTOCOL) RoutingProtocol protocol, @Nullable @JsonProperty(PROP_RECEIVED_FROM_IP) Ip receivedFromIp, @Nullable @JsonProperty(PROP_SRC_PROTOCOL) RoutingProtocol srcProtocol, @JsonProperty(PROP_WEIGHT) int weight) { checkArgument(originatorIp != null, "Missing %s", PROP_ORIGINATOR_IP); checkArgument(originType != null, "Missing %s", PROP_ORIGIN_TYPE); checkArgument(protocol != null, "Missing %s", PROP_PROTOCOL); return new BgpRoute( network, nextHopIp, admin, asPath, communities, discard, localPreference, med, originatorIp, clusterList, receivedFromRouteReflectorClient, originType, protocol, receivedFromIp, srcProtocol, weight, false, false); } private BgpRoute( @Nullable Prefix network, @Nullable Ip nextHopIp, int admin, @Nullable AsPath asPath, @Nullable SortedSet<Long> communities, boolean discard, long localPreference, long med, Ip originatorIp, @Nullable SortedSet<Long> clusterList, @JsonProperty(PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT) boolean receivedFromRouteReflectorClient, OriginType originType, RoutingProtocol protocol, @Nullable Ip receivedFromIp, @Nullable RoutingProtocol srcProtocol, int weight, boolean nonForwarding, boolean nonRouting) { super(network, admin, nonRouting, nonForwarding); _asPath = firstNonNull(asPath, AsPath.empty()); _clusterList = clusterList == null ? ImmutableSortedSet.of() : ImmutableSortedSet.copyOf(clusterList); _communities = communities == null ? ImmutableSortedSet.of() : ImmutableSortedSet.copyOf(communities); _discard = discard; _localPreference = localPreference; _med = med; _nextHopIp = firstNonNull(nextHopIp, Route.UNSET_ROUTE_NEXT_HOP_IP); _originatorIp = originatorIp; _originType = originType; _protocol = protocol; _receivedFromIp = receivedFromIp; _receivedFromRouteReflectorClient = receivedFromRouteReflectorClient; _srcProtocol = srcProtocol; _weight = weight; } public static Builder builder() { return new Builder(); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof BgpRoute)) { return false; } BgpRoute other = (BgpRoute) o; return Objects.equals(_network, other._network) && _admin == other._admin && _discard == other._discard && _localPreference == other._localPreference && _med == other._med && _receivedFromRouteReflectorClient == other._receivedFromRouteReflectorClient && _weight == other._weight && Objects.equals(_asPath, other._asPath) && Objects.equals(_clusterList, other._clusterList) && Objects.equals(_communities, other._communities) && Objects.equals(_nextHopIp, other._nextHopIp) && Objects.equals(_originatorIp, other._originatorIp) && _originType == other._originType && _protocol == other._protocol && Objects.equals(_receivedFromIp, other._receivedFromIp) && _srcProtocol == other._srcProtocol; } @Override public int hashCode() { if (_hashCode != 0) { return _hashCode; } _hashCode = Objects.hash( _admin, _asPath, _clusterList, _communities, _discard, _localPreference, _med, _network, _nextHopIp, _originatorIp, _originType.ordinal(), _protocol.ordinal(), _receivedFromIp, _receivedFromRouteReflectorClient, _srcProtocol == null ? 0 : _srcProtocol.ordinal(), _weight); return _hashCode; } @Nonnull @JsonProperty(PROP_AS_PATH) public AsPath getAsPath() { return _asPath; } @Nonnull @JsonProperty(PROP_CLUSTER_LIST) public SortedSet<Long> getClusterList() { return _clusterList; } @Nonnull @JsonProperty(PROP_COMMUNITIES) public SortedSet<Long> getCommunities() { return _communities; } @JsonProperty(PROP_DISCARD) public boolean getDiscard() { return _discard; } @JsonProperty(PROP_LOCAL_PREFERENCE) public long getLocalPreference() { return _localPreference; } @JsonIgnore(false) @JsonProperty(PROP_METRIC) @Override public Long getMetric() { return _med; } @Nonnull @Override public String getNextHopInterface() { return Route.UNSET_NEXT_HOP_INTERFACE; } @Nonnull @JsonIgnore(false) @JsonProperty(PROP_NEXT_HOP_IP) @Override public Ip getNextHopIp() { return _nextHopIp; } @Nonnull @JsonProperty(PROP_ORIGINATOR_IP) public Ip getOriginatorIp() { return _originatorIp; } @Nonnull @JsonProperty(PROP_ORIGIN_TYPE) public OriginType getOriginType() { return _originType; } @Nonnull @JsonIgnore(false) @JsonProperty(PROP_PROTOCOL) @Override public RoutingProtocol getProtocol() { return _protocol; } @Nullable @JsonProperty(PROP_RECEIVED_FROM_IP) public Ip getReceivedFromIp() { return _receivedFromIp; } @JsonProperty(PROP_RECEIVED_FROM_ROUTE_REFLECTOR_CLIENT) public boolean getReceivedFromRouteReflectorClient() { return _receivedFromRouteReflectorClient; } @Nullable @JsonProperty(PROP_SRC_PROTOCOL) public RoutingProtocol getSrcProtocol() { return _srcProtocol; } @Override public int getTag() { return NO_TAG; } @JsonProperty(PROP_WEIGHT) public int getWeight() { return _weight; } @Override public int routeCompare(@Nonnull AbstractRoute rhs) { if (getClass() != rhs.getClass()) { return 0; } return COMPARATOR.compare(this, (BgpRoute) rhs); } }
BgpRoute: make cached hashcode volatile and transient (#2977)
projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/BgpRoute.java
BgpRoute: make cached hashcode volatile and transient (#2977)
<ide><path>rojects/batfish-common-protocol/src/main/java/org/batfish/datamodel/BgpRoute.java <ide> /* NOTE: Cisco-only attribute */ <ide> private final int _weight; <ide> /* Cache the hashcode */ <del> private int _hashCode = 0; <add> private transient volatile int _hashCode = 0; <ide> <ide> @JsonCreator <ide> private static BgpRoute jsonCreator(
JavaScript
agpl-3.0
f18167a57ff546d896f8b78af8a93c2185bbbad9
0
strekmann/samklang,strekmann/samklang
import React from 'react'; import Navigation from '../components/Navigation'; import Footer from '../components/Footer'; import { connect } from 'react-redux'; class App extends React.Component { render() { return ( <div> <Navigation viewer={this.props.viewer} site={this.props.site} users={this.props.users} socket={this.props.socket} params={this.props.params} /> {this.props.children} <Footer id={this.props.viewer.get('id')} /> </div> ); } } App.propTypes = { children: React.PropTypes.element, viewer: React.PropTypes.object, site: React.PropTypes.object, users: React.PropTypes.object, socket: React.PropTypes.object, params: React.PropTypes.object, }; function select(state) { return { viewer: state.get('viewer'), site: state.get('site'), users: state.get('users'), socket: state.get('socket'), }; } export default connect(select)(App);
src/common/containers/App.js
import React from 'react'; import Navigation from '../components/Navigation'; import Footer from '../components/Footer'; import { connect } from 'react-redux'; class App extends React.Component { render() { return ( <div> <Navigation viewer={this.props.viewer} site={this.props.site} users={this.props.users} socket={this.props.socket} params={this.props.params} /> {this.props.children} <Footer id={this.props.viewer.get('id')}/> </div> ); } } App.propTypes = { children: React.PropTypes.element, viewer: React.PropTypes.object, site: React.PropTypes.object, users: React.PropTypes.object, socket: React.PropTypes.object, params: React.PropTypes.object, }; function select(state) { return { viewer: state.get('viewer'), site: state.get('site'), users: state.get('users'), socket: state.get('socket'), }; } export default connect(select)(App);
eslint: react/jsx-space-before-closing
src/common/containers/App.js
eslint: react/jsx-space-before-closing
<ide><path>rc/common/containers/App.js <ide> params={this.props.params} <ide> /> <ide> {this.props.children} <del> <Footer id={this.props.viewer.get('id')}/> <add> <Footer id={this.props.viewer.get('id')} /> <ide> </div> <ide> ); <ide> }
Java
mpl-2.0
f3a0616b6dd477e2714bddc17c74836a309cb5eb
0
vertretungsplanme/substitution-schedule-parser,vertretungsplanme/substitution-schedule-parser,johan12345/substitution-schedule-parser,johan12345/substitution-schedule-parser
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2016 Johan v. Forstner * * 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 https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.parser; import me.vertretungsplan.objects.Substitution; import me.vertretungsplan.objects.SubstitutionScheduleData; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; /** * Utility class used by the {@link SubstitutionScheduleParser} implementations to set suitable colors depending on * the type of substitution. * <ul> * <li>Red: Lesson is cancelled or the students are supposed to work without a teacher ("EVA" = * Eigenverantwortliches Arbeiten)</li> * <li>Blue: Lesson will be given by a different teacher and/or with a different subject</li> * <li>Yellow: Lesson will take place at another time or swapped with another lesson</li> * <li>Green: Lesson will take place in another room</li> * <li>Brown: A special event will replace the lesson</li> * <li>Orange: Exam will be taken in this lesson</li> * <li>Gray: Break supervision (teacher)</li> * <li>Purple: Unknown</li> * </ul> * Colors from the <a href="https://material.google.com/style/color.html#color-color-palette">Material design</a> * color palette are used. */ public class ColorProvider { private static final HashMap<String, String> colorNames = new HashMap<>(); // *** Default color values *** private static final String[] RED_VALUES = {"Entfall", "EVA", "Entf.", "Entf", "Fällt aus!", "Fällt aus", "entfällt", "Freistunde", "Klasse frei", "Selbstlernen", "HA", "selb.Arb.", "Aufgaben", "selbst.", "Frei", "Ausfall", "Stillarbeit", "Absenz", "-> Entfall", "Freisetzung"}; private static final String[] BLUE_VALUES = {"Vertretung", "Sondereins.", "Statt-Vertretung", "Betreuung", "V", "VTR", "Vertr."}; private static final String[] YELLOW_VALUES = {"Tausch", "Verlegung", "Zusammenlegung", "Unterricht geändert", "Unterrichtstausch", "geändert", "statt", "Stundentausch"}; private static final String[] GREEN_VALUES = {"Raum", "KLA", "Raum-Vtr.", "Raumtausch", "Raumverlegung", "Raumänderung", "R. Änd.", "Raum beachten", "Raum-Vertr."}; private static final String[] BROWN_VALUES = {"Veranst.", "Veranstaltung", "Frei/Veranstaltung", "Hochschultag"}; private static final String[] ORANGE_VALUES = {"Klausur"}; private static final String[] GRAY_VALUES = {"Pausenaufsicht"}; private static final HashMap<String, String> defaultColorMap = new HashMap<>(); // Material Design colors static { // These colors are used for the substitutions recognized by default and should also be used for other // substitutions if possible. For description of their meanings, see below colorNames.put("red", "#F44336"); colorNames.put("blue", "#2196F3"); colorNames.put("yellow", "#FFA000"); // this is darker for readable white text, should be #FFEB3B colorNames.put("green", "#4CAF50"); colorNames.put("brown", "#795548"); colorNames.put("orange", "#FF9800"); colorNames.put("gray", "#9E9E9E"); // This color is used for substitutions that could not be recognized and should not be used otherwise // (if not explicitly requested by the school) colorNames.put("purple", "#9C27B0"); // These are additional colors from the Material Design spec that can be used for substitutions that do not fit // into the scheme below colorNames.put("pink", "#E91E63"); colorNames.put("deep_purple", "#673AB7"); colorNames.put("indigo", "#3F51B5"); colorNames.put("light_blue", "#03A9F4"); colorNames.put("cyan", "#00BCD4"); colorNames.put("teal", "#009688"); colorNames.put("light_green", "#8BC34A"); colorNames.put("lime", "#CDDC39"); colorNames.put("amber", "#FFC107"); colorNames.put("deep_orange", "#FF5722"); colorNames.put("blue_gray", "#607D8B"); colorNames.put("black", "#000000"); colorNames.put("white", "#FFFFFF"); } static { for (String string : RED_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("red")); for (String string : BLUE_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("blue")); for (String string : YELLOW_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("yellow")); for (String string : GREEN_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("green")); for (String string : BROWN_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("brown")); for (String string : ORANGE_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("orange")); for (String string : GRAY_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("gray")); } private HashMap<String, String> colorMap = new HashMap<>(); public ColorProvider(SubstitutionScheduleData data) { try { if (data.getData().has("colors")) { JSONObject colors = data.getData().getJSONObject("colors"); Iterator<?> keys = colors.keys(); while (keys.hasNext()) { String type = (String) keys.next(); String value = colors.getString(type); if (colorNames.containsKey(value)) { colorMap.put(type.toLowerCase(), colorNames.get(value)); } else { colorMap.put(type.toLowerCase(), value); } } } } catch (JSONException e) { throw new RuntimeException(e); } } /** * Get an appropriate color for a substitution based on its type * * @param type the type of the substitution ({@link Substitution#getType()}) * @return an appropriate color in hexadecimal format */ public String getColor(String type) { if (type == null) { return null; } else if (colorMap.containsKey(type.toLowerCase())) { return colorMap.get(type.toLowerCase()); } else if (defaultColorMap.containsKey(type.toLowerCase())) { return defaultColorMap.get(type.toLowerCase()); } else { return colorNames.get("purple"); } } }
parser/src/main/java/me/vertretungsplan/parser/ColorProvider.java
/* * substitution-schedule-parser - Java library for parsing schools' substitution schedules * Copyright (c) 2016 Johan v. Forstner * * 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 https://mozilla.org/MPL/2.0/. */ package me.vertretungsplan.parser; import me.vertretungsplan.objects.Substitution; import me.vertretungsplan.objects.SubstitutionScheduleData; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; /** * Utility class used by the {@link SubstitutionScheduleParser} implementations to set suitable colors depending on * the type of substitution. * <ul> * <li>Red: Lesson is cancelled or the students are supposed to work without a teacher ("EVA" = * Eigenverantwortliches Arbeiten)</li> * <li>Blue: Lesson will be given by a different teacher and/or with a different subject</li> * <li>Yellow: Lesson will take place at another time or swapped with another lesson</li> * <li>Green: Lesson will take place in another room</li> * <li>Brown: A special event will replace the lesson</li> * <li>Orange: Exam will be taken in this lesson</li> * <li>Gray: Break supervision (teacher)</li> * <li>Purple: Unknown</li> * </ul> * Colors from the <a href="https://material.google.com/style/color.html#color-color-palette">Material design</a> * color palette are used. */ public class ColorProvider { private static final HashMap<String, String> colorNames = new HashMap<>(); // *** Default color values *** private static final String[] RED_VALUES = {"Entfall", "EVA", "Entf.", "Entf", "Fällt aus!", "Fällt aus", "entfällt", "Freistunde", "Klasse frei", "Selbstlernen", "HA", "selb.Arb.", "Aufgaben", "selbst.", "Frei", "Ausfall", "Stillarbeit"}; private static final String[] BLUE_VALUES = {"Vertretung", "Sondereins.", "Statt-Vertretung", "Betreuung", "V", "VTR", "Vertr."}; private static final String[] YELLOW_VALUES = {"Tausch", "Verlegung", "Zusammenlegung", "Unterricht geändert", "Unterrichtstausch", "geändert", "statt", "Stundentausch"}; private static final String[] GREEN_VALUES = {"Raum", "KLA", "Raum-Vtr.", "Raumtausch", "Raumverlegung", "Raumänderung", "R. Änd.", "Raum beachten", "Raum-Vertr."}; private static final String[] BROWN_VALUES = {"Veranst.", "Veranstaltung", "Frei/Veranstaltung"}; private static final String[] ORANGE_VALUES = {"Klausur"}; private static final String[] GRAY_VALUES = {"Pausenaufsicht"}; private static final HashMap<String, String> defaultColorMap = new HashMap<>(); // Material Design colors static { // These colors are used for the substitutions recognized by default and should also be used for other // substitutions if possible. For description of their meanings, see below colorNames.put("red", "#F44336"); colorNames.put("blue", "#2196F3"); colorNames.put("yellow", "#FFA000"); // this is darker for readable white text, should be #FFEB3B colorNames.put("green", "#4CAF50"); colorNames.put("brown", "#795548"); colorNames.put("orange", "#FF9800"); colorNames.put("gray", "#9E9E9E"); // This color is used for substitutions that could not be recognized and should not be used otherwise // (if not explicitly requested by the school) colorNames.put("purple", "#9C27B0"); // These are additional colors from the Material Design spec that can be used for substitutions that do not fit // into the scheme below colorNames.put("pink", "#E91E63"); colorNames.put("deep_purple", "#673AB7"); colorNames.put("indigo", "#3F51B5"); colorNames.put("light_blue", "#03A9F4"); colorNames.put("cyan", "#00BCD4"); colorNames.put("teal", "#009688"); colorNames.put("light_green", "#8BC34A"); colorNames.put("lime", "#CDDC39"); colorNames.put("amber", "#FFC107"); colorNames.put("deep_orange", "#FF5722"); colorNames.put("blue_gray", "#607D8B"); colorNames.put("black", "#000000"); colorNames.put("white", "#FFFFFF"); } static { for (String string : RED_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("red")); for (String string : BLUE_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("blue")); for (String string : YELLOW_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("yellow")); for (String string : GREEN_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("green")); for (String string : BROWN_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("brown")); for (String string : ORANGE_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("orange")); for (String string : GRAY_VALUES) defaultColorMap.put(string.toLowerCase(), colorNames.get("gray")); } private HashMap<String, String> colorMap = new HashMap<>(); public ColorProvider(SubstitutionScheduleData data) { try { if (data.getData().has("colors")) { JSONObject colors = data.getData().getJSONObject("colors"); Iterator<?> keys = colors.keys(); while (keys.hasNext()) { String type = (String) keys.next(); String value = colors.getString(type); if (colorNames.containsKey(value)) { colorMap.put(type.toLowerCase(), colorNames.get(value)); } else { colorMap.put(type.toLowerCase(), value); } } } } catch (JSONException e) { throw new RuntimeException(e); } } /** * Get an appropriate color for a substitution based on its type * * @param type the type of the substitution ({@link Substitution#getType()}) * @return an appropriate color in hexadecimal format */ public String getColor(String type) { if (type == null) { return null; } else if (colorMap.containsKey(type.toLowerCase())) { return colorMap.get(type.toLowerCase()); } else if (defaultColorMap.containsKey(type.toLowerCase())) { return defaultColorMap.get(type.toLowerCase()); } else { return colorNames.get("purple"); } } }
More strings for ColorProvider
parser/src/main/java/me/vertretungsplan/parser/ColorProvider.java
More strings for ColorProvider
<ide><path>arser/src/main/java/me/vertretungsplan/parser/ColorProvider.java <ide> // *** Default color values *** <ide> private static final String[] RED_VALUES = {"Entfall", "EVA", "Entf.", "Entf", "Fällt aus!", "Fällt aus", <ide> "entfällt", "Freistunde", "Klasse frei", "Selbstlernen", "HA", "selb.Arb.", "Aufgaben", "selbst.", "Frei", <del> "Ausfall", "Stillarbeit"}; <add> "Ausfall", "Stillarbeit", "Absenz", "-> Entfall", "Freisetzung"}; <ide> private static final String[] BLUE_VALUES = {"Vertretung", "Sondereins.", "Statt-Vertretung", <ide> "Betreuung", "V", "VTR", "Vertr."}; <ide> private static final String[] YELLOW_VALUES = {"Tausch", "Verlegung", "Zusammenlegung", <ide> private static final String[] GREEN_VALUES = <ide> {"Raum", "KLA", "Raum-Vtr.", "Raumtausch", "Raumverlegung", "Raumänderung", "R. Änd.", "Raum beachten", <ide> "Raum-Vertr."}; <del> private static final String[] BROWN_VALUES = {"Veranst.", "Veranstaltung", "Frei/Veranstaltung"}; <add> private static final String[] BROWN_VALUES = {"Veranst.", "Veranstaltung", "Frei/Veranstaltung", "Hochschultag"}; <ide> private static final String[] ORANGE_VALUES = {"Klausur"}; <ide> private static final String[] GRAY_VALUES = {"Pausenaufsicht"}; <ide> private static final HashMap<String, String> defaultColorMap = new HashMap<>();
Java
apache-2.0
error: pathspec 'src/com/itmill/toolkit/tests/tickets/Ticket2209OL2.java' did not match any file(s) known to git
51953fd7685a9ad112708109130991e2a1ceacd5
1
sitexa/vaadin,Scarlethue/vaadin,mittop/vaadin,shahrzadmn/vaadin,oalles/vaadin,magi42/vaadin,peterl1084/framework,travisfw/vaadin,Flamenco/vaadin,Peppe/vaadin,mittop/vaadin,jdahlstrom/vaadin.react,asashour/framework,carrchang/vaadin,shahrzadmn/vaadin,kironapublic/vaadin,peterl1084/framework,oalles/vaadin,udayinfy/vaadin,fireflyc/vaadin,shahrzadmn/vaadin,asashour/framework,mstahv/framework,udayinfy/vaadin,kironapublic/vaadin,Peppe/vaadin,Legioth/vaadin,Darsstar/framework,Legioth/vaadin,fireflyc/vaadin,Peppe/vaadin,jdahlstrom/vaadin.react,Flamenco/vaadin,fireflyc/vaadin,kironapublic/vaadin,asashour/framework,sitexa/vaadin,jdahlstrom/vaadin.react,kironapublic/vaadin,sitexa/vaadin,magi42/vaadin,carrchang/vaadin,cbmeeks/vaadin,sitexa/vaadin,travisfw/vaadin,magi42/vaadin,Darsstar/framework,bmitc/vaadin,cbmeeks/vaadin,oalles/vaadin,mstahv/framework,synes/vaadin,mstahv/framework,shahrzadmn/vaadin,Darsstar/framework,bmitc/vaadin,sitexa/vaadin,peterl1084/framework,kironapublic/vaadin,travisfw/vaadin,peterl1084/framework,synes/vaadin,carrchang/vaadin,mstahv/framework,mittop/vaadin,jdahlstrom/vaadin.react,synes/vaadin,bmitc/vaadin,magi42/vaadin,synes/vaadin,Peppe/vaadin,oalles/vaadin,Scarlethue/vaadin,Darsstar/framework,udayinfy/vaadin,mittop/vaadin,carrchang/vaadin,Legioth/vaadin,mstahv/framework,Scarlethue/vaadin,bmitc/vaadin,Peppe/vaadin,synes/vaadin,Scarlethue/vaadin,fireflyc/vaadin,Darsstar/framework,Scarlethue/vaadin,oalles/vaadin,asashour/framework,travisfw/vaadin,peterl1084/framework,Legioth/vaadin,cbmeeks/vaadin,udayinfy/vaadin,Flamenco/vaadin,asashour/framework,travisfw/vaadin,magi42/vaadin,Flamenco/vaadin,Legioth/vaadin,udayinfy/vaadin,fireflyc/vaadin,shahrzadmn/vaadin,cbmeeks/vaadin,jdahlstrom/vaadin.react
package com.itmill.toolkit.tests.tickets; import com.itmill.toolkit.Application; import com.itmill.toolkit.ui.Button; import com.itmill.toolkit.ui.ComboBox; import com.itmill.toolkit.ui.Label; import com.itmill.toolkit.ui.OrderedLayout; import com.itmill.toolkit.ui.Window; import com.itmill.toolkit.ui.Button.ClickEvent; import com.itmill.toolkit.ui.Button.ClickListener; public class Ticket2209OL2 extends Application { private OrderedLayout gl; private ComboBox combo; private Label labelLong; @Override public void init() { setMainWindow(new Window()); getMainWindow().getLayout().setWidth("250px"); gl = new OrderedLayout(); gl.setSizeUndefined(); gl.setStyleName("borders"); getMainWindow().addComponent(gl); setTheme("tests-tickets"); combo = new ComboBox("Combo caption"); labelLong = new Label( "This should stay on one line or to wrap to multiple lines? At leas it should display all the text?. " + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"); gl.addComponent(combo); gl.addComponent(labelLong); Button b = new Button("Add label text", new ClickListener() { public void buttonClick(ClickEvent event) { labelLong.setValue(labelLong.getValue() + "-12345"); } }); getMainWindow().addComponent(b); } }
src/com/itmill/toolkit/tests/tickets/Ticket2209OL2.java
added test case svn changeset:5932/svn branch:trunk
src/com/itmill/toolkit/tests/tickets/Ticket2209OL2.java
added test case
<ide><path>rc/com/itmill/toolkit/tests/tickets/Ticket2209OL2.java <add>package com.itmill.toolkit.tests.tickets; <add> <add>import com.itmill.toolkit.Application; <add>import com.itmill.toolkit.ui.Button; <add>import com.itmill.toolkit.ui.ComboBox; <add>import com.itmill.toolkit.ui.Label; <add>import com.itmill.toolkit.ui.OrderedLayout; <add>import com.itmill.toolkit.ui.Window; <add>import com.itmill.toolkit.ui.Button.ClickEvent; <add>import com.itmill.toolkit.ui.Button.ClickListener; <add> <add>public class Ticket2209OL2 extends Application { <add> <add> private OrderedLayout gl; <add> private ComboBox combo; <add> private Label labelLong; <add> <add> @Override <add> public void init() { <add> setMainWindow(new Window()); <add> getMainWindow().getLayout().setWidth("250px"); <add> gl = new OrderedLayout(); <add> gl.setSizeUndefined(); <add> gl.setStyleName("borders"); <add> getMainWindow().addComponent(gl); <add> setTheme("tests-tickets"); <add> combo = new ComboBox("Combo caption"); <add> labelLong = new Label( <add> "This should stay on one line or to wrap to multiple lines? At leas it should display all the text?. " <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?" <add> + "A long label, longer than the combo box. Why doesn't it affect the width? And why is the gridlayout so high?"); <add> gl.addComponent(combo); <add> gl.addComponent(labelLong); <add> <add> Button b = new Button("Add label text", new ClickListener() { <add> <add> public void buttonClick(ClickEvent event) { <add> labelLong.setValue(labelLong.getValue() + "-12345"); <add> } <add> <add> }); <add> getMainWindow().addComponent(b); <add> } <add> <add>}
Java
mit
a4d19f44d7790a0e287f0fd4664ac79970dad0d3
0
Innovimax-SARL/mix-them
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; interface IByteOperation extends IOperation { /** * Processes operation and set new result in the ByteResult parameter. * @param b1 The first byte to mix (maybe -1) * @param b2 The second byte to mix (maybe -1) * @param result The previous operation result * @return The result of the operation (maybe null) * @throws MixException - If an mixing error occurs * @see innovimax.mixthem.operation.ByteResult */ void process(byte b1, byte b2, ByteResult result) throws MixException; }
src/main/java/innovimax/mixthem/operation/IByteOperation.java
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; interface IByteOperation extends IOperation { /** * Processes operation and set new result in the ByteResult parameter. * @param b1 The first byte to mix (maybe -1) * @param b2 The second byte to mix (maybe -1) * @param result The previous operation result * @return The result of the operation (maybe null) * @throws MixException - If an mixing error occurs * @see innovimax.mixthem.operation.ByteResult */ void process(int b1, int b2, ByteResult result) throws MixException; }
Update IByteOperation.java
src/main/java/innovimax/mixthem/operation/IByteOperation.java
Update IByteOperation.java
<ide><path>rc/main/java/innovimax/mixthem/operation/IByteOperation.java <ide> * @throws MixException - If an mixing error occurs <ide> * @see innovimax.mixthem.operation.ByteResult <ide> */ <del> void process(int b1, int b2, ByteResult result) throws MixException; <add> void process(byte b1, byte b2, ByteResult result) throws MixException; <ide> }
JavaScript
mit
d4783e04172a17b58f409abb72dd00947a65ba0c
0
jials/nusmods-wiki,jials/nusmods-wiki,jials/nusmods-wiki,jials/nusmods-wiki
'use strict'; angular.module('wiki').controller('PastTACtrl', function ($scope, $modal, $log, $http, $stateParams, Authentication) { $http.get('/' + $stateParams.moduleTitle).success(function(data){ if (data.pastTA.length !== 0) { $scope.pastTAs = data.pastTA[data.pastTA.length - 1].faculties; } else { $scope.pastTAs = []; } }); $scope.open = function (size) { var modalInstance = $modal.open({ templateUrl: 'PastTAModalContent.html', controller: 'PastTAModalInstanceCtrl', size: size, resolve: { pastTAs: function () { return $scope.pastTAs; } } }); }; }); // Please note that $modalInstance represents a modal window (instance) dependency. // It is not the same as the $modal service used above. angular.module('wiki').controller('PastTAModalInstanceCtrl', function ($scope, $modalInstance, pastTAs, $http, $stateParams, Authentication) { for (var j = 0; j < pastTAs.length; j++) { delete pastTAs[j]._id; } $scope.pastTAs = pastTAs; $scope.save = function () { $http.put('/' + $stateParams.moduleTitle, {editedBy: Authentication.user.id, type: 'pastTA', pastTA: $scope.pastTAs}).success(function(data){ }); $modalInstance.close(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; $scope.add = function () { $scope.pastTAs.push({ name: '', academicYearStart: '', academicYearEnd: '', photo: '' }); }; $scope.uploadFile = function(index) { filepicker.setKey('ABMzRUFagRuyMHNU9Jksvz'); filepicker.pickMultiple( { mimetypes: 'image/*', container: 'modal', services:['COMPUTER', 'DROPBOX', 'FACEBOOK', 'GMAIL', 'GOOGLE_DRIVE', 'INSTAGRAM'], maxSize: '1584*2016', maxFiles: '1', }, function(Blob){ $scope.pastTA[index].photo = Blob[0].url; }, function(FPError){ console.log(FPError.toString()); } ); }; });
public/modules/wiki/controllers/wiki.pastta.modal.client.controller.js
'use strict'; angular.module('wiki').controller('PastTACtrl', function ($scope, $modal, $log, $http, $stateParams, Authentication) { $http.get('/' + $stateParams.moduleTitle).success(function(data){ if (data.pastTA.length !== 0) { $scope.pastTAs = data.pastTA[data.pastTA.length - 1].faculties; } else { $scope.pastTAs = []; } }); $scope.open = function (size) { var modalInstance = $modal.open({ templateUrl: 'PastTAModalContent.html', controller: 'PastTAModalInstanceCtrl', size: size, resolve: { pastTAs: function () { return $scope.pastTAs; } } }); }; }); // Please note that $modalInstance represents a modal window (instance) dependency. // It is not the same as the $modal service used above. angular.module('wiki').controller('PastTAModalInstanceCtrl', function ($scope, $modalInstance, pastTAs, $http, $stateParams, Authentication) { for (var j = 0; j < pastTAs.length; j++) { delete pastTAs[j]._id; } $scope.pastTAs = pastTAs; $scope.save = function () { alert(JSON.stringify($scope.pastTAs)); $http.put('/' + $stateParams.moduleTitle, {editedBy: Authentication.user.id, type: 'pastTA', pastTA: $scope.pastTAs}).success(function(data){ }); $modalInstance.close(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; $scope.add = function () { $scope.pastTAs.push({ name: '', academicYearStart: '', academicYearEnd: '', photo: '' }); }; $scope.uploadFile = function(index) { filepicker.setKey('ABMzRUFagRuyMHNU9Jksvz'); filepicker.pickMultiple( { mimetypes: 'image/*', container: 'modal', services:['COMPUTER', 'DROPBOX', 'FACEBOOK', 'GMAIL', 'GOOGLE_DRIVE', 'INSTAGRAM'], maxSize: '1584*2016', maxFiles: '1', }, function(Blob){ $scope.pastTA[index].photo = Blob[0].url; }, function(FPError){ console.log(FPError.toString()); } ); }; });
Remove pastTA alert
public/modules/wiki/controllers/wiki.pastta.modal.client.controller.js
Remove pastTA alert
<ide><path>ublic/modules/wiki/controllers/wiki.pastta.modal.client.controller.js <ide> $scope.pastTAs = pastTAs; <ide> <ide> $scope.save = function () { <del> alert(JSON.stringify($scope.pastTAs)); <ide> $http.put('/' + $stateParams.moduleTitle, {editedBy: Authentication.user.id, type: 'pastTA', pastTA: $scope.pastTAs}).success(function(data){ <ide> }); <ide> $modalInstance.close();