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
47632bb6f7bd68cc95aa7fc4bbfb6c273bb55933
0
mduerig/jackrabbit-oak,leftouterjoin/jackrabbit-oak,catholicon/jackrabbit-oak,leftouterjoin/jackrabbit-oak,kwin/jackrabbit-oak,afilimonov/jackrabbit-oak,stillalex/jackrabbit-oak,code-distillery/jackrabbit-oak,mduerig/jackrabbit-oak,afilimonov/jackrabbit-oak,kwin/jackrabbit-oak,stillalex/jackrabbit-oak,catholicon/jackrabbit-oak,meggermo/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,meggermo/jackrabbit-oak,bdelacretaz/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,chetanmeh/jackrabbit-oak,ieb/jackrabbit-oak,tripodsan/jackrabbit-oak,bdelacretaz/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,joansmith/jackrabbit-oak,rombert/jackrabbit-oak,anchela/jackrabbit-oak,catholicon/jackrabbit-oak,rombert/jackrabbit-oak,rombert/jackrabbit-oak,joansmith/jackrabbit-oak,chetanmeh/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,joansmith/jackrabbit-oak,tripodsan/jackrabbit-oak,mduerig/jackrabbit-oak,bdelacretaz/jackrabbit-oak,ieb/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,ieb/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,tripodsan/jackrabbit-oak,alexkli/jackrabbit-oak,stillalex/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,francescomari/jackrabbit-oak,leftouterjoin/jackrabbit-oak,alexkli/jackrabbit-oak,kwin/jackrabbit-oak,chetanmeh/jackrabbit-oak,joansmith/jackrabbit-oak,leftouterjoin/jackrabbit-oak,joansmith/jackrabbit-oak,code-distillery/jackrabbit-oak,mduerig/jackrabbit-oak,mduerig/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,bdelacretaz/jackrabbit-oak,meggermo/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,ieb/jackrabbit-oak,alexparvulescu/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,catholicon/jackrabbit-oak,francescomari/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,yesil/jackrabbit-oak,alexparvulescu/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,anchela/jackrabbit-oak,afilimonov/jackrabbit-oak,rombert/jackrabbit-oak,code-distillery/jackrabbit-oak,kwin/jackrabbit-oak,chetanmeh/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,yesil/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,anchela/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,yesil/jackrabbit-oak,anchela/jackrabbit-oak,meggermo/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,tripodsan/jackrabbit-oak,kwin/jackrabbit-oak,afilimonov/jackrabbit-oak
/* * 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.jackrabbit.oak.plugins.index.lucene; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.plugins.index.IndexUpdateProvider; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.EditorHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.test.ISO8601; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.junit.After; import org.junit.Test; import static com.google.common.collect.ImmutableSet.of; import static javax.jcr.PropertyType.TYPENAME_STRING; import static org.apache.jackrabbit.oak.api.Type.STRINGS; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME; import static org.apache.jackrabbit.oak.plugins.index.lucene.FieldNames.PATH; import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.INCLUDE_PROPERTY_NAMES; import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.VERSION; import static org.apache.jackrabbit.oak.plugins.index.lucene.util.LuceneIndexHelper.newLuceneIndexDefinition; import static org.apache.jackrabbit.oak.plugins.memory.PropertyStates.createProperty; import static org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent.INITIAL_CONTENT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; public class LuceneIndexEditorTest { private static final Analyzer analyzer = LuceneIndexConstants.ANALYZER; private static final EditorHook HOOK = new EditorHook( new IndexUpdateProvider( new LuceneIndexEditorProvider().with(analyzer))); private NodeState root = INITIAL_CONTENT; private NodeBuilder builder = root.builder(); private IndexTracker tracker = new IndexTracker(); private IndexNode indexNode; @Test public void testLuceneWithFullText() throws Exception { NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); builder.child("test").setProperty("price", 100); NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); assertEquals("/test", query("foo:fox")); assertNull("Non string properties not indexed by default", getPath(NumericRangeQuery.newLongRange("price", 100L, 100L, true, true))); } @Test public void testLuceneWithNonFullText() throws Exception { NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); NodeBuilder nb = newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo", "price", "weight", "bool", "creationTime"), STRINGS)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); builder.child("test").setProperty("bar", "kite is flying"); builder.child("test").setProperty("price", 100); builder.child("test").setProperty("weight", 10.0); builder.child("test").setProperty("bool", true); builder.child("test").setProperty("truth", true); builder.child("test").setProperty("creationTime", createCal("05/06/2014")); NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); assertNull("Fulltext search should not work", query("foo:fox")); assertEquals("/test", getPath(new TermQuery(new Term("foo", "fox is jumping")))); assertNull("bar must NOT be indexed", getPath(new TermQuery(new Term("bar", "kite is flying")))); //Long assertEquals("/test", getPath(NumericRangeQuery.newDoubleRange("weight", 8D, 12D, true, true))); //Double assertEquals("/test", getPath(NumericRangeQuery.newLongRange("price", 100L, 100L, true, true))); //Boolean assertEquals("/test", getPath(new TermQuery(new Term("bool", "true")))); assertNull("truth must NOT be indexed", getPath(new TermQuery(new Term("truth", "true")))); //Date assertEquals("/test", getPath(NumericRangeQuery.newLongRange("creationTime", dateToTime("05/05/2014"), dateToTime("05/07/2014"), true, true))); } @Test public void noOfDocsIndexedNonFullText() throws Exception{ NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); NodeBuilder nb = newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo"), STRINGS)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); builder.child("test2").setProperty("bar", "kite is flying"); builder.child("test3").setProperty("foo", "wind is blowing"); NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); assertEquals(2, getSearcher().getIndexReader().numDocs()); } //@Test public void checkLuceneIndexFileUpdates() throws Exception{ NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); NodeBuilder nb = newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo" , "bar", "baz"), STRINGS)); //nb.removeProperty(REINDEX_PROPERTY_NAME); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); //InfoStream.setDefault(new PrintStreamInfoStream(System.out)); before = commitAndDump(before, builder.getNodeState()); builder = before.builder(); builder.child("test2").setProperty("bar", "ship is sinking"); before = commitAndDump(before, builder.getNodeState()); builder = before.builder(); builder.child("test3").setProperty("baz", "horn is blowing"); before = commitAndDump(before, builder.getNodeState()); builder = before.builder(); builder.child("test2").remove(); before = commitAndDump(before, builder.getNodeState()); builder = before.builder(); builder.child("test2").setProperty("bar", "ship is back again"); before = commitAndDump(before, builder.getNodeState()); } @After public void releaseIndexNode(){ if(indexNode != null){ indexNode.release(); } indexNode = null; } private String query(String query) throws IOException, ParseException { QueryParser queryParser = new QueryParser(VERSION, "", analyzer); return getPath(queryParser.parse(query)); } private String getPath(Query query) throws IOException { TopDocs td = getSearcher().search(query, 100); if (td.totalHits > 0){ if(td.totalHits > 1){ fail("More than 1 result found for query " + query); } return getSearcher().getIndexReader().document(td.scoreDocs[0].doc).get(PATH); } return null; } private IndexSearcher getSearcher(){ if(indexNode == null){ indexNode = tracker.acquireIndexNode("/oak:index/lucene"); } return indexNode.getSearcher(); } private NodeState commitAndDump(NodeState before, NodeState after) throws CommitFailedException, IOException { NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); dumpIndexDir(); return indexed; } private void dumpIndexDir() throws IOException { Directory dir = ((DirectoryReader)getSearcher().getIndexReader()).directory(); System.out.println("================"); String[] fileNames = dir.listAll(); Arrays.sort(fileNames); for (String file : fileNames){ System.out.printf("%s - %d %n", file, dir.fileLength(file)); } releaseIndexNode(); } static Calendar createCal(String dt) throws java.text.ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(dt)); return cal; } static long dateToTime(String dt) throws java.text.ParseException { return FieldFactory.dateToLong(ISO8601.format(createCal(dt))); } }
oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorTest.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.jackrabbit.oak.plugins.index.lucene; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.plugins.index.IndexUpdateProvider; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.EditorHook; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.jackrabbit.test.ISO8601; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.junit.After; import org.junit.Test; import static com.google.common.collect.ImmutableSet.of; import static javax.jcr.PropertyType.TYPENAME_STRING; import static org.apache.jackrabbit.oak.api.Type.STRINGS; import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.INDEX_DEFINITIONS_NAME; import static org.apache.jackrabbit.oak.plugins.index.lucene.FieldNames.PATH; import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.INCLUDE_PROPERTY_NAMES; import static org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexConstants.VERSION; import static org.apache.jackrabbit.oak.plugins.index.lucene.util.LuceneIndexHelper.newLuceneIndexDefinition; import static org.apache.jackrabbit.oak.plugins.memory.PropertyStates.createProperty; import static org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent.INITIAL_CONTENT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; public class LuceneIndexEditorTest { private static final Analyzer analyzer = LuceneIndexConstants.ANALYZER; private static final EditorHook HOOK = new EditorHook( new IndexUpdateProvider( new LuceneIndexEditorProvider().with(analyzer))); private NodeState root = INITIAL_CONTENT; private NodeBuilder builder = root.builder(); private IndexTracker tracker = new IndexTracker(); private IndexNode indexNode; @Test public void testLuceneWithFullText() throws Exception { NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); builder.child("test").setProperty("price", 100); NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); assertEquals("/test", query("foo:fox")); assertNull("Non string properties not indexed by default", getPath(NumericRangeQuery.newLongRange("price", 100L, 100L, true, true))); } @Test public void testLuceneWithNonFullText() throws Exception { NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); NodeBuilder nb = newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo", "price", "weight", "bool", "creationTime"), STRINGS)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); builder.child("test").setProperty("bar", "kite is flying"); builder.child("test").setProperty("price", 100); builder.child("test").setProperty("weight", 10.0); builder.child("test").setProperty("bool", true); builder.child("test").setProperty("truth", true); builder.child("test").setProperty("creationTime", createCal("05/06/2014")); NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); assertNull("Fulltext search should not work", query("foo:fox")); assertEquals("/test", getPath(new TermQuery(new Term("foo", "fox is jumping")))); assertNull("bar must NOT be indexed", getPath(new TermQuery(new Term("bar", "kite is flying")))); //Long assertEquals("/test", getPath(NumericRangeQuery.newDoubleRange("weight", 8D, 12D, true, true))); //Double assertEquals("/test", getPath(NumericRangeQuery.newLongRange("price", 100L, 100L, true, true))); //Boolean assertEquals("/test", getPath(new TermQuery(new Term("bool", "true")))); assertNull("truth must NOT be indexed", getPath(new TermQuery(new Term("truth", "true")))); //Date assertEquals("/test", getPath(NumericRangeQuery.newLongRange("creationTime", dateToTime("05/05/2014"), dateToTime("05/07/2014"), true, true))); } @Test public void noOfDocsIndexedNonFullText() throws Exception{ NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); NodeBuilder nb = newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo"), STRINGS)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); builder.child("test2").setProperty("bar", "kite is flying"); builder.child("test3").setProperty("foo", "wind is blowing"); NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); assertEquals(2, getSearcher().getIndexReader().numDocs()); } //@Test public void checkLuceneIndexFileUpdates() throws Exception{ NodeBuilder index = builder.child(INDEX_DEFINITIONS_NAME); NodeBuilder nb = newLuceneIndexDefinition(index, "lucene", of(TYPENAME_STRING)); nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo" , "bar", "baz"), STRINGS)); NodeState before = builder.getNodeState(); builder.child("test").setProperty("foo", "fox is jumping"); before = commitAndDump(before); builder.child("test2").setProperty("bar", "ship is sinking"); before = commitAndDump(before); builder.child("test3").setProperty("baz", "horn is blowing"); before = commitAndDump(before); builder.child("test2").remove(); before = commitAndDump(before); builder.child("test2").setProperty("bar", "ship is back again"); before = commitAndDump(before); } @After public void releaseIndexNode(){ if(indexNode != null){ indexNode.release(); } indexNode = null; } private String query(String query) throws IOException, ParseException { QueryParser queryParser = new QueryParser(VERSION, "", analyzer); return getPath(queryParser.parse(query)); } private String getPath(Query query) throws IOException { TopDocs td = getSearcher().search(query, 100); if (td.totalHits > 0){ if(td.totalHits > 1){ fail("More than 1 result found for query " + query); } return getSearcher().getIndexReader().document(td.scoreDocs[0].doc).get(PATH); } return null; } private IndexSearcher getSearcher(){ if(indexNode == null){ indexNode = tracker.acquireIndexNode("/oak:index/lucene"); } return indexNode.getSearcher(); } private NodeState commitAndDump(NodeState before) throws CommitFailedException, IOException { NodeState after = builder.getNodeState(); NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); tracker.update(indexed); dumpIndexDir(); return after; } private void dumpIndexDir() throws IOException { Directory dir = ((DirectoryReader)getSearcher().getIndexReader()).directory(); System.out.println("================"); for (String file : dir.listAll()){ System.out.printf("%s - %d %n", file, dir.fileLength(file)); } releaseIndexNode(); } static Calendar createCal(String dt) throws java.text.ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(dt)); return cal; } static long dateToTime(String dt) throws java.text.ParseException { return FieldFactory.dateToLong(ISO8601.format(createCal(dt))); } }
OAK-2005 - Use separate Lucene index for performing property related queries Modifying the test logic to ensure that previous Lucene index is not lost. With this change Lucene does not modify existing files git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1634504 13f79535-47bb-0310-9956-ffa450edef68
oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorTest.java
OAK-2005 - Use separate Lucene index for performing property related queries
<ide><path>ak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/LuceneIndexEditorTest.java <ide> <ide> import java.io.IOException; <ide> import java.text.SimpleDateFormat; <add>import java.util.Arrays; <ide> import java.util.Calendar; <ide> <ide> import org.apache.jackrabbit.oak.api.CommitFailedException; <ide> of(TYPENAME_STRING)); <ide> nb.setProperty(LuceneIndexConstants.FULL_TEXT_ENABLED, false); <ide> nb.setProperty(createProperty(INCLUDE_PROPERTY_NAMES, of("foo" , "bar", "baz"), STRINGS)); <del> <del> NodeState before = builder.getNodeState(); <del> builder.child("test").setProperty("foo", "fox is jumping"); <del> before = commitAndDump(before); <del> <add> //nb.removeProperty(REINDEX_PROPERTY_NAME); <add> <add> NodeState before = builder.getNodeState(); <add> builder.child("test").setProperty("foo", "fox is jumping"); <add> <add> //InfoStream.setDefault(new PrintStreamInfoStream(System.out)); <add> before = commitAndDump(before, builder.getNodeState()); <add> <add> builder = before.builder(); <ide> builder.child("test2").setProperty("bar", "ship is sinking"); <del> before = commitAndDump(before); <del> <add> before = commitAndDump(before, builder.getNodeState()); <add> <add> builder = before.builder(); <ide> builder.child("test3").setProperty("baz", "horn is blowing"); <del> before = commitAndDump(before); <del> <add> before = commitAndDump(before, builder.getNodeState()); <add> <add> builder = before.builder(); <ide> builder.child("test2").remove(); <del> before = commitAndDump(before); <del> <add> before = commitAndDump(before, builder.getNodeState()); <add> <add> builder = before.builder(); <ide> builder.child("test2").setProperty("bar", "ship is back again"); <del> before = commitAndDump(before); <add> before = commitAndDump(before, builder.getNodeState()); <ide> } <ide> <ide> @After <ide> return indexNode.getSearcher(); <ide> } <ide> <del> private NodeState commitAndDump(NodeState before) throws CommitFailedException, IOException { <del> NodeState after = builder.getNodeState(); <add> private NodeState commitAndDump(NodeState before, NodeState after) throws CommitFailedException, IOException { <ide> NodeState indexed = HOOK.processCommit(before, after, CommitInfo.EMPTY); <ide> tracker.update(indexed); <ide> dumpIndexDir(); <del> return after; <add> return indexed; <ide> } <ide> <ide> private void dumpIndexDir() throws IOException { <ide> Directory dir = ((DirectoryReader)getSearcher().getIndexReader()).directory(); <ide> <ide> System.out.println("================"); <del> for (String file : dir.listAll()){ <add> String[] fileNames = dir.listAll(); <add> Arrays.sort(fileNames); <add> for (String file : fileNames){ <ide> System.out.printf("%s - %d %n", file, dir.fileLength(file)); <ide> } <ide> releaseIndexNode();
Java
epl-1.0
7a9473dcdc48954b63893c7f258fe63a2713e7e6
0
dim1989/zhangzhoujun.github.io,dim1989/zhangzhoujun.github.io,dim1989/zhangzhoujun.github.io,dim1989/zhangzhoujun.github.io,dim1989/zhangzhoujun.github.io
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.myvolley.volley.toolbox; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import com.android.myvolley.volley.AuthFailureError; import com.android.myvolley.volley.Request; import com.android.myvolley.volley.Request.Method; /** * An {@link HttpStack} based on {@link HttpURLConnection}. */ public class HurlStack implements HttpStack { private static final String HEADER_CONTENT_TYPE = "Content-Type"; /** * An interface for transforming URLs before use. */ public interface UrlRewriter { /** * Returns a URL to use instead of the provided one, or null to indicate * this URL should not be used at all. */ public String rewriteUrl(String originalUrl); } private final UrlRewriter mUrlRewriter; private final SSLSocketFactory mSslSocketFactory; public HurlStack() { this(null); } /** * @param urlRewriter * Rewriter to use for request URLs */ public HurlStack(UrlRewriter urlRewriter) { this(urlRewriter, null); } /** * @param urlRewriter * Rewriter to use for request URLs * @param sslSocketFactory * SSL factory to use for HTTPS connections */ public HurlStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) { mUrlRewriter = urlRewriter; mSslSocketFactory = sslSocketFactory; } @Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders(request.getHeadType())); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; } /** * Initializes an {@link HttpEntity} from the given * {@link HttpURLConnection}. * * @param connection * @return an HttpEntity populated with data from <code>connection</code>. */ private static HttpEntity entityFromConnection(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream; try { inputStream = connection.getInputStream(); } catch (IOException ioe) { inputStream = connection.getErrorStream(); } entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; } /** * Create an {@link HttpURLConnection} for the specified {@code url}. */ protected HttpURLConnection createConnection(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); } /** * Opens an {@link HttpURLConnection} with parameters. * * @param url * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; } @SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length // explicitly, // since this is handled by HttpURLConnection using the size of // the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody); out.close(); } break; case Method.GET: // Not necessary to set the request method because connection // defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); addBodyIfExists(connection, request); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.PATCH: connection.setRequestMethod("PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } } private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
MyVolley/app/src/main/java/com/android/myvolley/volley/toolbox/HurlStack.java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.myvolley.volley.toolbox; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import com.android.myvolley.volley.AuthFailureError; import com.android.myvolley.volley.Request; import com.android.myvolley.volley.Request.Method; /** * An {@link HttpStack} based on {@link HttpURLConnection}. */ public class HurlStack implements HttpStack { private static final String HEADER_CONTENT_TYPE = "Content-Type"; /** * An interface for transforming URLs before use. */ public interface UrlRewriter { /** * Returns a URL to use instead of the provided one, or null to indicate * this URL should not be used at all. */ public String rewriteUrl(String originalUrl); } private final UrlRewriter mUrlRewriter; private final SSLSocketFactory mSslSocketFactory; public HurlStack() { this(null); } /** * @param urlRewriter Rewriter to use for request URLs */ public HurlStack(UrlRewriter urlRewriter) { this(urlRewriter, null); } /** * @param urlRewriter Rewriter to use for request URLs * @param sslSocketFactory SSL factory to use for HTTPS connections */ public HurlStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) { mUrlRewriter = urlRewriter; mSslSocketFactory = sslSocketFactory; } @Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders(request.getHeadType())); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; } /** * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}. * @param connection * @return an HttpEntity populated with data from <code>connection</code>. */ private static HttpEntity entityFromConnection(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream; try { inputStream = connection.getInputStream(); } catch (IOException ioe) { inputStream = connection.getErrorStream(); } entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; } /** * Create an {@link HttpURLConnection} for the specified {@code url}. */ protected HttpURLConnection createConnection(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); } /** * Opens an {@link HttpURLConnection} with parameters. * @param url * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); } return connection; } @SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length explicitly, // since this is handled by HttpURLConnection using the size of the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody); out.close(); } break; case Method.GET: // Not necessary to set the request method because connection defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); addBodyIfExists(connection, request); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.PATCH: connection.setRequestMethod("PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } } private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
修改http请求支持delete请求
MyVolley/app/src/main/java/com/android/myvolley/volley/toolbox/HurlStack.java
修改http请求支持delete请求
<ide><path>yVolley/app/src/main/java/com/android/myvolley/volley/toolbox/HurlStack.java <ide> public String rewriteUrl(String originalUrl); <ide> } <ide> <del> private final UrlRewriter mUrlRewriter; <add> private final UrlRewriter mUrlRewriter; <ide> private final SSLSocketFactory mSslSocketFactory; <ide> <ide> public HurlStack() { <ide> } <ide> <ide> /** <del> * @param urlRewriter Rewriter to use for request URLs <add> * @param urlRewriter <add> * Rewriter to use for request URLs <ide> */ <ide> public HurlStack(UrlRewriter urlRewriter) { <ide> this(urlRewriter, null); <ide> } <ide> <ide> /** <del> * @param urlRewriter Rewriter to use for request URLs <del> * @param sslSocketFactory SSL factory to use for HTTPS connections <add> * @param urlRewriter <add> * Rewriter to use for request URLs <add> * @param sslSocketFactory <add> * SSL factory to use for HTTPS connections <ide> */ <ide> public HurlStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) { <ide> mUrlRewriter = urlRewriter; <ide> } <ide> <ide> @Override <del> public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) <del> throws IOException, AuthFailureError { <add> public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { <ide> String url = request.getUrl(); <ide> HashMap<String, String> map = new HashMap<String, String>(); <ide> map.putAll(request.getHeaders(request.getHeadType())); <ide> ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); <ide> int responseCode = connection.getResponseCode(); <ide> if (responseCode == -1) { <del> // -1 is returned by getResponseCode() if the response code could not be retrieved. <del> // Signal to the caller that something was wrong with the connection. <add> // -1 is returned by getResponseCode() if the response code could <add> // not be retrieved. <add> // Signal to the caller that something was wrong with the <add> // connection. <ide> throw new IOException("Could not retrieve response code from HttpUrlConnection."); <ide> } <del> StatusLine responseStatus = new BasicStatusLine(protocolVersion, <del> connection.getResponseCode(), connection.getResponseMessage()); <add> StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); <ide> BasicHttpResponse response = new BasicHttpResponse(responseStatus); <ide> response.setEntity(entityFromConnection(connection)); <ide> for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { <ide> } <ide> <ide> /** <del> * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}. <add> * Initializes an {@link HttpEntity} from the given <add> * {@link HttpURLConnection}. <add> * <ide> * @param connection <ide> * @return an HttpEntity populated with data from <code>connection</code>. <ide> */ <ide> <ide> /** <ide> * Opens an {@link HttpURLConnection} with parameters. <add> * <ide> * @param url <ide> * @return an open connection <ide> * @throws IOException <ide> <ide> // use caller-provided custom SslSocketFactory, if any, for HTTPS <ide> if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { <del> ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); <add> ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); <ide> } <ide> <ide> return connection; <ide> } <ide> <ide> @SuppressWarnings("deprecation") <del> /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, <del> Request<?> request) throws IOException, AuthFailureError { <add> /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { <ide> switch (request.getMethod()) { <del> case Method.DEPRECATED_GET_OR_POST: <del> // This is the deprecated way that needs to be handled for backwards compatibility. <del> // If the request's post body is null, then the assumption is that the request is <del> // GET. Otherwise, it is assumed that the request is a POST. <del> byte[] postBody = request.getPostBody(); <del> if (postBody != null) { <del> // Prepare output. There is no need to set Content-Length explicitly, <del> // since this is handled by HttpURLConnection using the size of the prepared <del> // output stream. <del> connection.setDoOutput(true); <del> connection.setRequestMethod("POST"); <del> connection.addRequestProperty(HEADER_CONTENT_TYPE, <del> request.getPostBodyContentType()); <del> DataOutputStream out = new DataOutputStream(connection.getOutputStream()); <del> out.write(postBody); <del> out.close(); <del> } <del> break; <del> case Method.GET: <del> // Not necessary to set the request method because connection defaults to GET but <del> // being explicit here. <del> connection.setRequestMethod("GET"); <del> break; <del> case Method.DELETE: <del> connection.setRequestMethod("DELETE"); <del> addBodyIfExists(connection, request); <del> break; <del> case Method.POST: <add> case Method.DEPRECATED_GET_OR_POST: <add> // This is the deprecated way that needs to be handled for backwards <add> // compatibility. <add> // If the request's post body is null, then the assumption is that <add> // the request is <add> // GET. Otherwise, it is assumed that the request is a POST. <add> byte[] postBody = request.getPostBody(); <add> if (postBody != null) { <add> // Prepare output. There is no need to set Content-Length <add> // explicitly, <add> // since this is handled by HttpURLConnection using the size of <add> // the prepared <add> // output stream. <add> connection.setDoOutput(true); <ide> connection.setRequestMethod("POST"); <del> addBodyIfExists(connection, request); <del> break; <del> case Method.PUT: <del> connection.setRequestMethod("PUT"); <del> addBodyIfExists(connection, request); <del> break; <del> case Method.PATCH: <del> connection.setRequestMethod("PATCH"); <del> addBodyIfExists(connection, request); <del> break; <del> default: <del> throw new IllegalStateException("Unknown method type."); <del> } <del> } <del> <del> private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) <del> throws IOException, AuthFailureError { <add> connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); <add> DataOutputStream out = new DataOutputStream(connection.getOutputStream()); <add> out.write(postBody); <add> out.close(); <add> } <add> break; <add> case Method.GET: <add> // Not necessary to set the request method because connection <add> // defaults to GET but <add> // being explicit here. <add> connection.setRequestMethod("GET"); <add> break; <add> case Method.DELETE: <add> connection.setRequestMethod("DELETE"); <add> addBodyIfExists(connection, request); <add> break; <add> case Method.POST: <add> connection.setRequestMethod("POST"); <add> addBodyIfExists(connection, request); <add> break; <add> case Method.PUT: <add> connection.setRequestMethod("PUT"); <add> addBodyIfExists(connection, request); <add> break; <add> case Method.PATCH: <add> connection.setRequestMethod("PATCH"); <add> addBodyIfExists(connection, request); <add> break; <add> default: <add> throw new IllegalStateException("Unknown method type."); <add> } <add> } <add> <add> private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { <ide> byte[] body = request.getBody(); <ide> if (body != null) { <ide> connection.setDoOutput(true);
Java
mit
2ecff67ae55c8f50b4c2ae1d6b60f8492ecfb875
0
dreamhead/moco,dreamhead/moco
package com.github.dreamhead.moco.parser.model; import com.github.dreamhead.moco.ResponseBase; import com.github.dreamhead.moco.RestSetting; import com.github.dreamhead.moco.RestSettingBuilder; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import java.util.List; import static com.google.common.collect.FluentIterable.from; public abstract class RestBaseSetting { protected RequestSetting request; protected ResponseSetting response; protected abstract RestSettingBuilder startRestSetting(); @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("request", request) .add("response", response) .toString(); } final RestSetting toRestSetting() { if (response == null) { throw new IllegalArgumentException("Response is expected in rest setting"); } return this.getRestSettingBuilder().response(response.getResponseHandler()); } private ResponseBase<RestSetting> getRestSettingBuilder() { RestSettingBuilder builder = this.startRestSetting(); if (request != null) { return builder.request(request.getRequestMatcher()); } return builder; } private static <T extends RestBaseSetting> Function<T, RestSetting> toSetting() { return new Function<T, RestSetting>() { @Override public RestSetting apply(final T setting) { return setting.toRestSetting(); } }; } public static Iterable<RestSetting> asRestSetting(final List<? extends RestBaseSetting> setting) { if (setting == null || setting.isEmpty()) { return ImmutableList.of(); } return from(setting).transform(toSetting()); } }
moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/RestBaseSetting.java
package com.github.dreamhead.moco.parser.model; import com.github.dreamhead.moco.ResponseBase; import com.github.dreamhead.moco.RestSetting; import com.github.dreamhead.moco.RestSettingBuilder; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import java.util.List; import static com.google.common.collect.FluentIterable.from; public abstract class RestBaseSetting { protected RequestSetting request; protected ResponseSetting response; protected abstract RestSettingBuilder startRestSetting(); @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("request", request) .add("response", response) .toString(); } RestSetting toRestSetting() { if (response == null) { throw new IllegalArgumentException("Response is expected in rest setting"); } return this.getRestSettingBuilder().response(response.getResponseHandler()); } private ResponseBase<RestSetting> getRestSettingBuilder() { RestSettingBuilder builder = this.startRestSetting(); if (request != null) { return builder.request(request.getRequestMatcher()); } return builder; } private static <T extends RestBaseSetting> Function<T, RestSetting> toSetting() { return new Function<T, RestSetting>() { @Override public RestSetting apply(final T setting) { return setting.toRestSetting(); } }; } public static Iterable<RestSetting> asRestSetting(final List<? extends RestBaseSetting> setting) { if (setting == null || setting.isEmpty()) { return ImmutableList.of(); } return from(setting).transform(toSetting()); } }
added missing final to rest base setting
moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/RestBaseSetting.java
added missing final to rest base setting
<ide><path>oco-runner/src/main/java/com/github/dreamhead/moco/parser/model/RestBaseSetting.java <ide> .toString(); <ide> } <ide> <del> RestSetting toRestSetting() { <add> final RestSetting toRestSetting() { <ide> if (response == null) { <ide> throw new IllegalArgumentException("Response is expected in rest setting"); <ide> }
Java
mit
d40f34ac6d3680a0b5f7c8d88a38b2542d49402c
0
mdaniline/spring-autoproperties
package com.mdaniline.spring.autoproperties; import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.StandardAnnotationMetadata; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.*; public class AutoPropertiesRegistrarTest { private BeanDefinitionRegistry registry; private AnnotationMetadata metadata; private AutoPropertiesRegistrar underTest; @Before public void setUp() throws Exception { metadata = new StandardAnnotationMetadata(TestConfig.class, true); registry = new DefaultListableBeanFactory(); underTest = new AutoPropertiesRegistrar(); } @Test public void givenPackageWithAnnotatedInterfaces_registerDefinitions_addsExpectedBeansToRegistryWithExpectedNames() { underTest.setResourceLoader(new DefaultResourceLoader()); underTest.setEnvironment(new StandardEnvironment()); underTest.registerBeanDefinitions(metadata, registry); List<String> beanNames = Arrays.asList(registry.getBeanDefinitionNames()); assertThat(beanNames, contains("testBasicProperties")); } @EnableAutoProperties(basePackageClasses = TestBasicProperties.class) private class TestConfig { } }
src/test/java/com/mdaniline/spring/autoproperties/AutoPropertiesRegistrarTest.java
package com.mdaniline.spring.autoproperties; import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.StandardAnnotationMetadata; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.*; public class AutoPropertiesRegistrarTest { private BeanDefinitionRegistry registry; private AnnotationMetadata metadata; private AutoPropertiesRegistrar underTest; @Before public void setUp() throws Exception { metadata = new StandardAnnotationMetadata(TestConfig.class, true); registry = new DefaultListableBeanFactory(); underTest = new AutoPropertiesRegistrar(); } @Test public void givenPackageWithAnnotatedInterfaces_registerDefinitions_addsExpectedBeansToRegistryWithExpectedNames() { underTest.setResourceLoader(new DefaultResourceLoader()); underTest.setEnvironment(new StandardEnvironment()); underTest.registerBeanDefinitions(metadata, registry); List<String> beanNames = Arrays.asList(registry.getBeanDefinitionNames()); assertThat(beanNames, contains("testBasicProperties")); } @EnableAutoProperties(basePackageClasses = TestBasicProperties.class) private class TestConfig { } }
Remove unnecessary dependency from unit test
src/test/java/com/mdaniline/spring/autoproperties/AutoPropertiesRegistrarTest.java
Remove unnecessary dependency from unit test
<ide><path>rc/test/java/com/mdaniline/spring/autoproperties/AutoPropertiesRegistrarTest.java <ide> package com.mdaniline.spring.autoproperties; <ide> <ide> import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties; <del>import org.junit.After; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry;
Java
apache-2.0
160005ea1c087534ee5c29f8dcc515c76dd9b6ea
0
andreilemdyanov/junior,andreilemdyanov/junior
package pro.ru.job4j.iterator; import java.util.Iterator; /** * Class IteratorArray. * * @author Andrey Lemdyanov {[email protected]) * @version $Id$ * @since 03.06.2017 */ public class IteratorArray implements Iterator { /** * Поле двухмерного массива. */ private final int[][] values; /** * Поле индекс - количество массивов в массиве. */ private int index = 0; /** * Поле количества элементов в массиве. */ private int indexdeep = 0; /** * Конструктор. * * @param values двухмерный массив. */ public IteratorArray(final int[][] values) { this.values = values; } /** * Метод для перехода внутри двумерного массива. */ public void nextArray() { if (indexdeep == values[index].length && index < values.length - 1) { index++; indexdeep = 0; } } /** * Переопределение метода hasNext. * * @return есть ли еще элемент? */ @Override public boolean hasNext() { nextArray(); return values.length - 1 >= index && values[index].length - 1 >= indexdeep; } /** * Переопределение метода next. * * @return значение текущего элемента и перевод каретки на следующий. */ @Override public Object next() { return values[index][indexdeep++]; } }
chapter_005/src/main/java/pro/ru/job4j/iterator/IteratorArray.java
package pro.ru.job4j.iterator; import java.util.Iterator; /** * Class IteratorArray. * * @author Andrey Lemdyanov {[email protected]) * @version $Id$ * @since 03.06.2017 */ public class IteratorArray implements Iterator { /** * Поле двухмерного массива. */ private final int[][] values; /** * Поле индекс - количество массивов в массиве. */ private int index = 0; /** * Поле количества элементов в массиве. */ private int indexdeep = 0; /** * Конструктор. * * @param values двухмерный массив. */ public IteratorArray(final int[][] values) { this.values = values; } /** * Метод для перехода внутри двумерного массива. */ public void nextArray() { if (indexdeep == values[index].length && index < values.length - 1) { index++; indexdeep = 0; } } /** * Переопределение метода hasNext. * * @return есть ли еще элемент? */ @Override public boolean hasNext() { nextArray(); boolean result; if (values.length > index && values[index].length > indexdeep) { result = true; } else if (values.length - 1 == index && values[index].length > indexdeep) { result = true; } else if (values.length - 1 == index && values[index].length == indexdeep) { result = false; } else if (values.length > index && values[index].length == indexdeep) { result = true; } else { result = false; } return result; } /** * Переопределение метода next. * * @return значение текущего элемента и перевод каретки на следующий. */ @Override public Object next() { return values[index][indexdeep++]; } }
task 9539
chapter_005/src/main/java/pro/ru/job4j/iterator/IteratorArray.java
task 9539
<ide><path>hapter_005/src/main/java/pro/ru/job4j/iterator/IteratorArray.java <ide> @Override <ide> public boolean hasNext() { <ide> nextArray(); <del> boolean result; <del> if (values.length > index && values[index].length > indexdeep) { <del> result = true; <del> } else if (values.length - 1 == index && values[index].length > indexdeep) { <del> result = true; <del> } else if (values.length - 1 == index && values[index].length == indexdeep) { <del> result = false; <del> } else if (values.length > index && values[index].length == indexdeep) { <del> result = true; <del> } else { <del> result = false; <del> } <del> return result; <add> return values.length - 1 >= index && values[index].length - 1 >= indexdeep; <ide> } <ide> <ide> /**
Java
epl-1.0
382a44067d1cc903e90165be18b693772b4b87a4
0
gerasimou/EMC-CDT,gerasimou/EMC-CDT
package org.eclipse.epsilon.emc.cdt.propertygetter; import java.util.HashMap; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.core.runtime.CoreException; import org.eclipse.epsilon.emc.cdt.NameFinderASTVisitor; public class TranslationUnitGetter extends CElementGetter<Object> { private final static String ACCEPT_NAME = "name"; private final static String ACCEPT_LIB = "lib"; /** Pairs of ITranslationUnit, IASTTranslationUnit **/ private HashMap<ITranslationUnit, IASTTranslationUnit> astCache = new HashMap<ITranslationUnit, IASTTranslationUnit>(); /** * Class constructor * @param clazz * @param properties */ public TranslationUnitGetter() { super(ITranslationUnit.class, ACCEPT_NAME, ACCEPT_LIB); } @Override public Object getValue(ICElement object, String property) { //name command --> call superclass if (property.equals(ACCEPT_NAME)){ return super.getValue(object, property); } //lib command else if (property.equals(ACCEPT_LIB)){ if (object instanceof ITranslationUnit){ try { //get tu ITranslationUnit tu = (ITranslationUnit)object; //create index IIndex projectIndex = CCorePlugin.getIndexManager().getIndex(tu.getCProject() ); //cache ast IASTTranslationUnit ast = null; if (astCache.containsKey(tu)){ ast = astCache.get(tu); } else{ ast = tu.getAST(projectIndex, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); astCache.put(tu, ast); } //visitor NameFinderASTVisitor visitor = new NameFinderASTVisitor(); ast.accept(visitor); return visitor.getList(); } catch (CoreException e) { e.printStackTrace(); } } } return null; } }
org.eclipse.epsilon.emc.cdt/src/org/eclipse/epsilon/emc/cdt/propertygetter/TranslationUnitGetter.java
package org.eclipse.epsilon.emc.cdt.propertygetter; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression; import org.eclipse.cdt.core.dom.ast.IASTIdExpression; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionCallExpression; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope; import org.eclipse.cdt.core.index.IIndex; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.core.runtime.CoreException; import org.eclipse.epsilon.emc.cdt.NameFinderASTVisitor; public class TranslationUnitGetter extends CElementGetter<Object> { private final static String ACCEPT_NAME = "name"; private final static String ACCEPT_LIB = "lib"; /** * Class constructor * @param clazz * @param properties */ public TranslationUnitGetter() { super(ITranslationUnit.class, ACCEPT_NAME, ACCEPT_LIB); } @Override public Object getValue(ICElement object, String property) { //name command --> call superclass if (property.equals(ACCEPT_NAME)){ return super.getValue(object, property); } //lib command else if (property.equals(ACCEPT_LIB)){ if (object instanceof ITranslationUnit){ try { //get tu ITranslationUnit tu = (ITranslationUnit)object; //create index IIndex index = CCorePlugin.getIndexManager().getIndex(tu.getCProject() ); // get AST IASTTranslationUnit ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); //visitor NameFinderASTVisitor visitor = new NameFinderASTVisitor(); ast.accept(visitor); return visitor.getList(); } catch (CoreException e) { e.printStackTrace(); } } } return null; } }
- TranslationUnitGetter now caches the AST
org.eclipse.epsilon.emc.cdt/src/org/eclipse/epsilon/emc/cdt/propertygetter/TranslationUnitGetter.java
- TranslationUnitGetter now caches the AST
<ide><path>rg.eclipse.epsilon.emc.cdt/src/org/eclipse/epsilon/emc/cdt/propertygetter/TranslationUnitGetter.java <ide> package org.eclipse.epsilon.emc.cdt.propertygetter; <ide> <add>import java.util.HashMap; <add> <ide> import org.eclipse.cdt.core.CCorePlugin; <del>import org.eclipse.cdt.core.dom.ast.DOMException; <del>import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression; <del>import org.eclipse.cdt.core.dom.ast.IASTIdExpression; <ide> import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; <del>import org.eclipse.cdt.core.dom.ast.IBinding; <del>import org.eclipse.cdt.core.dom.ast.IScope; <del>import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionCallExpression; <del>import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope; <ide> import org.eclipse.cdt.core.index.IIndex; <ide> import org.eclipse.cdt.core.model.ICElement; <ide> import org.eclipse.cdt.core.model.ITranslationUnit; <ide> <ide> public class TranslationUnitGetter extends CElementGetter<Object> { <ide> private final static String ACCEPT_NAME = "name"; <del> <add> <add> private final static String ACCEPT_LIB = "lib"; <ide> <del> private final static String ACCEPT_LIB = "lib"; <add> /** Pairs of ITranslationUnit, IASTTranslationUnit **/ <add> private HashMap<ITranslationUnit, IASTTranslationUnit> astCache = new HashMap<ITranslationUnit, IASTTranslationUnit>(); <ide> <ide> /** <ide> * Class constructor <ide> try { <ide> //get tu <ide> ITranslationUnit tu = (ITranslationUnit)object; <add> <ide> //create index <del> IIndex index = CCorePlugin.getIndexManager().getIndex(tu.getCProject() ); <del> // get AST <del> IASTTranslationUnit ast = tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); <add> IIndex projectIndex = CCorePlugin.getIndexManager().getIndex(tu.getCProject() ); <add> <add> //cache ast <add> IASTTranslationUnit ast = null; <add> if (astCache.containsKey(tu)){ <add> ast = astCache.get(tu); <add> } <add> else{ <add> ast = tu.getAST(projectIndex, ITranslationUnit.AST_SKIP_INDEXED_HEADERS); <add> astCache.put(tu, ast); <add> } <add> <ide> //visitor <ide> NameFinderASTVisitor visitor = new NameFinderASTVisitor(); <ide> ast.accept(visitor);
JavaScript
mit
1c8bdfa121ab38c5fc5fb902132184880f17b42d
0
textioHQ/qTip2,itnovator/qTip2,qTip2/qTip2,landsurveyorsunited/qTip2,textioHQ/qTip2
function delay(callback, duration) { // If tooltip has displayed, start hide timer if(duration > 0) { return setTimeout( $.proxy(callback, this), duration ); } else{ callback.call(this); } } function showMethod(event) { if(this.tooltip.hasClass(CLASS_DISABLED)) { return FALSE; } // Clear hide timers clearTimeout(this.timers.show); clearTimeout(this.timers.hide); // Start show timer this.timers.show = delay.call(this, function() { this.toggle(TRUE, event); }, this.options.show.delay ); } function hideMethod(event) { if(this.tooltip.hasClass(CLASS_DISABLED)) { return FALSE; } // Check if new target was actually the tooltip element var relatedTarget = $(event.relatedTarget), ontoTooltip = relatedTarget.closest(SELECTOR)[0] === this.tooltip[0], ontoTarget = relatedTarget[0] === this.options.show.target[0]; // Clear timers and stop animation queue clearTimeout(this.timers.show); clearTimeout(this.timers.hide); // Prevent hiding if tooltip is fixed and event target is the tooltip. // Or if mouse positioning is enabled and cursor momentarily overlaps if(this !== relatedTarget[0] && (this.options.position.target === 'mouse' && ontoTooltip) || (this.options.hide.fixed && ( (/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget)) )) { try { event.preventDefault(); event.stopImmediatePropagation(); } catch(e) {} return; } // If tooltip has displayed, start hide timer this.timers.hide = delay.call(this, function() { this.toggle(FALSE, event); }, this.options.hide.delay, this ); } function inactiveMethod(event) { if(this.tooltip.hasClass(CLASS_DISABLED) || !this.options.hide.inactive) { return FALSE; } // Clear timer clearTimeout(this.timers.inactive); this.timers.inactive = delay.call(this, function(){ this.hide(event); }, this.options.hide.inactive ); } function repositionMethod(event) { if(this.rendered && this.tooltip[0].offsetWidth > 0) { this.reposition(event); } } // Store mouse coordinates PROTOTYPE._storeMouse = function(event) { (this.mouse = $.event.fix(event)).type = 'mousemove'; }; // Bind events PROTOTYPE._bind = function(targets, events, method, suffix, context) { var ns = '.' + this._id + (suffix ? '-'+suffix : ''); events.length && $(targets).bind( (events.split ? events : events.join(ns + ' ')) + ns, $.proxy(method, context || this) ); }; PROTOTYPE._unbind = function(targets, suffix) { $(targets).unbind('.' + this._id + (suffix ? '-'+suffix : '')); }; // Apply common event handlers using delegate (avoids excessive .bind calls!) var ns = '.'+NAMESPACE; function delegate(selector, events, method) { $(document.body).delegate(selector, (events.split ? events : events.join(ns + ' ')) + ns, function() { var api = QTIP.api[ $.attr(this, ATTR_ID) ]; api && !api.disabled && method.apply(api, arguments); } ); } $(function() { delegate(SELECTOR, ['mouseenter', 'mouseleave'], function(event) { var state = event.type === 'mouseenter', tooltip = $(event.currentTarget), target = $(event.relatedTarget || event.target), options = this.options; // On mouseenter... if(state) { // Focus the tooltip on mouseenter (z-index stacking) this.focus(event); // Clear hide timer on tooltip hover to prevent it from closing tooltip.hasClass(CLASS_FIXED) && !tooltip.hasClass(CLASS_DISABLED) && clearTimeout(this.timers.hide); } // On mouseleave... else { // Hide when we leave the tooltip and not onto the show target (if a hide event is set) if(options.position.target === 'mouse' && options.hide.event && options.show.target && !target.closest(options.show.target[0]).length) { this.hide(event); } } // Add hover class tooltip.toggleClass(CLASS_HOVER, state); }); // Define events which reset the 'inactive' event handler delegate('['+ATTR_ID+']', INACTIVE_EVENTS, inactiveMethod); }); // Event trigger PROTOTYPE._trigger = function(type, args, event) { var callback = $.Event('tooltip'+type); callback.originalEvent = (event && $.extend({}, event)) || this.cache.event || NULL; this.triggering = type; this.tooltip.trigger(callback, [this].concat(args || [])); this.triggering = FALSE; return !callback.isDefaultPrevented(); }; PROTOTYPE._bindEvents = function(showEvents, hideEvents, showTargets, hideTargets, showMethod, hideMethod) { // Get tasrgets that lye within both var similarTargets = showTargets.filter( hideTargets ).add( hideTargets.filter(showTargets) ), toggleEvents = []; // If hide and show targets are the same... if(similarTargets.length) { // Filter identical show/hide events $.each(hideEvents, function(i, type) { var showIndex = $.inArray(type, showEvents); // Both events are identical, remove from both hide and show events // and append to toggleEvents showIndex > -1 && toggleEvents.push( showEvents.splice( showIndex, 1 )[0] ); }); // Toggle events are special case of identical show/hide events, which happen in sequence if(toggleEvents.length) { // Bind toggle events to the similar targets this._bind(similarTargets, toggleEvents, function(event) { var state = this.rendered ? this.tooltip[0].offsetWidth > 0 : false; (state ? hideMethod : showMethod).call(this, event); }); // Remove the similar targets from the regular show/hide bindings showTargets = showTargets.not(similarTargets); hideTargets = hideTargets.not(similarTargets); } } // Apply show/hide/toggle events this._bind(showTargets, showEvents, showMethod); this._bind(hideTargets, hideEvents, hideMethod); }; PROTOTYPE._assignInitialEvents = function(event) { var options = this.options, showTarget = options.show.target, hideTarget = options.hide.target, showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [], hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : []; /* * Make sure hoverIntent functions properly by using mouseleave as a hide event if * mouseenter/mouseout is used for show.event, even if it isn't in the users options. */ if(/mouse(over|enter)/i.test(options.show.event) && !/mouse(out|leave)/i.test(options.hide.event)) { hideEvents.push('mouseleave'); } /* * Also make sure initial mouse targetting works correctly by caching mousemove coords * on show targets before the tooltip has rendered. Also set onTarget when triggered to * keep mouse tracking working. */ this._bind(showTarget, 'mousemove', function(event) { this._storeMouse(event); this.cache.onTarget = TRUE; }); // Define hoverIntent function function hoverIntent(event) { // Only continue if tooltip isn't disabled if(this.disabled || this.destroyed) { return FALSE; } // Cache the event data this.cache.event = $.event.fix(event); this.cache.target = event ? $(event.target) : [undefined]; // Start the event sequence clearTimeout(this.timers.show); this.timers.show = delay.call(this, function() { this.render(typeof event === 'object' || options.show.ready); }, options.show.delay ); } // Filter and bind events this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, hoverIntent, function() { clearTimeout(this.timers.show); }); // Prerendering is enabled, create tooltip now if(options.show.ready || options.prerender) { hoverIntent.call(this, event); } }; // Event assignment method PROTOTYPE._assignEvents = function() { var self = this, options = this.options, posOptions = options.position, tooltip = this.tooltip, showTarget = options.show.target, hideTarget = options.hide.target, containerTarget = posOptions.container, viewportTarget = posOptions.viewport, documentTarget = $(document), bodyTarget = $(document.body), windowTarget = $(window), showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [], hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : []; // Assign passed event callbacks $.each(options.events, function(name, callback) { self._bind(tooltip, name === 'toggle' ? ['tooltipshow','tooltiphide'] : ['tooltip'+name], callback, null, tooltip); }); // Hide tooltips when leaving current window/frame (but not select/option elements) if(/mouse(out|leave)/i.test(options.hide.event) && options.hide.leave === 'window') { this._bind(documentTarget, ['mouseout', 'blur'], function(event) { if(!/select|option/.test(event.target.nodeName) && !event.relatedTarget) { this.hide(event); } }); } // Enable hide.fixed by adding appropriate class if(options.hide.fixed) { hideTarget = hideTarget.add( tooltip.addClass(CLASS_FIXED) ); } /* * Make sure hoverIntent functions properly by using mouseleave to clear show timer if * mouseenter/mouseout is used for show.event, even if it isn't in the users options. */ else if(/mouse(over|enter)/i.test(options.show.event)) { this._bind(hideTarget, 'mouseleave', function() { clearTimeout(this.timers.show); }); } // Hide tooltip on document mousedown if unfocus events are enabled if(('' + options.hide.event).indexOf('unfocus') > -1) { this._bind(containerTarget.closest('html'), ['mousedown', 'touchstart'], function(event) { var elem = $(event.target), enabled = this.rendered && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0, isAncestor = elem.parents(SELECTOR).filter(this.tooltip[0]).length > 0; if(elem[0] !== this.target[0] && elem[0] !== this.tooltip[0] && !isAncestor && !this.target.has(elem[0]).length && enabled ) { this.hide(event); } }); } // Check if the tooltip hides when inactive if('number' === typeof options.hide.inactive) { // Bind inactive method to show target(s) as a custom event this._bind(showTarget, 'qtip-'+this.id+'-inactive', inactiveMethod); // Define events which reset the 'inactive' event handler this._bind(hideTarget.add(tooltip), QTIP.inactiveEvents, inactiveMethod, '-inactive'); } // Filter and bind events this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, showMethod, hideMethod); // Mouse movement bindings this._bind(showTarget.add(tooltip), 'mousemove', function(event) { // Check if the tooltip hides when mouse is moved a certain distance if('number' === typeof options.hide.distance) { var origin = this.cache.origin || {}, limit = this.options.hide.distance, abs = Math.abs; // Check if the movement has gone beyond the limit, and hide it if so if(abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) { this.hide(event); } } // Cache mousemove coords on show targets this._storeMouse(event); }); // Mouse positioning events if(posOptions.target === 'mouse') { // If mouse adjustment is on... if(posOptions.adjust.mouse) { // Apply a mouseleave event so we don't get problems with overlapping if(options.hide.event) { // Track if we're on the target or not this._bind(showTarget, ['mouseenter', 'mouseleave'], function(event) { this.cache.onTarget = event.type === 'mouseenter'; }); } // Update tooltip position on mousemove this._bind(documentTarget, 'mousemove', function(event) { // Update the tooltip position only if the tooltip is visible and adjustment is enabled if(this.rendered && this.cache.onTarget && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0) { this.reposition(event); } }); } } // Adjust positions of the tooltip on window resize if enabled if(posOptions.adjust.resize || viewportTarget.length) { this._bind( $.event.special.resize ? viewportTarget : windowTarget, 'resize', repositionMethod ); } // Adjust tooltip position on scroll of the window or viewport element if present if(posOptions.adjust.scroll) { this._bind( windowTarget.add(posOptions.container), 'scroll', repositionMethod ); } }; // Un-assignment method PROTOTYPE._unassignEvents = function() { var targets = [ this.options.show.target[0], this.options.hide.target[0], this.rendered && this.tooltip[0], this.options.position.container[0], this.options.position.viewport[0], this.options.position.container.closest('html')[0], // unfocus window, document ]; this._unbind($([]).pushStack( $.grep(targets, function(i) { return typeof i === 'object'; }))); };
src/core/events.js
function delay(callback, duration) { // If tooltip has displayed, start hide timer if(duration > 0) { return setTimeout( $.proxy(callback, this), duration ); } else{ callback.call(this); } } function showMethod(event) { if(this.tooltip.hasClass(CLASS_DISABLED)) { return FALSE; } // Clear hide timers clearTimeout(this.timers.show); clearTimeout(this.timers.hide); // Start show timer this.timers.show = delay.call(this, function() { this.toggle(TRUE, event); }, this.options.show.delay ); } function hideMethod(event) { if(this.tooltip.hasClass(CLASS_DISABLED)) { return FALSE; } // Check if new target was actually the tooltip element var relatedTarget = $(event.relatedTarget), ontoTooltip = relatedTarget.closest(SELECTOR)[0] === this.tooltip[0], ontoTarget = relatedTarget[0] === this.options.show.target[0]; // Clear timers and stop animation queue clearTimeout(this.timers.show); clearTimeout(this.timers.hide); // Prevent hiding if tooltip is fixed and event target is the tooltip. // Or if mouse positioning is enabled and cursor momentarily overlaps if(this !== relatedTarget[0] && (this.options.position.target === 'mouse' && ontoTooltip) || (this.options.hide.fixed && ( (/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget)) )) { try { event.preventDefault(); event.stopImmediatePropagation(); } catch(e) {} return; } // If tooltip has displayed, start hide timer this.timers.hide = delay.call(this, function() { this.toggle(FALSE, event); }, this.options.hide.delay, this ); } function inactiveMethod(event) { if(this.tooltip.hasClass(CLASS_DISABLED) || !this.options.hide.inactive) { return FALSE; } // Clear timer clearTimeout(this.timers.inactive); this.timers.inactive = delay.call(this, function(){ this.hide(event); }, this.options.hide.inactive ); } function repositionMethod(event) { if(this.rendered && this.tooltip[0].offsetWidth > 0) { this.reposition(event); } } // Store mouse coordinates PROTOTYPE._storeMouse = function(event) { (this.mouse = $.event.fix(event)).type = 'mousemove'; }; // Bind events PROTOTYPE._bind = function(targets, events, method, suffix, context) { var ns = '.' + this._id + (suffix ? '-'+suffix : ''); events.length && $(targets).bind( (events.split ? events : events.join(ns + ' ')) + ns, $.proxy(method, context || this) ); }; PROTOTYPE._unbind = function(targets, suffix) { $(targets).unbind('.' + this._id + (suffix ? '-'+suffix : '')); }; // Apply common event handlers using delegate (avoids excessive .bind calls!) var ns = '.'+NAMESPACE; function delegate(selector, events, method) { $(document.body).delegate(selector, (events.split ? events : events.join(ns + ' ')) + ns, function() { var api = QTIP.api[ $.attr(this, ATTR_ID) ]; api && !api.disabled && method.apply(api, arguments); } ); } $(function() { delegate(SELECTOR, ['mouseenter', 'mouseleave'], function(event) { var state = event.type === 'mouseenter', tooltip = $(event.currentTarget), target = $(event.relatedTarget || event.target), options = this.options; // On mouseenter... if(state) { // Focus the tooltip on mouseenter (z-index stacking) this.focus(event); // Clear hide timer on tooltip hover to prevent it from closing tooltip.hasClass(CLASS_FIXED) && !tooltip.hasClass(CLASS_DISABLED) && clearTimeout(this.timers.hide); } // On mouseleave... else { // Hide when we leave the tooltip and not onto the show target (if a hide event is set) if(options.position.target === 'mouse' && options.hide.event && options.show.target && !target.closest(options.show.target[0]).length) { this.hide(event); } } // Add hover class tooltip.toggleClass(CLASS_HOVER, state); }); // Define events which reset the 'inactive' event handler delegate('['+ATTR_ID+']', INACTIVE_EVENTS, inactiveMethod); }); // Event trigger PROTOTYPE._trigger = function(type, args, event) { var callback = $.Event('tooltip'+type); callback.originalEvent = (event && $.extend({}, event)) || this.cache.event || NULL; this.triggering = type; this.tooltip.trigger(callback, [this].concat(args || [])); this.triggering = FALSE; return !callback.isDefaultPrevented(); }; PROTOTYPE._bindEvents = function(showEvents, hideEvents, showTarget, hideTarget, showMethod, hideMethod) { // Get tasrgets that lye within both var similarTargets = showTarget.filter( hideTarget ), toggleEvents = []; // If hide and show targets are the same... if(similarTargets.length) { // Filter identical show/hide events $.each(hideEvents, function(i, type) { var showIndex = $.inArray(type, showEvents); // Both events are identical, remove from both hide and show events // and append to toggleEvents showIndex > -1 && toggleEvents.push( showEvents.splice( showIndex, 1 )[0] ); }); // Toggle events are special case of identical show/hide events, which happen in sequence toggleEvents.length && this._bind(similarTargets, toggleEvents, function(event) { var state = this.rendered ? this.tooltip[0].offsetWidth > 0 : false; (state ? hideMethod : showMethod).call(this, event); }); } // Apply show/hide/toggle events this._bind(showTarget.not(similarTargets), showEvents, showMethod); this._bind(hideTarget.not(similarTargets), hideEvents, hideMethod); }; PROTOTYPE._assignInitialEvents = function(event) { var options = this.options, showTarget = options.show.target, hideTarget = options.hide.target, showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [], hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : []; /* * Make sure hoverIntent functions properly by using mouseleave as a hide event if * mouseenter/mouseout is used for show.event, even if it isn't in the users options. */ if(/mouse(over|enter)/i.test(options.show.event) && !/mouse(out|leave)/i.test(options.hide.event)) { hideEvents.push('mouseleave'); } /* * Also make sure initial mouse targetting works correctly by caching mousemove coords * on show targets before the tooltip has rendered. Also set onTarget when triggered to * keep mouse tracking working. */ this._bind(showTarget, 'mousemove', function(event) { this._storeMouse(event); this.cache.onTarget = TRUE; }); // Define hoverIntent function function hoverIntent(event) { // Only continue if tooltip isn't disabled if(this.disabled || this.destroyed) { return FALSE; } // Cache the event data this.cache.event = $.event.fix(event); this.cache.target = event ? $(event.target) : [undefined]; // Start the event sequence clearTimeout(this.timers.show); this.timers.show = delay.call(this, function() { this.render(typeof event === 'object' || options.show.ready); }, options.show.delay ); } // Filter and bind events this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, hoverIntent, function() { clearTimeout(this.timers.show); }); // Prerendering is enabled, create tooltip now if(options.show.ready || options.prerender) { hoverIntent.call(this, event); } }; // Event assignment method PROTOTYPE._assignEvents = function() { var self = this, options = this.options, posOptions = options.position, tooltip = this.tooltip, showTarget = options.show.target, hideTarget = options.hide.target, containerTarget = posOptions.container, viewportTarget = posOptions.viewport, documentTarget = $(document), bodyTarget = $(document.body), windowTarget = $(window), showEvents = options.show.event ? $.trim('' + options.show.event).split(' ') : [], hideEvents = options.hide.event ? $.trim('' + options.hide.event).split(' ') : []; // Assign passed event callbacks $.each(options.events, function(name, callback) { self._bind(tooltip, name === 'toggle' ? ['tooltipshow','tooltiphide'] : ['tooltip'+name], callback, null, tooltip); }); // Hide tooltips when leaving current window/frame (but not select/option elements) if(/mouse(out|leave)/i.test(options.hide.event) && options.hide.leave === 'window') { this._bind(documentTarget, ['mouseout', 'blur'], function(event) { if(!/select|option/.test(event.target.nodeName) && !event.relatedTarget) { this.hide(event); } }); } // Enable hide.fixed by adding appropriate class if(options.hide.fixed) { hideTarget = hideTarget.add( tooltip.addClass(CLASS_FIXED) ); } /* * Make sure hoverIntent functions properly by using mouseleave to clear show timer if * mouseenter/mouseout is used for show.event, even if it isn't in the users options. */ else if(/mouse(over|enter)/i.test(options.show.event)) { this._bind(hideTarget, 'mouseleave', function() { clearTimeout(this.timers.show); }); } // Hide tooltip on document mousedown if unfocus events are enabled if(('' + options.hide.event).indexOf('unfocus') > -1) { this._bind(containerTarget.closest('html'), ['mousedown', 'touchstart'], function(event) { var elem = $(event.target), enabled = this.rendered && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0, isAncestor = elem.parents(SELECTOR).filter(this.tooltip[0]).length > 0; if(elem[0] !== this.target[0] && elem[0] !== this.tooltip[0] && !isAncestor && !this.target.has(elem[0]).length && enabled ) { this.hide(event); } }); } // Check if the tooltip hides when inactive if('number' === typeof options.hide.inactive) { // Bind inactive method to show target(s) as a custom event this._bind(showTarget, 'qtip-'+this.id+'-inactive', inactiveMethod); // Define events which reset the 'inactive' event handler this._bind(hideTarget.add(tooltip), QTIP.inactiveEvents, inactiveMethod, '-inactive'); } // Filter and bind events this._bindEvents(showEvents, hideEvents, showTarget, hideTarget, showMethod, hideMethod); // Mouse movement bindings this._bind(showTarget.add(tooltip), 'mousemove', function(event) { // Check if the tooltip hides when mouse is moved a certain distance if('number' === typeof options.hide.distance) { var origin = this.cache.origin || {}, limit = this.options.hide.distance, abs = Math.abs; // Check if the movement has gone beyond the limit, and hide it if so if(abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) { this.hide(event); } } // Cache mousemove coords on show targets this._storeMouse(event); }); // Mouse positioning events if(posOptions.target === 'mouse') { // If mouse adjustment is on... if(posOptions.adjust.mouse) { // Apply a mouseleave event so we don't get problems with overlapping if(options.hide.event) { // Track if we're on the target or not this._bind(showTarget, ['mouseenter', 'mouseleave'], function(event) { this.cache.onTarget = event.type === 'mouseenter'; }); } // Update tooltip position on mousemove this._bind(documentTarget, 'mousemove', function(event) { // Update the tooltip position only if the tooltip is visible and adjustment is enabled if(this.rendered && this.cache.onTarget && !this.tooltip.hasClass(CLASS_DISABLED) && this.tooltip[0].offsetWidth > 0) { this.reposition(event); } }); } } // Adjust positions of the tooltip on window resize if enabled if(posOptions.adjust.resize || viewportTarget.length) { this._bind( $.event.special.resize ? viewportTarget : windowTarget, 'resize', repositionMethod ); } // Adjust tooltip position on scroll of the window or viewport element if present if(posOptions.adjust.scroll) { this._bind( windowTarget.add(posOptions.container), 'scroll', repositionMethod ); } }; // Un-assignment method PROTOTYPE._unassignEvents = function() { var targets = [ this.options.show.target[0], this.options.hide.target[0], this.rendered && this.tooltip[0], this.options.position.container[0], this.options.position.viewport[0], this.options.position.container.closest('html')[0], // unfocus window, document ]; this._unbind($([]).pushStack( $.grep(targets, function(i) { return typeof i === 'object'; }))); };
Fix problem with previous commit. Fixes #629
src/core/events.js
Fix problem with previous commit. Fixes #629
<ide><path>rc/core/events.js <ide> return !callback.isDefaultPrevented(); <ide> }; <ide> <del>PROTOTYPE._bindEvents = function(showEvents, hideEvents, showTarget, hideTarget, showMethod, hideMethod) { <add>PROTOTYPE._bindEvents = function(showEvents, hideEvents, showTargets, hideTargets, showMethod, hideMethod) { <ide> // Get tasrgets that lye within both <del> var similarTargets = showTarget.filter( hideTarget ), <add> var similarTargets = showTargets.filter( hideTargets ).add( hideTargets.filter(showTargets) ), <ide> toggleEvents = []; <ide> <ide> // If hide and show targets are the same... <ide> }); <ide> <ide> // Toggle events are special case of identical show/hide events, which happen in sequence <del> toggleEvents.length && this._bind(similarTargets, toggleEvents, function(event) { <del> var state = this.rendered ? this.tooltip[0].offsetWidth > 0 : false; <del> (state ? hideMethod : showMethod).call(this, event); <del> }); <add> if(toggleEvents.length) { <add> // Bind toggle events to the similar targets <add> this._bind(similarTargets, toggleEvents, function(event) { <add> var state = this.rendered ? this.tooltip[0].offsetWidth > 0 : false; <add> (state ? hideMethod : showMethod).call(this, event); <add> }); <add> <add> // Remove the similar targets from the regular show/hide bindings <add> showTargets = showTargets.not(similarTargets); <add> hideTargets = hideTargets.not(similarTargets); <add> } <ide> } <ide> <ide> // Apply show/hide/toggle events <del> this._bind(showTarget.not(similarTargets), showEvents, showMethod); <del> this._bind(hideTarget.not(similarTargets), hideEvents, hideMethod); <add> this._bind(showTargets, showEvents, showMethod); <add> this._bind(hideTargets, hideEvents, hideMethod); <ide> }; <ide> <ide> PROTOTYPE._assignInitialEvents = function(event) {
Java
agpl-3.0
3c5c29d638dedb85e5ced761f5e21d27ac916bf7
0
enviroCar/enviroCar-server,enviroCar/enviroCar-server,autermann/enviroCar-server,Drifftr/enviroCar-server,gotodeepak1122/enviroCar-server,autermann/enviroCar-server,autermann/enviroCar-server,Drifftr/enviroCar-server,enviroCar/enviroCar-server,gotodeepak1122/enviroCar-server
/* * Copyright (C) 2013 Christian Autermann, Jan Alexander Wirwahn, * Arne De Wall, Dustin Demuth, Saqib Rasheed * * 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 io.car.server.rest.validation; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.List; import java.util.zip.GZIPInputStream; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.fge.jsonschema.exceptions.ProcessingException; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.report.ProcessingMessage; import com.github.fge.jsonschema.report.ProcessingReport; import com.google.common.collect.ImmutableMap; import com.google.common.io.Closeables; import com.google.inject.Inject; import com.google.inject.name.Named; import com.sun.jersey.api.container.ContainerException; import com.sun.jersey.api.model.AbstractMethod; import com.sun.jersey.core.util.ReaderWriter; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerRequestFilter; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; import com.sun.jersey.spi.container.ContainerResponseWriter; import com.sun.jersey.spi.container.ResourceFilter; import com.sun.jersey.spi.container.ResourceFilterFactory; import io.car.server.core.exception.ValidationException; import io.car.server.rest.JSONConstants; import io.car.server.rest.MediaTypes; /** * @author Christian Autermann <[email protected]> */ public class JSONSchemaResourceFilterFactory implements ResourceFilterFactory { private static final Logger log = LoggerFactory .getLogger(JSONSchemaResourceFilterFactory.class); public static final String VALIDATE_REQUESTS = "validate_requests"; public static final String VALIDATE_RESPONSES = "validate_responses"; private final boolean validateRequests; private final boolean validateResponses; private final JsonSchemaFactory schemaFactory; private final ObjectReader reader; private final ObjectWriter writer; private final JsonNodeFactory factory; @Inject public JSONSchemaResourceFilterFactory(JsonSchemaFactory schemaFactory, ObjectReader reader, ObjectWriter writer, JsonNodeFactory factory, @Named(VALIDATE_REQUESTS) boolean validateRequests, @Named(VALIDATE_RESPONSES) boolean validateResponses) { this.schemaFactory = schemaFactory; this.reader = reader; this.writer = writer; this.factory = factory; this.validateRequests = validateRequests; this.validateResponses = validateResponses; } @Override public List<ResourceFilter> create(AbstractMethod am) { String requestSchema = null; String responseSchema = null; Schema schema = am.getAnnotation(Schema.class); if (schema != null) { if (!schema.request().isEmpty()) { requestSchema = schema.request(); } if (!schema.response().isEmpty()) { responseSchema = schema.response(); } } if (requestSchema != null || responseSchema != null) { JSONSchemaResourceFilter filter = new JSONSchemaResourceFilter(requestSchema, responseSchema); return Collections.<ResourceFilter>singletonList(filter); } else { return Collections.emptyList(); } } protected String getRequestType(AbstractMethod am) throws IllegalArgumentException { Schema schema = am.getAnnotation(Schema.class); if (schema != null && !schema.request().isEmpty()) { return schema.request(); } return null; } protected void validate(JsonNode entity, String schema) throws ValidationException, IOException { try { validate(entity, schemaFactory.getJsonSchema(schema)); } catch (ProcessingException ex) { throw new ValidationException(ex); } } protected void validate(JsonNode t, JsonSchema schema) throws ValidationException, ProcessingException { ProcessingReport report = schema.validate(t); if (!report.isSuccess()) { ObjectNode error = factory.objectNode(); ArrayNode errors = error.putArray(JSONConstants.ERRORS); for (ProcessingMessage message : report) { errors.add(message.asJson()); } throw new JSONValidationException(error); } } private class JSONSchemaResourceFilter implements ResourceFilter { private String request; private String response; JSONSchemaResourceFilter(String request, String response) { this.request = request; this.response = response; } @Override public ContainerRequestFilter getRequestFilter() { return request == null || !validateRequests ? null : new JSONSchemaRequestFilter(request); } @Override public ContainerResponseFilter getResponseFilter() { return response == null || !validateResponses ? null : new JSONSchemaResponeFilter(response); } } private class JSONSchemaRequestFilter implements ContainerRequestFilter { private String schema; JSONSchemaRequestFilter(String schema) { this.schema = schema; } @Override public ContainerRequest filter(ContainerRequest request) { if (request.getMediaType() != null && request.getMediaType() .isCompatible(MediaType.APPLICATION_JSON_TYPE)) { adjustContentType(request); validate(request); } return request; } protected void adjustContentType(ContainerRequest request) { MediaType newMt = new MediaType("application", "json", ImmutableMap .<String, String>builder() .putAll(request.getMediaType().getParameters()) .put(MediaTypes.SCHEMA_ATTRIBUTE, schema).build()); // container request caches the header...... request.getRequestHeaders().remove(HttpHeaders.CONTENT_TYPE); request.getMediaType(); request.getRequestHeaders() .putSingle(HttpHeaders.CONTENT_TYPE, newMt.toString()); } private void validate(ContainerRequest request) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = request.getEntityInputStream(); try { ReaderWriter.writeTo(in, out); byte[] requestEntity = out.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(requestEntity); request.setEntityInputStream(bais); String entity = new String(requestEntity, ReaderWriter .getCharset(request.getMediaType())); if (entity.isEmpty()) { throw new WebApplicationException(Status.BAD_REQUEST); } JsonNode tree; try { tree = reader.readTree(entity); } catch (JsonParseException e) { throw new WebApplicationException(e, Status.BAD_REQUEST); } JSONSchemaResourceFilterFactory.this.validate(tree, schema); } catch (IOException ex) { throw new ContainerException(ex); } } } private class JSONSchemaResponeFilter implements ContainerResponseFilter { private String schema; JSONSchemaResponeFilter(String schema) { this.schema = schema; } @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { MediaType mt = response.getMediaType(); if (mt.isCompatible(MediaType.APPLICATION_JSON_TYPE)) { adjustContentType(response); ContainerResponseWriter crw = response .getContainerResponseWriter(); ContainerResponseWriter vcrw = new ValidatingWriter(crw, schema); response.setContainerResponseWriter(vcrw); } return response; } protected void adjustContentType(ContainerResponse response) { MediaType newMt = new MediaType("application", "json", ImmutableMap .<String, String>builder() .putAll(response.getMediaType().getParameters()) .put(MediaTypes.SCHEMA_ATTRIBUTE, schema) .build()); response.getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, newMt); } } private class ValidatingWriter implements ContainerResponseWriter { private final ContainerResponseWriter crw; private ByteArrayOutputStream baos; private OutputStream crwout; private MediaType mediaType; private String schema; private MultivaluedMap<String, Object> httpHeaders; ValidatingWriter(ContainerResponseWriter crw, String schema) { this.crw = crw; this.schema = schema; } @Override public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse response) throws IOException { this.mediaType = response.getMediaType(); this.crwout = crw.writeStatusAndHeaders(contentLength, response); this.baos = new ByteArrayOutputStream(); this.httpHeaders = response.getHttpHeaders(); return this.baos; } @Override public void finish() throws IOException { byte[] bytes = this.baos.toByteArray(); ReaderWriter.writeTo(new ByteArrayInputStream(bytes), this.crwout); this.crw.finish(); String contentEncoding = (String) httpHeaders .getFirst(HttpHeaders.CONTENT_ENCODING); if (contentEncoding != null && contentEncoding.equals("gzip")) { validate(gunzip(bytes)); } else { validate(bytes); } } protected byte[] gunzip(byte[] bytes) throws IOException { GZIPInputStream gzin = null; ByteArrayInputStream bain = null; ByteArrayOutputStream out = null; try { bain = new ByteArrayInputStream(bytes); out = new ByteArrayOutputStream(); gzin = new GZIPInputStream(bain); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = gzin.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.flush(); return out.toByteArray(); } finally { Closeables.closeQuietly(bain); Closeables.closeQuietly(gzin); Closeables.closeQuietly(out); } } protected void validate(byte[] bytes) throws IOException, WebApplicationException { String entity = new String(bytes, ReaderWriter.getCharset(mediaType)); try { JSONSchemaResourceFilterFactory.this.validate(reader .readTree(entity), schema); } catch (JSONValidationException v) { log.error("Created invalid response: Error:\n" + writer.writeValueAsString(v.getError()) + "\nGenerated Response:\n" + entity + "\n", v); } catch (ValidationException v) { log.error("Created invalid response: Error:\n" + v.getMessage() + "\nGenerated Response:\n" + entity + "\n", v); throw new WebApplicationException(v, Status.INTERNAL_SERVER_ERROR); } } } }
rest/src/main/java/io/car/server/rest/validation/JSONSchemaResourceFilterFactory.java
/* * Copyright (C) 2013 Christian Autermann, Jan Alexander Wirwahn, * Arne De Wall, Dustin Demuth, Saqib Rasheed * * 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 io.car.server.rest.validation; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Collections; import java.util.List; import java.util.zip.GZIPInputStream; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.fge.jsonschema.exceptions.ProcessingException; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.report.ProcessingMessage; import com.github.fge.jsonschema.report.ProcessingReport; import com.google.common.collect.ImmutableMap; import com.google.common.io.Closeables; import com.google.inject.Inject; import com.google.inject.name.Named; import com.sun.jersey.api.container.ContainerException; import com.sun.jersey.api.model.AbstractMethod; import com.sun.jersey.core.util.ReaderWriter; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerRequestFilter; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; import com.sun.jersey.spi.container.ContainerResponseWriter; import com.sun.jersey.spi.container.ResourceFilter; import com.sun.jersey.spi.container.ResourceFilterFactory; import io.car.server.core.exception.ValidationException; import io.car.server.rest.JSONConstants; import io.car.server.rest.MediaTypes; /** * @author Christian Autermann <[email protected]> */ public class JSONSchemaResourceFilterFactory implements ResourceFilterFactory { private static final Logger log = LoggerFactory .getLogger(JSONSchemaResourceFilterFactory.class); public static final String VALIDATE_REQUESTS = "validate_requests"; public static final String VALIDATE_RESPONSES = "validate_responses"; private final boolean validateRequests; private final boolean validateResponses; private final JsonSchemaFactory schemaFactory; private final ObjectReader reader; private final ObjectWriter writer; private final JsonNodeFactory factory; @Inject public JSONSchemaResourceFilterFactory(JsonSchemaFactory schemaFactory, ObjectReader reader, ObjectWriter writer, JsonNodeFactory factory, @Named(VALIDATE_REQUESTS) boolean validateRequests, @Named(VALIDATE_RESPONSES) boolean validateResponses) { this.schemaFactory = schemaFactory; this.reader = reader; this.writer = writer; this.factory = factory; this.validateRequests = validateRequests; this.validateResponses = validateResponses; } @Override public List<ResourceFilter> create(AbstractMethod am) { String requestSchema = null; String responseSchema = null; Schema schema = am.getAnnotation(Schema.class); if (schema != null) { if (!schema.request().isEmpty()) { requestSchema = schema.request(); } if (!schema.response().isEmpty()) { responseSchema = schema.response(); } } if (requestSchema != null || responseSchema != null) { JSONSchemaResourceFilter filter = new JSONSchemaResourceFilter(requestSchema, responseSchema); return Collections.<ResourceFilter>singletonList(filter); } else { return Collections.emptyList(); } } protected String getRequestType(AbstractMethod am) throws IllegalArgumentException { Schema schema = am.getAnnotation(Schema.class); if (schema != null && !schema.request().isEmpty()) { return schema.request(); } return null; } protected void validate(String entity, String schema) throws ValidationException, IOException { try { validate(reader.readTree(entity), schemaFactory .getJsonSchema(schema)); } catch (ProcessingException ex) { throw new ValidationException(ex); } } protected void validate(JsonNode t, JsonSchema schema) throws ValidationException, ProcessingException { ProcessingReport report = schema.validate(t); if (!report.isSuccess()) { ObjectNode error = factory.objectNode(); ArrayNode errors = error.putArray(JSONConstants.ERRORS); for (ProcessingMessage message : report) { errors.add(message.asJson()); } throw new JSONValidationException(error); } } private class JSONSchemaResourceFilter implements ResourceFilter { private String request; private String response; JSONSchemaResourceFilter(String request, String response) { this.request = request; this.response = response; } @Override public ContainerRequestFilter getRequestFilter() { return request == null || !validateRequests ? null : new JSONSchemaRequestFilter(request); } @Override public ContainerResponseFilter getResponseFilter() { return response == null || !validateResponses ? null : new JSONSchemaResponeFilter(response); } } private class JSONSchemaRequestFilter implements ContainerRequestFilter { private String schema; JSONSchemaRequestFilter(String schema) { this.schema = schema; } @Override public ContainerRequest filter(ContainerRequest request) { if (request.getMediaType() != null && request.getMediaType() .isCompatible(MediaType.APPLICATION_JSON_TYPE)) { adjustContentType(request); validate(request); } return request; } protected void adjustContentType(ContainerRequest request) { MediaType newMt = new MediaType("application", "json", ImmutableMap .<String, String>builder() .putAll(request.getMediaType().getParameters()) .put(MediaTypes.SCHEMA_ATTRIBUTE, schema).build()); // container request caches the header...... request.getRequestHeaders().remove(HttpHeaders.CONTENT_TYPE); request.getMediaType(); request.getRequestHeaders() .putSingle(HttpHeaders.CONTENT_TYPE, newMt.toString()); } private void validate(ContainerRequest request) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = request.getEntityInputStream(); try { ReaderWriter.writeTo(in, out); byte[] requestEntity = out.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(requestEntity); request.setEntityInputStream(bais); String enitity = new String(requestEntity, ReaderWriter .getCharset(request.getMediaType())); JSONSchemaResourceFilterFactory.this .validate(enitity, schema); } catch (IOException ex) { throw new ContainerException(ex); } } } private class JSONSchemaResponeFilter implements ContainerResponseFilter { private String schema; JSONSchemaResponeFilter(String schema) { this.schema = schema; } @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { MediaType mt = response.getMediaType(); if (mt.isCompatible(MediaType.APPLICATION_JSON_TYPE)) { adjustContentType(response); ContainerResponseWriter crw = response .getContainerResponseWriter(); ContainerResponseWriter vcrw = new ValidatingWriter(crw, schema); response.setContainerResponseWriter(vcrw); } return response; } protected void adjustContentType(ContainerResponse response) { MediaType newMt = new MediaType("application", "json", ImmutableMap .<String, String>builder() .putAll(response.getMediaType().getParameters()) .put(MediaTypes.SCHEMA_ATTRIBUTE, schema) .build()); response.getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, newMt); } } private class ValidatingWriter implements ContainerResponseWriter { private final ContainerResponseWriter crw; private ByteArrayOutputStream baos; private OutputStream crwout; private MediaType mediaType; private String schema; private MultivaluedMap<String, Object> httpHeaders; ValidatingWriter(ContainerResponseWriter crw, String schema) { this.crw = crw; this.schema = schema; } @Override public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse response) throws IOException { this.mediaType = response.getMediaType(); this.crwout = crw.writeStatusAndHeaders(contentLength, response); this.baos = new ByteArrayOutputStream(); this.httpHeaders = response.getHttpHeaders(); return this.baos; } @Override public void finish() throws IOException { byte[] bytes = this.baos.toByteArray(); ReaderWriter.writeTo(new ByteArrayInputStream(bytes), this.crwout); this.crw.finish(); String contentEncoding = (String) httpHeaders .getFirst(HttpHeaders.CONTENT_ENCODING); if (contentEncoding != null && contentEncoding.equals("gzip")) { validate(gunzip(bytes)); } else { validate(bytes); } } protected byte[] gunzip(byte[] bytes) throws IOException { GZIPInputStream gzin = null; ByteArrayInputStream bain = null; ByteArrayOutputStream out = null; try { bain = new ByteArrayInputStream(bytes); out = new ByteArrayOutputStream(); gzin = new GZIPInputStream(bain); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = gzin.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.flush(); return out.toByteArray(); } finally { Closeables.closeQuietly(bain); Closeables.closeQuietly(gzin); Closeables.closeQuietly(out); } } protected void validate(byte[] bytes) throws IOException, WebApplicationException { String entity = new String(bytes, ReaderWriter.getCharset(mediaType)); try { JSONSchemaResourceFilterFactory.this.validate(entity, schema); } catch (JSONValidationException v) { log.error("Created invalid response: Error:\n" + writer.writeValueAsString(v.getError()) + "\nGenerated Response:\n" + entity + "\n", v); } catch (ValidationException v) { log.error("Created invalid response: Error:\n" + v.getMessage() + "\nGenerated Response:\n" + entity + "\n", v); throw new WebApplicationException(v, Status.INTERNAL_SERVER_ERROR); } } } }
fixed 500 ISE when not submitting any entity
rest/src/main/java/io/car/server/rest/validation/JSONSchemaResourceFilterFactory.java
fixed 500 ISE when not submitting any entity
<ide><path>est/src/main/java/io/car/server/rest/validation/JSONSchemaResourceFilterFactory.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <add>import com.fasterxml.jackson.core.JsonParseException; <ide> import com.fasterxml.jackson.databind.JsonNode; <ide> import com.fasterxml.jackson.databind.ObjectReader; <ide> import com.fasterxml.jackson.databind.ObjectWriter; <ide> return null; <ide> } <ide> <del> protected void validate(String entity, String schema) throws <add> protected void validate(JsonNode entity, String schema) throws <ide> ValidationException, IOException { <ide> try { <del> validate(reader.readTree(entity), schemaFactory <del> .getJsonSchema(schema)); <add> validate(entity, schemaFactory.getJsonSchema(schema)); <ide> } catch (ProcessingException ex) { <ide> throw new ValidationException(ex); <ide> } <ide> ByteArrayInputStream bais = <ide> new ByteArrayInputStream(requestEntity); <ide> request.setEntityInputStream(bais); <del> String enitity = new String(requestEntity, ReaderWriter <add> String entity = new String(requestEntity, ReaderWriter <ide> .getCharset(request.getMediaType())); <del> JSONSchemaResourceFilterFactory.this <del> .validate(enitity, schema); <add> if (entity.isEmpty()) { <add> throw new WebApplicationException(Status.BAD_REQUEST); <add> } <add> JsonNode tree; <add> try { <add> tree = reader.readTree(entity); <add> } catch (JsonParseException e) { <add> throw new WebApplicationException(e, Status.BAD_REQUEST); <add> } <add> JSONSchemaResourceFilterFactory.this.validate(tree, schema); <ide> } catch (IOException ex) { <ide> throw new ContainerException(ex); <ide> } <ide> String entity = <ide> new String(bytes, ReaderWriter.getCharset(mediaType)); <ide> try { <del> JSONSchemaResourceFilterFactory.this.validate(entity, schema); <add> JSONSchemaResourceFilterFactory.this.validate(reader <add> .readTree(entity), schema); <ide> } catch (JSONValidationException v) { <ide> log.error("Created invalid response: Error:\n" + <ide> writer.writeValueAsString(v.getError()) +
Java
bsd-3-clause
6ceefb71dc777ed83c4f6df365796b550dd4cf58
0
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
/* * Copyright (c) 2017, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program; import android.content.ContentValues; import android.database.MatrixCursor; import android.support.test.runner.AndroidJUnit4; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.period.PeriodType; import org.hisp.dhis.android.core.program.ProgramModel.Columns; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import static com.google.common.truth.Truth.assertThat; import static org.hisp.dhis.android.core.AndroidTestUtils.toBoolean; @RunWith(AndroidJUnit4.class) public class ProgramModelShould { //BaseIdentifiableModel attributes: private static final long ID = 11L; private static final String UID = "test_uid"; private static final String CODE = "test_code"; private static final String NAME = "test_name"; private static final String DISPLAY_NAME = "test_display_name"; //BaseNameableModel attributes: private static final String SHORT_NAME = "test_program"; private static final String DISPLAY_SHORT_NAME = "test_prog"; private static final String DESCRIPTION = "A test program for the integration tests."; private static final String DISPLAY_DESCRIPTION = "A test program for the integration tests."; //ProgramModel attributes: private static final Integer VERSION = 1; private static final Integer ONLY_ENROLL_ONCE = 1; private static final String ENROLLMENT_DATE_LABEL = "enrollment date"; private static final Integer DISPLAY_INCIDENT_DATE = 1; private static final String INCIDENT_DATE_LABEL = "incident date label"; private static final Integer REGISTRATION = 1; private static final Integer SELECT_ENROLLMENT_DATES_IN_FUTURE = 1; private static final Integer DATA_ENTRY_METHOD = 1; private static final Integer IGNORE_OVERDUE_EVENTS = 0; private static final Integer RELATIONSHIP_FROM_A = 1; private static final Integer SELECT_INCIDENT_DATES_IN_FUTURE = 1; private static final Integer CAPTURE_COORDINATES = 1; private static final Integer USE_FIRST_STAGE_DURING_REGISTRATION = 1; private static final Integer DISPLAY_FRONT_PAGE_LIST = 1; private static final ProgramType PROGRAM_TYPE = ProgramType.WITH_REGISTRATION; private static final String RELATIONSHIP_TYPE = "relationshipUid"; private static final String RELATIONSHIP_TEXT = "test relationship"; private static final String RELATED_PROGRAM = "ProgramUid"; private static final String TRACKED_ENTITY = "TrackedEntityUid"; private static final String CATEGORY_COMBO = "CategoryComboUid"; private static final Integer ACCESS_DATA_WRITE = 1; private final static Integer EXPIRY_DAYS = 7; private final static Integer COMPLETE_EVENTS_EXPIRY_DAYS = 30; private final static PeriodType EXPIRY_PERIOD_TYPE = PeriodType.Daily; private final static Integer MIN_ATTRIBUTES_REQUIRED_TO_SEARCH = 3; private final Date date; private final String dateString; public ProgramModelShould() { this.date = new Date(); this.dateString = BaseIdentifiableObject.DATE_FORMAT.format(date); } @Test public void create_model_when_created_from_database_cursor() { MatrixCursor cursor = new MatrixCursor(new String[]{ Columns.ID, Columns.UID, Columns.CODE, Columns.NAME, Columns.DISPLAY_NAME, Columns.CREATED, Columns.LAST_UPDATED, Columns.SHORT_NAME, Columns.DISPLAY_SHORT_NAME, Columns.DESCRIPTION, Columns.DISPLAY_DESCRIPTION, Columns.VERSION, Columns.ONLY_ENROLL_ONCE, Columns.ENROLLMENT_DATE_LABEL, Columns.DISPLAY_INCIDENT_DATE, Columns.INCIDENT_DATE_LABEL, Columns.REGISTRATION, Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, Columns.DATA_ENTRY_METHOD, Columns.IGNORE_OVERDUE_EVENTS, Columns.RELATIONSHIP_FROM_A, Columns.SELECT_INCIDENT_DATES_IN_FUTURE, Columns.CAPTURE_COORDINATES, Columns.USE_FIRST_STAGE_DURING_REGISTRATION, Columns.DISPLAY_FRONT_PAGE_LIST, Columns.PROGRAM_TYPE, Columns.RELATIONSHIP_TYPE, Columns.RELATIONSHIP_TEXT, Columns.RELATED_PROGRAM, Columns.TRACKED_ENTITY_TYPE, Columns.CATEGORY_COMBO, Columns.ACCESS_DATA_WRITE, Columns.EXPIRY_DAYS, Columns.COMPLETE_EVENTS_EXPIRY_DAYS, Columns.EXPIRY_PERIOD_TYPE, Columns.MIN_ATTRIBUTES_REQUIRED_TO_SEARCH }); cursor.addRow(new Object[]{ID, UID, CODE, NAME, DISPLAY_NAME, dateString, dateString, SHORT_NAME, DISPLAY_SHORT_NAME, DESCRIPTION, DISPLAY_DESCRIPTION, VERSION, ONLY_ENROLL_ONCE, ENROLLMENT_DATE_LABEL, DISPLAY_INCIDENT_DATE, INCIDENT_DATE_LABEL, REGISTRATION, SELECT_ENROLLMENT_DATES_IN_FUTURE, DATA_ENTRY_METHOD, IGNORE_OVERDUE_EVENTS, RELATIONSHIP_FROM_A, SELECT_INCIDENT_DATES_IN_FUTURE, CAPTURE_COORDINATES, USE_FIRST_STAGE_DURING_REGISTRATION, DISPLAY_FRONT_PAGE_LIST, PROGRAM_TYPE, RELATIONSHIP_TYPE, RELATIONSHIP_TEXT, RELATED_PROGRAM, TRACKED_ENTITY, CATEGORY_COMBO, ACCESS_DATA_WRITE, EXPIRY_DAYS, COMPLETE_EVENTS_EXPIRY_DAYS, EXPIRY_PERIOD_TYPE, MIN_ATTRIBUTES_REQUIRED_TO_SEARCH }); cursor.moveToFirst(); ProgramModel model = ProgramModel.create(cursor); cursor.close(); assertThat(model.id()).isEqualTo(ID); assertThat(model.uid()).isEqualTo(UID); assertThat(model.code()).isEqualTo(CODE); assertThat(model.name()).isEqualTo(NAME); assertThat(model.displayName()).isEqualTo(DISPLAY_NAME); assertThat(model.created()).isEqualTo(date); assertThat(model.lastUpdated()).isEqualTo(date); assertThat(model.shortName()).isEqualTo(SHORT_NAME); assertThat(model.displayShortName()).isEqualTo(DISPLAY_SHORT_NAME); assertThat(model.description()).isEqualTo(DESCRIPTION); assertThat(model.displayDescription()).isEqualTo(DISPLAY_DESCRIPTION); assertThat(model.version()).isEqualTo(VERSION); assertThat(model.onlyEnrollOnce()).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(model.enrollmentDateLabel()).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(model.displayIncidentDate()).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(model.incidentDateLabel()).isEqualTo(INCIDENT_DATE_LABEL); assertThat(model.registration()).isEqualTo(toBoolean(REGISTRATION)); assertThat(model.selectEnrollmentDatesInFuture()).isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(model.dataEntryMethod()).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(model.ignoreOverdueEvents()).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(model.relationshipFromA()).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(model.selectIncidentDatesInFuture()).isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(model.captureCoordinates()).isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(model.useFirstStageDuringRegistration()).isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(model.displayFrontPageList()).isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(model.programType()).isEqualTo(PROGRAM_TYPE); assertThat(model.relationshipType()).isEqualTo(RELATIONSHIP_TYPE); assertThat(model.relationshipText()).isEqualTo(RELATIONSHIP_TEXT); assertThat(model.relatedProgram()).isEqualTo(RELATED_PROGRAM); assertThat(model.trackedEntityType()).isEqualTo(TRACKED_ENTITY); assertThat(model.categoryCombo()).isEqualTo(CATEGORY_COMBO); assertThat(model.accessDataWrite()).isEqualTo(toBoolean(ACCESS_DATA_WRITE)); assertThat(model.expiryDays()).isEqualTo(EXPIRY_DAYS); assertThat(model.completeEventsExpiryDays()).isEqualTo(COMPLETE_EVENTS_EXPIRY_DAYS); assertThat(model.expiryPeriodType()).isEqualTo(EXPIRY_PERIOD_TYPE); assertThat(model.minAttributesRequiredToSearch()).isEqualTo(MIN_ATTRIBUTES_REQUIRED_TO_SEARCH); } @Test public void create_content_values_when_created_from_builder() { ProgramModel model = ProgramModel.builder() .id(ID) .uid(UID) .code(CODE) .name(NAME).displayName(DISPLAY_NAME).created(date).lastUpdated(date) .shortName(SHORT_NAME) .displayShortName(DISPLAY_SHORT_NAME) .description(DESCRIPTION) .displayDescription(DISPLAY_DESCRIPTION) .version(VERSION) .onlyEnrollOnce(toBoolean(ONLY_ENROLL_ONCE)) .enrollmentDateLabel(ENROLLMENT_DATE_LABEL) .displayIncidentDate(toBoolean(DISPLAY_INCIDENT_DATE)) .registration(toBoolean(REGISTRATION)) .selectEnrollmentDatesInFuture(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)) .dataEntryMethod(toBoolean(DATA_ENTRY_METHOD)) .ignoreOverdueEvents(toBoolean(IGNORE_OVERDUE_EVENTS)) .relationshipFromA(toBoolean(RELATIONSHIP_FROM_A)) .selectIncidentDatesInFuture(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)) .captureCoordinates(toBoolean(CAPTURE_COORDINATES)) .useFirstStageDuringRegistration(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)) .displayFrontPageList(toBoolean(DISPLAY_FRONT_PAGE_LIST)) .programType(PROGRAM_TYPE) .relationshipType(RELATIONSHIP_TYPE) .relationshipText(RELATIONSHIP_TEXT) .relatedProgram(RELATED_PROGRAM) .trackedEntityType(TRACKED_ENTITY) .categoryCombo(CATEGORY_COMBO) .accessDataWrite(toBoolean(ACCESS_DATA_WRITE)) .expiryDays(EXPIRY_DAYS) .completeEventsExpiryDays(COMPLETE_EVENTS_EXPIRY_DAYS) .expiryPeriodType(EXPIRY_PERIOD_TYPE) .minAttributesRequiredToSearch(MIN_ATTRIBUTES_REQUIRED_TO_SEARCH) .build(); ContentValues contentValues = model.toContentValues(); assertThat(contentValues.getAsLong(ProgramModel.Columns.ID)).isEqualTo(ID); assertThat(contentValues.getAsString(ProgramModel.Columns.UID)).isEqualTo(UID); assertThat(contentValues.getAsString(ProgramModel.Columns.NAME)).isEqualTo(NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.DISPLAY_NAME)).isEqualTo(DISPLAY_NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.CREATED)).isEqualTo(dateString); assertThat(contentValues.getAsString(ProgramModel.Columns.LAST_UPDATED)).isEqualTo(dateString); assertThat(contentValues.getAsString(ProgramModel.Columns.SHORT_NAME)).isEqualTo(SHORT_NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.DISPLAY_SHORT_NAME)).isEqualTo(DISPLAY_SHORT_NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.DESCRIPTION)).isEqualTo(DESCRIPTION); assertThat(contentValues.getAsString(ProgramModel.Columns.DISPLAY_DESCRIPTION)).isEqualTo(DISPLAY_DESCRIPTION); assertThat(contentValues.getAsInteger(ProgramModel.Columns.VERSION)).isEqualTo(VERSION); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.ONLY_ENROLL_ONCE)).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(contentValues.getAsString( ProgramModel.Columns.ENROLLMENT_DATE_LABEL)).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.DISPLAY_INCIDENT_DATE)).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.REGISTRATION)).isEqualTo(toBoolean(REGISTRATION)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE)) .isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.DATA_ENTRY_METHOD)).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.IGNORE_OVERDUE_EVENTS)).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.RELATIONSHIP_FROM_A)).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.SELECT_INCIDENT_DATES_IN_FUTURE)) .isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.CAPTURE_COORDINATES)) .isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.USE_FIRST_STAGE_DURING_REGISTRATION)) .isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.DISPLAY_FRONT_PAGE_LIST)) .isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(contentValues.getAsString(ProgramModel.Columns.PROGRAM_TYPE)).isEqualTo(PROGRAM_TYPE.toString()); assertThat(contentValues.getAsString(ProgramModel.Columns.RELATIONSHIP_TYPE)).isEqualTo(RELATIONSHIP_TYPE); assertThat(contentValues.getAsString(ProgramModel.Columns.RELATIONSHIP_TEXT)).isEqualTo(RELATIONSHIP_TEXT); assertThat(contentValues.getAsString(ProgramModel.Columns.RELATED_PROGRAM)).isEqualTo(RELATED_PROGRAM); assertThat(contentValues.getAsString(ProgramModel.Columns.TRACKED_ENTITY_TYPE)).isEqualTo(TRACKED_ENTITY); assertThat(contentValues.getAsString(ProgramModel.Columns.CATEGORY_COMBO)).isEqualTo(CATEGORY_COMBO); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.ACCESS_DATA_WRITE)) .isEqualTo(toBoolean(ACCESS_DATA_WRITE)); assertThat(contentValues.getAsInteger(ProgramModel.Columns.EXPIRY_DAYS)).isEqualTo(EXPIRY_DAYS); assertThat(contentValues.getAsInteger(ProgramModel.Columns.COMPLETE_EVENTS_EXPIRY_DAYS)) .isEqualTo(COMPLETE_EVENTS_EXPIRY_DAYS); assertThat(contentValues.getAsString(ProgramModel.Columns.EXPIRY_PERIOD_TYPE)) .isEqualTo(EXPIRY_PERIOD_TYPE.toString()); assertThat(contentValues.getAsInteger(ProgramModel.Columns.MIN_ATTRIBUTES_REQUIRED_TO_SEARCH)) .isEqualTo(MIN_ATTRIBUTES_REQUIRED_TO_SEARCH); } }
core/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramModelShould.java
/* * Copyright (c) 2017, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program; import android.content.ContentValues; import android.database.MatrixCursor; import android.support.test.runner.AndroidJUnit4; import org.hisp.dhis.android.core.common.BaseIdentifiableObject; import org.hisp.dhis.android.core.period.PeriodType; import org.hisp.dhis.android.core.program.ProgramModel.Columns; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Date; import static com.google.common.truth.Truth.assertThat; import static org.hisp.dhis.android.core.AndroidTestUtils.toBoolean; @RunWith(AndroidJUnit4.class) public class ProgramModelShould { //BaseIdentifiableModel attributes: private static final long ID = 11L; private static final String UID = "test_uid"; private static final String CODE = "test_code"; private static final String NAME = "test_name"; private static final String DISPLAY_NAME = "test_display_name"; //BaseNameableModel attributes: private static final String SHORT_NAME = "test_program"; private static final String DISPLAY_SHORT_NAME = "test_prog"; private static final String DESCRIPTION = "A test program for the integration tests."; private static final String DISPLAY_DESCRIPTION = "A test program for the integration tests."; //ProgramModel attributes: private static final Integer VERSION = 1; private static final Integer ONLY_ENROLL_ONCE = 1; private static final String ENROLLMENT_DATE_LABEL = "enrollment date"; private static final Integer DISPLAY_INCIDENT_DATE = 1; private static final String INCIDENT_DATE_LABEL = "incident date label"; private static final Integer REGISTRATION = 1; private static final Integer SELECT_ENROLLMENT_DATES_IN_FUTURE = 1; private static final Integer DATA_ENTRY_METHOD = 1; private static final Integer IGNORE_OVERDUE_EVENTS = 0; private static final Integer RELATIONSHIP_FROM_A = 1; private static final Integer SELECT_INCIDENT_DATES_IN_FUTURE = 1; private static final Integer CAPTURE_COORDINATES = 1; private static final Integer USE_FIRST_STAGE_DURING_REGISTRATION = 1; private static final Integer DISPLAY_FRONT_PAGE_LIST = 1; private static final ProgramType PROGRAM_TYPE = ProgramType.WITH_REGISTRATION; private static final String RELATIONSHIP_TYPE = "relationshipUid"; private static final String RELATIONSHIP_TEXT = "test relationship"; private static final String RELATED_PROGRAM = "ProgramUid"; private static final String TRACKED_ENTITY = "TrackedEntityUid"; private static final String CATEGORY_COMBO = "CategoryComboUid"; private static final Integer ACCESS_DATA_WRITE = 1; private final static Integer EXPIRY_DAYS = 7; private final static Integer COMPLETE_EVENTS_EXPIRY_DAYS = 30; private final static PeriodType EXPIRY_PERIOD_TYPE = PeriodType.Daily; private final Date date; private final String dateString; public ProgramModelShould() { this.date = new Date(); this.dateString = BaseIdentifiableObject.DATE_FORMAT.format(date); } @Test public void create_model_when_created_from_database_cursor() { MatrixCursor cursor = new MatrixCursor(new String[]{ Columns.ID, Columns.UID, Columns.CODE, Columns.NAME, Columns.DISPLAY_NAME, Columns.CREATED, Columns.LAST_UPDATED, Columns.SHORT_NAME, Columns.DISPLAY_SHORT_NAME, Columns.DESCRIPTION, Columns.DISPLAY_DESCRIPTION, Columns.VERSION, Columns.ONLY_ENROLL_ONCE, Columns.ENROLLMENT_DATE_LABEL, Columns.DISPLAY_INCIDENT_DATE, Columns.INCIDENT_DATE_LABEL, Columns.REGISTRATION, Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE, Columns.DATA_ENTRY_METHOD, Columns.IGNORE_OVERDUE_EVENTS, Columns.RELATIONSHIP_FROM_A, Columns.SELECT_INCIDENT_DATES_IN_FUTURE, Columns.CAPTURE_COORDINATES, Columns.USE_FIRST_STAGE_DURING_REGISTRATION, Columns.DISPLAY_FRONT_PAGE_LIST, Columns.PROGRAM_TYPE, Columns.RELATIONSHIP_TYPE, Columns.RELATIONSHIP_TEXT, Columns.RELATED_PROGRAM, Columns.TRACKED_ENTITY_TYPE, Columns.CATEGORY_COMBO, Columns.ACCESS_DATA_WRITE, Columns.EXPIRY_DAYS, Columns.COMPLETE_EVENTS_EXPIRY_DAYS, Columns.EXPIRY_PERIOD_TYPE }); cursor.addRow(new Object[]{ID, UID, CODE, NAME, DISPLAY_NAME, dateString, dateString, SHORT_NAME, DISPLAY_SHORT_NAME, DESCRIPTION, DISPLAY_DESCRIPTION, VERSION, ONLY_ENROLL_ONCE, ENROLLMENT_DATE_LABEL, DISPLAY_INCIDENT_DATE, INCIDENT_DATE_LABEL, REGISTRATION, SELECT_ENROLLMENT_DATES_IN_FUTURE, DATA_ENTRY_METHOD, IGNORE_OVERDUE_EVENTS, RELATIONSHIP_FROM_A, SELECT_INCIDENT_DATES_IN_FUTURE, CAPTURE_COORDINATES, USE_FIRST_STAGE_DURING_REGISTRATION, DISPLAY_FRONT_PAGE_LIST, PROGRAM_TYPE, RELATIONSHIP_TYPE, RELATIONSHIP_TEXT, RELATED_PROGRAM, TRACKED_ENTITY, CATEGORY_COMBO, ACCESS_DATA_WRITE, EXPIRY_DAYS, COMPLETE_EVENTS_EXPIRY_DAYS, EXPIRY_PERIOD_TYPE }); cursor.moveToFirst(); ProgramModel model = ProgramModel.create(cursor); cursor.close(); assertThat(model.id()).isEqualTo(ID); assertThat(model.uid()).isEqualTo(UID); assertThat(model.code()).isEqualTo(CODE); assertThat(model.name()).isEqualTo(NAME); assertThat(model.displayName()).isEqualTo(DISPLAY_NAME); assertThat(model.created()).isEqualTo(date); assertThat(model.lastUpdated()).isEqualTo(date); assertThat(model.shortName()).isEqualTo(SHORT_NAME); assertThat(model.displayShortName()).isEqualTo(DISPLAY_SHORT_NAME); assertThat(model.description()).isEqualTo(DESCRIPTION); assertThat(model.displayDescription()).isEqualTo(DISPLAY_DESCRIPTION); assertThat(model.version()).isEqualTo(VERSION); assertThat(model.onlyEnrollOnce()).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(model.enrollmentDateLabel()).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(model.displayIncidentDate()).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(model.incidentDateLabel()).isEqualTo(INCIDENT_DATE_LABEL); assertThat(model.registration()).isEqualTo(toBoolean(REGISTRATION)); assertThat(model.selectEnrollmentDatesInFuture()).isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(model.dataEntryMethod()).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(model.ignoreOverdueEvents()).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(model.relationshipFromA()).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(model.selectIncidentDatesInFuture()).isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(model.captureCoordinates()).isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(model.useFirstStageDuringRegistration()).isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(model.displayFrontPageList()).isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(model.programType()).isEqualTo(PROGRAM_TYPE); assertThat(model.relationshipType()).isEqualTo(RELATIONSHIP_TYPE); assertThat(model.relationshipText()).isEqualTo(RELATIONSHIP_TEXT); assertThat(model.relatedProgram()).isEqualTo(RELATED_PROGRAM); assertThat(model.trackedEntityType()).isEqualTo(TRACKED_ENTITY); assertThat(model.categoryCombo()).isEqualTo(CATEGORY_COMBO); assertThat(model.accessDataWrite()).isEqualTo(toBoolean(ACCESS_DATA_WRITE)); assertThat(model.expiryDays()).isEqualTo(EXPIRY_DAYS); assertThat(model.completeEventsExpiryDays()).isEqualTo(COMPLETE_EVENTS_EXPIRY_DAYS); assertThat(model.expiryPeriodType()).isEqualTo(EXPIRY_PERIOD_TYPE); } @Test public void create_content_values_when_created_from_builder() { ProgramModel model = ProgramModel.builder() .id(ID) .uid(UID) .code(CODE) .name(NAME).displayName(DISPLAY_NAME).created(date).lastUpdated(date) .shortName(SHORT_NAME) .displayShortName(DISPLAY_SHORT_NAME) .description(DESCRIPTION) .displayDescription(DISPLAY_DESCRIPTION) .version(VERSION) .onlyEnrollOnce(toBoolean(ONLY_ENROLL_ONCE)) .enrollmentDateLabel(ENROLLMENT_DATE_LABEL) .displayIncidentDate(toBoolean(DISPLAY_INCIDENT_DATE)) .registration(toBoolean(REGISTRATION)) .selectEnrollmentDatesInFuture(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)) .dataEntryMethod(toBoolean(DATA_ENTRY_METHOD)) .ignoreOverdueEvents(toBoolean(IGNORE_OVERDUE_EVENTS)) .relationshipFromA(toBoolean(RELATIONSHIP_FROM_A)) .selectIncidentDatesInFuture(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)) .captureCoordinates(toBoolean(CAPTURE_COORDINATES)) .useFirstStageDuringRegistration(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)) .displayFrontPageList(toBoolean(DISPLAY_FRONT_PAGE_LIST)) .programType(PROGRAM_TYPE) .relationshipType(RELATIONSHIP_TYPE) .relationshipText(RELATIONSHIP_TEXT) .relatedProgram(RELATED_PROGRAM) .trackedEntityType(TRACKED_ENTITY) .categoryCombo(CATEGORY_COMBO) .accessDataWrite(toBoolean(ACCESS_DATA_WRITE)) .expiryDays(EXPIRY_DAYS) .completeEventsExpiryDays(COMPLETE_EVENTS_EXPIRY_DAYS) .expiryPeriodType(EXPIRY_PERIOD_TYPE) .build(); ContentValues contentValues = model.toContentValues(); assertThat(contentValues.getAsLong(ProgramModel.Columns.ID)).isEqualTo(ID); assertThat(contentValues.getAsString(ProgramModel.Columns.UID)).isEqualTo(UID); assertThat(contentValues.getAsString(ProgramModel.Columns.NAME)).isEqualTo(NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.DISPLAY_NAME)).isEqualTo(DISPLAY_NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.CREATED)).isEqualTo(dateString); assertThat(contentValues.getAsString(ProgramModel.Columns.LAST_UPDATED)).isEqualTo(dateString); assertThat(contentValues.getAsString(ProgramModel.Columns.SHORT_NAME)).isEqualTo(SHORT_NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.DISPLAY_SHORT_NAME)).isEqualTo(DISPLAY_SHORT_NAME); assertThat(contentValues.getAsString(ProgramModel.Columns.DESCRIPTION)).isEqualTo(DESCRIPTION); assertThat(contentValues.getAsString(ProgramModel.Columns.DISPLAY_DESCRIPTION)).isEqualTo(DISPLAY_DESCRIPTION); assertThat(contentValues.getAsInteger(ProgramModel.Columns.VERSION)).isEqualTo(VERSION); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.ONLY_ENROLL_ONCE)).isEqualTo(toBoolean(ONLY_ENROLL_ONCE)); assertThat(contentValues.getAsString( ProgramModel.Columns.ENROLLMENT_DATE_LABEL)).isEqualTo(ENROLLMENT_DATE_LABEL); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.DISPLAY_INCIDENT_DATE)).isEqualTo(toBoolean(DISPLAY_INCIDENT_DATE)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.REGISTRATION)).isEqualTo(toBoolean(REGISTRATION)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.SELECT_ENROLLMENT_DATES_IN_FUTURE)) .isEqualTo(toBoolean(SELECT_ENROLLMENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.DATA_ENTRY_METHOD)).isEqualTo(toBoolean(DATA_ENTRY_METHOD)); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.IGNORE_OVERDUE_EVENTS)).isEqualTo(toBoolean(IGNORE_OVERDUE_EVENTS)); assertThat(contentValues.getAsBoolean( ProgramModel.Columns.RELATIONSHIP_FROM_A)).isEqualTo(toBoolean(RELATIONSHIP_FROM_A)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.SELECT_INCIDENT_DATES_IN_FUTURE)) .isEqualTo(toBoolean(SELECT_INCIDENT_DATES_IN_FUTURE)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.CAPTURE_COORDINATES)) .isEqualTo(toBoolean(CAPTURE_COORDINATES)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.USE_FIRST_STAGE_DURING_REGISTRATION)) .isEqualTo(toBoolean(USE_FIRST_STAGE_DURING_REGISTRATION)); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.DISPLAY_FRONT_PAGE_LIST)) .isEqualTo(toBoolean(DISPLAY_FRONT_PAGE_LIST)); assertThat(contentValues.getAsString(ProgramModel.Columns.PROGRAM_TYPE)).isEqualTo(PROGRAM_TYPE.toString()); assertThat(contentValues.getAsString(ProgramModel.Columns.RELATIONSHIP_TYPE)).isEqualTo(RELATIONSHIP_TYPE); assertThat(contentValues.getAsString(ProgramModel.Columns.RELATIONSHIP_TEXT)).isEqualTo(RELATIONSHIP_TEXT); assertThat(contentValues.getAsString(ProgramModel.Columns.RELATED_PROGRAM)).isEqualTo(RELATED_PROGRAM); assertThat(contentValues.getAsString(ProgramModel.Columns.TRACKED_ENTITY_TYPE)).isEqualTo(TRACKED_ENTITY); assertThat(contentValues.getAsString(ProgramModel.Columns.CATEGORY_COMBO)).isEqualTo(CATEGORY_COMBO); assertThat(contentValues.getAsBoolean(ProgramModel.Columns.ACCESS_DATA_WRITE)) .isEqualTo(toBoolean(ACCESS_DATA_WRITE)); assertThat(contentValues.getAsInteger(ProgramModel.Columns.EXPIRY_DAYS)).isEqualTo(EXPIRY_DAYS); assertThat(contentValues.getAsInteger(ProgramModel.Columns.COMPLETE_EVENTS_EXPIRY_DAYS)) .isEqualTo(COMPLETE_EVENTS_EXPIRY_DAYS); assertThat(contentValues.getAsString(ProgramModel.Columns.EXPIRY_PERIOD_TYPE)) .isEqualTo(EXPIRY_PERIOD_TYPE.toString()); } }
min-attributes-to-search: adapt ProgramModelShould
core/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramModelShould.java
min-attributes-to-search: adapt ProgramModelShould
<ide><path>ore/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramModelShould.java <ide> private final static Integer EXPIRY_DAYS = 7; <ide> private final static Integer COMPLETE_EVENTS_EXPIRY_DAYS = 30; <ide> private final static PeriodType EXPIRY_PERIOD_TYPE = PeriodType.Daily; <add> private final static Integer MIN_ATTRIBUTES_REQUIRED_TO_SEARCH = 3; <ide> <ide> private final Date date; <ide> private final String dateString; <ide> Columns.ACCESS_DATA_WRITE, <ide> Columns.EXPIRY_DAYS, <ide> Columns.COMPLETE_EVENTS_EXPIRY_DAYS, <del> Columns.EXPIRY_PERIOD_TYPE <add> Columns.EXPIRY_PERIOD_TYPE, <add> Columns.MIN_ATTRIBUTES_REQUIRED_TO_SEARCH <ide> }); <ide> cursor.addRow(new Object[]{ID, UID, CODE, NAME, DISPLAY_NAME, dateString, dateString, <ide> SHORT_NAME, <ide> ACCESS_DATA_WRITE, <ide> EXPIRY_DAYS, <ide> COMPLETE_EVENTS_EXPIRY_DAYS, <del> EXPIRY_PERIOD_TYPE <add> EXPIRY_PERIOD_TYPE, <add> MIN_ATTRIBUTES_REQUIRED_TO_SEARCH <ide> }); <ide> cursor.moveToFirst(); <ide> <ide> assertThat(model.expiryDays()).isEqualTo(EXPIRY_DAYS); <ide> assertThat(model.completeEventsExpiryDays()).isEqualTo(COMPLETE_EVENTS_EXPIRY_DAYS); <ide> assertThat(model.expiryPeriodType()).isEqualTo(EXPIRY_PERIOD_TYPE); <add> assertThat(model.minAttributesRequiredToSearch()).isEqualTo(MIN_ATTRIBUTES_REQUIRED_TO_SEARCH); <ide> } <ide> <ide> @Test <ide> .expiryDays(EXPIRY_DAYS) <ide> .completeEventsExpiryDays(COMPLETE_EVENTS_EXPIRY_DAYS) <ide> .expiryPeriodType(EXPIRY_PERIOD_TYPE) <add> .minAttributesRequiredToSearch(MIN_ATTRIBUTES_REQUIRED_TO_SEARCH) <ide> .build(); <ide> ContentValues contentValues = model.toContentValues(); <ide> <ide> .isEqualTo(COMPLETE_EVENTS_EXPIRY_DAYS); <ide> assertThat(contentValues.getAsString(ProgramModel.Columns.EXPIRY_PERIOD_TYPE)) <ide> .isEqualTo(EXPIRY_PERIOD_TYPE.toString()); <add> assertThat(contentValues.getAsInteger(ProgramModel.Columns.MIN_ATTRIBUTES_REQUIRED_TO_SEARCH)) <add> .isEqualTo(MIN_ATTRIBUTES_REQUIRED_TO_SEARCH); <ide> } <ide> }
Java
mit
f7d48ca3006b9073f6ab848c01324547e31eb798
0
JPMoresmau/sqlg,pietermartin/sqlg,JPMoresmau/sqlg,pietermartin/sqlg,JPMoresmau/sqlg,pietermartin/sqlg,pietermartin/sqlg
package org.umlg.sqlg.test.repeatstep; import org.apache.commons.lang3.time.StopWatch; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Path; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeGlobalStep; import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions; import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.RepeatUnrollStrategy; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.AnyOf; import org.hamcrest.core.IsEqual; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.step.barrier.SqlgRepeatStepBarrier; import org.umlg.sqlg.test.BaseTest; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import static org.junit.Assert.assertFalse; /** * @author Pieter Martin (https://github.com/pietermartin) * Date: 2017/06/06 */ public class TestUnoptimizedRepeatStep extends BaseTest { // @Test //Takes very long need to investigate public void g_VX3X_repeatXbothX_createdXX_untilXloops_is_40XXemit_repeatXin_knowsXX_emit_loopsXisX1Xdedup_values() { loadModern(); Object id = convertToVertexId("lop"); // final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V(id) // .repeat(__.both("created")) // .until(loops().is(40)) // .emit( // __.repeat(__.in("knows")) // .emit(loops().is(1))) // .dedup().values("name"); final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V(id) .repeat(__.both("created")) .times(40) .dedup().values("name"); printTraversalForm(traversal); checkResults(Arrays.asList("josh", "ripple", "lop"), traversal); assertFalse(traversal.hasNext()); } // @Test public void testRepeatStepPerformance() { this.sqlgGraph.tx().normalBatchModeOn(); for (int i = 0; i < 1000; i++) { Vertex a; if (i % 100 == 0) { a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); } else { a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); } for (int j = 0; j < 10; j++) { Vertex b = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); a.addEdge("link", b); for (int k = 0; k < 10; k++) { Vertex c; if (k == 5) { c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); } else { c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); } b.addEdge("link", c); for (int l = 0; l < 10; l++) { Vertex d = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); c.addEdge("link", d); } } } } this.sqlgGraph.tx().commit(); System.out.println("==========================="); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 1000; i++) { stopWatch.start(); List<Path> vertices = this.sqlgGraph.traversal() .V().has("hubSite", true) .repeat(__.out()) .until(__.or(__.loops().is(P.gt(3)), __.has("hubSite", true))) // .until(__.has("hubSite", true)) .path() .toList(); Assert.assertEquals(10000, vertices.size()); stopWatch.stop(); System.out.println(stopWatch.toString()); stopWatch.reset(); } } // @Test public void testRepeatUtilFirstPerformance() { this.sqlgGraph.tx().normalBatchModeOn(); for (int i = 0; i < 10_000; i++) { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); } this.sqlgGraph.tx().commit(); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 1000; i++) { stopWatch.start(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(20_000, vertices.size()); stopWatch.stop(); System.out.println(stopWatch.toString()); stopWatch.reset(); } } @Test public void g_V_valueMapXname_ageX_withXtokens_labelsX_byXunfoldX() { loadModern(); final Traversal<Vertex, Map<Object, Object>> t = this.sqlgGraph.traversal().V() .valueMap("name", "age") .with(WithOptions.tokens, WithOptions.labels); List<Map<Object, Object>> result = t.toList(); System.out.println(result); final Traversal<Vertex, Map<Object, Object>> traversal = this.sqlgGraph.traversal().V() .valueMap("name", "age") .with(WithOptions.tokens, WithOptions.labels) .by(__.unfold()); printTraversalForm(traversal); int counter = 0; while (traversal.hasNext()) { counter++; final Map<Object, Object> values = traversal.next(); final String name = (String) values.get("name"); Assert.assertThat(values.containsKey(T.id), Matchers.is(false)); if (name.equals("marko")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(29, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("josh")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(32, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("peter")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(35, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("vadas")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(27, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("lop")) { Assert.assertEquals(2, values.size()); Assert.assertNull(values.get("lang")); Assert.assertEquals("software", values.get(T.label)); } else if (name.equals("ripple")) { Assert.assertEquals(2, values.size()); Assert.assertNull(values.get("lang")); Assert.assertEquals("software", values.get(T.label)); } else { throw new IllegalStateException("It is not possible to reach here: " + values); } } Assert.assertEquals(6, counter); } @Test public void g_V_emitXhasXname_markoX_or_loops_isX2XX_repeatXoutX_valuesXnameX() { loadModern(); final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V() .emit( __.has("name", "marko").or().loops().is(2) ) .repeat( __.out() ) .values("name"); printTraversalForm(traversal); checkResults(Arrays.asList("marko", "ripple", "lop"), traversal); } @Test public void g_VX6X_repeatXa_bothXcreatedX_simplePathX_emitXrepeatXb_bothXknowsXX_untilXloopsXbX_asXb_whereXloopsXaX_asXbX_hasXname_vadasXX_dedup_name() { loadModern(); Object peterId = this.convertToVertexId("peter"); Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V(peterId) .repeat("a", __.both("created").simplePath()) .emit( __.repeat("b", __.both("knows")) .until( __.loops("b").as("c").where(__.loops("a").as("c")) ) .has("name", "vadas") ).dedup().values("name"); this.printTraversalForm(traversal); Assert.assertTrue(traversal.hasNext()); String name = (String) traversal.next(); Assert.assertEquals("josh", name); Assert.assertFalse(traversal.hasNext()); } @Test public void g_V_repeatXout_repeatXoutX_timesX1XX_timesX1X_limitX1X_path_by_name() { loadModern(); Traversal<Vertex, Path> traversal_unrolled = this.sqlgGraph.traversal().V() .repeat( __.out().repeat( __.out() ).times(1) ).times(1).limit(1L).path().by("name"); Path pathOriginal = (Path) traversal_unrolled.next(); Assert.assertFalse(traversal_unrolled.hasNext()); Assert.assertEquals(3L, (long) pathOriginal.size()); Assert.assertEquals("marko", pathOriginal.get(0)); Assert.assertEquals("josh", pathOriginal.get(1)); MatcherAssert.assertThat(pathOriginal.get(2), AnyOf.anyOf(IsEqual.equalTo("ripple"), IsEqual.equalTo("lop"))); GraphTraversalSource g = this.sqlgGraph.traversal().withoutStrategies(new Class[]{RepeatUnrollStrategy.class}); Traversal<Vertex, Path> traversal = g.V() .repeat( __.out().repeat( __.out() ).times(1) ).times(1).limit(1L).path().by("name"); this.printTraversalForm(traversal); Path path = (Path) traversal.next(); Assert.assertFalse(traversal.hasNext()); Assert.assertEquals(3L, (long) path.size()); Assert.assertEquals("marko", path.get(0)); Assert.assertEquals("josh", path.get(1)); MatcherAssert.assertThat(path.get(2), AnyOf.anyOf(IsEqual.equalTo("ripple"), IsEqual.equalTo("lop"))); } @Test public void testRepeatStepWithUntilLast() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(c1)); } @Test public void testRepeatStepWithUntilLastEmitFirst() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .emit() .repeat(__.out()) .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(5, vertices.size()); Assert.assertTrue(vertices.contains(a1) && vertices.contains(a2) && vertices.contains(b1) || vertices.contains(b2) || vertices.contains(c2)); } @Test public void testRepeatStepWithUntilLastEmitLast() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .emit() .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(3, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(b2) || vertices.contains(c2)); } @Test public void testRepeatStepWithUntilFirst() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.out().has("name", "hallo")) .repeat(__.out()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(c2)); } @Test public void testRepeatStepWithUntilFirstEmitFirst() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.out().has("name", "hallo")) .emit() .repeat(__.out()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(5, vertices.size()); Assert.assertTrue(vertices.contains(a1) && vertices.contains(a2) && vertices.contains(b1) && vertices.contains(b2) && vertices.contains(c2)); } @Test public void testRepeatStepWithUntilFirstEmitLast() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.out().has("name", "hallo")) .repeat(__.out()) .emit(); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(5, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2) && vertices.contains(c2)); int count = 0; for (Vertex vertex : vertices) { if (vertex.equals(b1)) { count++; } } Assert.assertEquals(2, count); count = 0; for (Vertex vertex : vertices) { if (vertex.equals(c2)) { count++; } } Assert.assertEquals(2, count); } @Test public void testRepeatStepWithLimit() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.has(T.label, "B")) .repeat(__.out()) .limit(1); Assert.assertEquals(4, traversal.getSteps().size()); Assert.assertTrue(traversal.getSteps().get(2) instanceof RepeatStep); Assert.assertTrue(traversal.getSteps().get(3) instanceof RangeGlobalStep); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, traversal.getSteps().size()); Assert.assertTrue(traversal.getSteps().get(1) instanceof SqlgRepeatStepBarrier); Assert.assertEquals(1, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(b2)); vertices = this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .until(__.has(T.label, "B")) .limit(1) .toList(); Assert.assertEquals(1, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(b2)); } @Test public void testHubSites() { Vertex a0 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); Vertex a10 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a11 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a12 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a13 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a14 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); a0.addEdge("a", a10); a0.addEdge("a", a11); a0.addEdge("a", a13); a0.addEdge("a", a14); Vertex a20 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); Vertex a21 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a22 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a23 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); a10.addEdge("a", a20); a11.addEdge("a", a21); a12.addEdge("a", a22); a13.addEdge("a", a23); Vertex a30 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); Vertex a31 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); a21.addEdge("a", a30); a22.addEdge("a", a31); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal() .V(a0) .repeat(__.out()) // .until(__.or(__.loops().is(P.gt(3)), __.has("hubSite", true))) .until(__.has("hubSite", true)) .toList(); Assert.assertEquals(3, vertices.size()); List<Path> paths = this.sqlgGraph.traversal() .V(a0) .repeat(__.out()) .until(__.or(__.loops().is(P.gt(10)), __.has("hubSite", true))) .path() .toList(); Assert.assertEquals(3, paths.size()); List<Predicate<Path>> pathsToAssert = Arrays.asList( p -> p.size() == 3 && p.get(0).equals(a0) && p.get(1).equals(a10) && p.get(2).equals(a20), p -> p.size() == 4 && p.get(0).equals(a0) && p.get(1).equals(a11) && p.get(2).equals(a21) && p.get(3).equals(a30), p -> p.size() == 2 && p.get(0).equals(a0) && p.get(1).equals(a14) ); for (Predicate<Path> pathPredicate : pathsToAssert) { Optional<Path> path = paths.stream().filter(pathPredicate).findAny(); Assert.assertTrue(path.isPresent()); Assert.assertTrue(paths.remove(path.get())); } Assert.assertTrue(paths.isEmpty()); } @Test public void testUnoptimizedRepeatStep() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").until(__.has(T.label, "B")).repeat(__.out()).toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2)); vertices = this.sqlgGraph.traversal().V().hasLabel("A").repeat(__.out()).until(__.has(T.label, "B")).toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2)); } @Test public void testUnoptimizedRepeatStepUntilHasProperty() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1", "hub", true); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "name", "b2", "hub", true); a1.addEdge("ab", b1); a2.addEdge("ab", b2); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").repeat(__.out()).until(__.has("hub", true)).toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2)); } @Test public void testUnoptimizedRepeatDeep() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "hub", true); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "hub", false); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "hub", false); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B", "hub", false); a1.addEdge("ab", b1); a1.addEdge("ab", b2); a1.addEdge("ab", b3); Vertex c11 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c12 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c13 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); b1.addEdge("bc", c11); b1.addEdge("bc", c12); b1.addEdge("bc", c13); Vertex c21 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c22 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c23 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); b2.addEdge("bc", c21); b2.addEdge("bc", c22); b2.addEdge("bc", c23); Vertex c31 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c32 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c33 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); b3.addEdge("bc", c31); b3.addEdge("bc", c32); b3.addEdge("bc", c33); Vertex d = this.sqlgGraph.addVertex(T.label, "D", "hub", true); c11.addEdge("cd", d); c12.addEdge("cd", d); c13.addEdge("cd", d); c21.addEdge("cd", d); c22.addEdge("cd", d); c23.addEdge("cd", d); c31.addEdge("cd", d); c32.addEdge("cd", d); c33.addEdge("cd", d); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal() .V().hasLabel("A") .repeat( __.out() ) .until(__.has("hub", true)) .toList(); Assert.assertEquals(9, vertices.size()); } @Test public void testUnoptimizedRepeatStepOnGraphyGremlin() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "hub", true); Vertex a21 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a22 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a23 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a31 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a32 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a33 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a4 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a5 = this.sqlgGraph.addVertex(T.label, "A", "hub", true); a1.addEdge("aa", a21); a1.addEdge("aa", a22); a1.addEdge("aa", a23); a21.addEdge("aa", a31); a21.addEdge("aa", a32); a21.addEdge("aa", a33); a31.addEdge("aa", a4); a4.addEdge("aa", a5); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal() .V().hasLabel("A") .repeat( __.out() ).until( __.has("hub", true) ) .toList(); Assert.assertEquals(4, vertices.size()); Assert.assertEquals(a5, vertices.get(0)); Assert.assertEquals(a5, vertices.get(1)); Assert.assertEquals(a5, vertices.get(2)); Assert.assertEquals(a5, vertices.get(3)); } }
sqlg-test/src/main/java/org/umlg/sqlg/test/repeatstep/TestUnoptimizedRepeatStep.java
package org.umlg.sqlg.test.repeatstep; import org.apache.commons.lang3.time.StopWatch; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Path; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeGlobalStep; import org.apache.tinkerpop.gremlin.process.traversal.step.util.WithOptions; import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.RepeatUnrollStrategy; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.hamcrest.core.AnyOf; import org.hamcrest.core.IsEqual; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.step.barrier.SqlgRepeatStepBarrier; import org.umlg.sqlg.test.BaseTest; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; /** * @author Pieter Martin (https://github.com/pietermartin) * Date: 2017/06/06 */ public class TestUnoptimizedRepeatStep extends BaseTest { @Test public void testDot() { this.sqlgGraph.addVertex(T.label, "R_NTXSAM.xml_lag.Interface"); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("R_NTXSAM.xml_lag.Interface").toList(); Assert.assertEquals(1, vertices.size()); } // @Test public void testRepeatUtilFirstPerformance() { this.sqlgGraph.tx().normalBatchModeOn(); for (int i = 0; i < 10_000; i++) { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); } this.sqlgGraph.tx().commit(); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 1000; i++) { stopWatch.start(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(20_000, vertices.size()); stopWatch.stop(); System.out.println(stopWatch.toString()); stopWatch.reset(); } } @Test public void g_V_valueMapXname_ageX_withXtokens_labelsX_byXunfoldX() { loadModern(); final Traversal<Vertex, Map<Object, Object>> t = this.sqlgGraph.traversal().V() .valueMap("name", "age") .with(WithOptions.tokens, WithOptions.labels); List<Map<Object, Object>> result = t.toList(); System.out.println(result); final Traversal<Vertex, Map<Object, Object>> traversal = this.sqlgGraph.traversal().V() .valueMap("name", "age") .with(WithOptions.tokens, WithOptions.labels) .by(__.unfold()); printTraversalForm(traversal); int counter = 0; while (traversal.hasNext()) { counter++; final Map<Object, Object> values = traversal.next(); final String name = (String) values.get("name"); Assert.assertThat(values.containsKey(T.id), Matchers.is(false)); if (name.equals("marko")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(29, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("josh")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(32, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("peter")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(35, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("vadas")) { Assert.assertEquals(3, values.size()); Assert.assertEquals(27, values.get("age")); Assert.assertEquals("person", values.get(T.label)); } else if (name.equals("lop")) { Assert.assertEquals(2, values.size()); Assert.assertNull(values.get("lang")); Assert.assertEquals("software", values.get(T.label)); } else if (name.equals("ripple")) { Assert.assertEquals(2, values.size()); Assert.assertNull(values.get("lang")); Assert.assertEquals("software", values.get(T.label)); } else { throw new IllegalStateException("It is not possible to reach here: " + values); } } Assert.assertEquals(6, counter); } @Test public void g_V_emitXhasXname_markoX_or_loops_isX2XX_repeatXoutX_valuesXnameX() { loadModern(); final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V() .emit( __.has("name", "marko").or().loops().is(2) ) .repeat( __.out() ) .values("name"); printTraversalForm(traversal); checkResults(Arrays.asList("marko", "ripple", "lop"), traversal); } @Test public void g_VX6X_repeatXa_bothXcreatedX_simplePathX_emitXrepeatXb_bothXknowsXX_untilXloopsXbX_asXb_whereXloopsXaX_asXbX_hasXname_vadasXX_dedup_name() { loadModern(); Object peterId = this.convertToVertexId("peter"); Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V(peterId) .repeat("a", __.both("created").simplePath()) .emit( __.repeat("b", __.both("knows")) .until( __.loops("b").as("c").where(__.loops("a").as("c")) ) .has("name", "vadas") ).dedup().values("name"); this.printTraversalForm(traversal); Assert.assertTrue(traversal.hasNext()); String name = (String) traversal.next(); Assert.assertEquals("josh", name); Assert.assertFalse(traversal.hasNext()); } @Test public void g_V_repeatXout_repeatXoutX_timesX1XX_timesX1X_limitX1X_path_by_name() { loadModern(); Traversal<Vertex, Path> traversal_unrolled = this.sqlgGraph.traversal().V() .repeat( __.out().repeat( __.out() ).times(1) ).times(1).limit(1L).path().by("name"); Path pathOriginal = (Path) traversal_unrolled.next(); Assert.assertFalse(traversal_unrolled.hasNext()); Assert.assertEquals(3L, (long) pathOriginal.size()); Assert.assertEquals("marko", pathOriginal.get(0)); Assert.assertEquals("josh", pathOriginal.get(1)); MatcherAssert.assertThat(pathOriginal.get(2), AnyOf.anyOf(IsEqual.equalTo("ripple"), IsEqual.equalTo("lop"))); GraphTraversalSource g = this.sqlgGraph.traversal().withoutStrategies(new Class[]{RepeatUnrollStrategy.class}); Traversal<Vertex, Path> traversal = g.V() .repeat( __.out().repeat( __.out() ).times(1) ).times(1).limit(1L).path().by("name"); this.printTraversalForm(traversal); Path path = (Path) traversal.next(); Assert.assertFalse(traversal.hasNext()); Assert.assertEquals(3L, (long) path.size()); Assert.assertEquals("marko", path.get(0)); Assert.assertEquals("josh", path.get(1)); MatcherAssert.assertThat(path.get(2), AnyOf.anyOf(IsEqual.equalTo("ripple"), IsEqual.equalTo("lop"))); } @Test public void testRepeatStepWithUntilLast() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(c1)); } @Test public void testRepeatStepWithUntilLastEmitFirst() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .emit() .repeat(__.out()) .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(5, vertices.size()); Assert.assertTrue(vertices.contains(a1) && vertices.contains(a2) && vertices.contains(b1) || vertices.contains(b2) || vertices.contains(c2)); } @Test public void testRepeatStepWithUntilLastEmitLast() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .emit() .until(__.out().has("name", "hallo")); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(3, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(b2) || vertices.contains(c2)); } @Test public void testRepeatStepWithUntilFirst() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.out().has("name", "hallo")) .repeat(__.out()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(c2)); } @Test public void testRepeatStepWithUntilFirstEmitFirst() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.out().has("name", "hallo")) .emit() .repeat(__.out()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(5, vertices.size()); Assert.assertTrue(vertices.contains(a1) && vertices.contains(a2) && vertices.contains(b1) && vertices.contains(b2) && vertices.contains(c2)); } @Test public void testRepeatStepWithUntilFirstEmitLast() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex x = this.sqlgGraph.addVertex(T.label, "X", "name", "hallo"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); b1.addEdge("bc", c1); b2.addEdge("bc", c2); b1.addEdge("bx", x); c2.addEdge("cx", x); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.out().has("name", "hallo")) .repeat(__.out()) .emit(); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(5, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2) && vertices.contains(c2)); int count = 0; for (Vertex vertex : vertices) { if (vertex.equals(b1)) { count++; } } Assert.assertEquals(2, count); count = 0; for (Vertex vertex : vertices) { if (vertex.equals(c2)) { count++; } } Assert.assertEquals(2, count); } @Test public void testRepeatStepWithLimit() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V().hasLabel("A") .until(__.has(T.label, "B")) .repeat(__.out()) .limit(1); Assert.assertEquals(4, traversal.getSteps().size()); Assert.assertTrue(traversal.getSteps().get(2) instanceof RepeatStep); Assert.assertTrue(traversal.getSteps().get(3) instanceof RangeGlobalStep); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(2, traversal.getSteps().size()); Assert.assertTrue(traversal.getSteps().get(1) instanceof SqlgRepeatStepBarrier); Assert.assertEquals(1, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(b2)); vertices = this.sqlgGraph.traversal() .V().hasLabel("A") .repeat(__.out()) .until(__.has(T.label, "B")) .limit(1) .toList(); Assert.assertEquals(1, vertices.size()); Assert.assertTrue(vertices.contains(b1) || vertices.contains(b2)); } // @Test public void testRepeatStepPerformance() { this.sqlgGraph.tx().normalBatchModeOn(); for (int i = 0; i < 1000; i++) { Vertex a; if (i % 100 == 0) { a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); } else { a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); } for (int j = 0; j < 10; j++) { Vertex b = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); a.addEdge("link", b); for (int k = 0; k < 10; k++) { Vertex c; if (k == 5) { c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); } else { c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); } b.addEdge("link", c); for (int l = 0; l < 10; l++) { Vertex d = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); c.addEdge("link", d); } } } } this.sqlgGraph.tx().commit(); System.out.println("==========================="); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 1000; i++) { stopWatch.start(); List<Path> vertices = this.sqlgGraph.traversal() .V().has("hubSite", true) .repeat(__.out()) .until(__.or(__.loops().is(P.gt(3)), __.has("hubSite", true))) // .until(__.has("hubSite", true)) .path() .toList(); Assert.assertEquals(10000, vertices.size()); stopWatch.stop(); System.out.println(stopWatch.toString()); stopWatch.reset(); } } @Test public void testHubSites() { Vertex a0 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); Vertex a10 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a11 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a12 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a13 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a14 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); a0.addEdge("a", a10); a0.addEdge("a", a11); a0.addEdge("a", a13); a0.addEdge("a", a14); Vertex a20 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); Vertex a21 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a22 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); Vertex a23 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); a10.addEdge("a", a20); a11.addEdge("a", a21); a12.addEdge("a", a22); a13.addEdge("a", a23); Vertex a30 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); Vertex a31 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); a21.addEdge("a", a30); a22.addEdge("a", a31); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal() .V(a0) .repeat(__.out()) // .until(__.or(__.loops().is(P.gt(3)), __.has("hubSite", true))) .until(__.has("hubSite", true)) .toList(); Assert.assertEquals(3, vertices.size()); List<Path> paths = this.sqlgGraph.traversal() .V(a0) .repeat(__.out()) .until(__.or(__.loops().is(P.gt(10)), __.has("hubSite", true))) .path() .toList(); Assert.assertEquals(3, paths.size()); List<Predicate<Path>> pathsToAssert = Arrays.asList( p -> p.size() == 3 && p.get(0).equals(a0) && p.get(1).equals(a10) && p.get(2).equals(a20), p -> p.size() == 4 && p.get(0).equals(a0) && p.get(1).equals(a11) && p.get(2).equals(a21) && p.get(3).equals(a30), p -> p.size() == 2 && p.get(0).equals(a0) && p.get(1).equals(a14) ); for (Predicate<Path> pathPredicate : pathsToAssert) { Optional<Path> path = paths.stream().filter(pathPredicate).findAny(); Assert.assertTrue(path.isPresent()); Assert.assertTrue(paths.remove(path.get())); } Assert.assertTrue(paths.isEmpty()); } @Test public void testUnoptimizedRepeatStep() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").until(__.has(T.label, "B")).repeat(__.out()).toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2)); vertices = this.sqlgGraph.traversal().V().hasLabel("A").repeat(__.out()).until(__.has(T.label, "B")).toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2)); } @Test public void testUnoptimizedRepeatStepUntilHasProperty() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1", "hub", true); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "name", "b2", "hub", true); a1.addEdge("ab", b1); a2.addEdge("ab", b2); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").repeat(__.out()).until(__.has("hub", true)).toList(); Assert.assertEquals(2, vertices.size()); Assert.assertTrue(vertices.contains(b1) && vertices.contains(b2)); } @Test public void testUnoptimizedRepeatDeep() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "hub", true); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "hub", false); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "hub", false); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B", "hub", false); a1.addEdge("ab", b1); a1.addEdge("ab", b2); a1.addEdge("ab", b3); Vertex c11 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c12 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c13 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); b1.addEdge("bc", c11); b1.addEdge("bc", c12); b1.addEdge("bc", c13); Vertex c21 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c22 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c23 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); b2.addEdge("bc", c21); b2.addEdge("bc", c22); b2.addEdge("bc", c23); Vertex c31 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c32 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); Vertex c33 = this.sqlgGraph.addVertex(T.label, "C", "hub", false); b3.addEdge("bc", c31); b3.addEdge("bc", c32); b3.addEdge("bc", c33); Vertex d = this.sqlgGraph.addVertex(T.label, "D", "hub", true); c11.addEdge("cd", d); c12.addEdge("cd", d); c13.addEdge("cd", d); c21.addEdge("cd", d); c22.addEdge("cd", d); c23.addEdge("cd", d); c31.addEdge("cd", d); c32.addEdge("cd", d); c33.addEdge("cd", d); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal() .V().hasLabel("A") .repeat( __.out() ) .until(__.has("hub", true)) .toList(); Assert.assertEquals(9, vertices.size()); } @Test public void testUnoptimizedRepeatStepOnGraphyGremlin() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "hub", true); Vertex a21 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a22 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a23 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a31 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a32 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a33 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a4 = this.sqlgGraph.addVertex(T.label, "A", "hub", false); Vertex a5 = this.sqlgGraph.addVertex(T.label, "A", "hub", true); a1.addEdge("aa", a21); a1.addEdge("aa", a22); a1.addEdge("aa", a23); a21.addEdge("aa", a31); a21.addEdge("aa", a32); a21.addEdge("aa", a33); a31.addEdge("aa", a4); a4.addEdge("aa", a5); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal() .V().hasLabel("A") .repeat( __.out() ).until( __.has("hub", true) ) .toList(); Assert.assertEquals(4, vertices.size()); Assert.assertEquals(a5, vertices.get(0)); Assert.assertEquals(a5, vertices.get(1)); Assert.assertEquals(a5, vertices.get(2)); Assert.assertEquals(a5, vertices.get(3)); } }
added performance test to investigate
sqlg-test/src/main/java/org/umlg/sqlg/test/repeatstep/TestUnoptimizedRepeatStep.java
added performance test to investigate
<ide><path>qlg-test/src/main/java/org/umlg/sqlg/test/repeatstep/TestUnoptimizedRepeatStep.java <ide> import java.util.Optional; <ide> import java.util.function.Predicate; <ide> <add>import static org.junit.Assert.assertFalse; <add> <ide> /** <ide> * @author Pieter Martin (https://github.com/pietermartin) <ide> * Date: 2017/06/06 <ide> */ <ide> public class TestUnoptimizedRepeatStep extends BaseTest { <ide> <del> @Test <del> public void testDot() { <del> this.sqlgGraph.addVertex(T.label, "R_NTXSAM.xml_lag.Interface"); <del> this.sqlgGraph.tx().commit(); <del> List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("R_NTXSAM.xml_lag.Interface").toList(); <del> Assert.assertEquals(1, vertices.size()); <del> } <del> <ide> // @Test <add> //Takes very long need to investigate <add> public void g_VX3X_repeatXbothX_createdXX_untilXloops_is_40XXemit_repeatXin_knowsXX_emit_loopsXisX1Xdedup_values() { <add> loadModern(); <add> Object id = convertToVertexId("lop"); <add>// final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V(id) <add>// .repeat(__.both("created")) <add>// .until(loops().is(40)) <add>// .emit( <add>// __.repeat(__.in("knows")) <add>// .emit(loops().is(1))) <add>// .dedup().values("name"); <add> <add> <add> final Traversal<Vertex, String> traversal = this.sqlgGraph.traversal().V(id) <add> .repeat(__.both("created")) <add> .times(40) <add> .dedup().values("name"); <add> <add> printTraversalForm(traversal); <add> checkResults(Arrays.asList("josh", "ripple", "lop"), traversal); <add> assertFalse(traversal.hasNext()); <add> } <add> <add> // @Test <add> public void testRepeatStepPerformance() { <add> this.sqlgGraph.tx().normalBatchModeOn(); <add> for (int i = 0; i < 1000; i++) { <add> Vertex a; <add> if (i % 100 == 0) { <add> a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); <add> } else { <add> a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <add> } <add> for (int j = 0; j < 10; j++) { <add> Vertex b = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <add> a.addEdge("link", b); <add> for (int k = 0; k < 10; k++) { <add> Vertex c; <add> if (k == 5) { <add> c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <add> } else { <add> c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <add> } <add> b.addEdge("link", c); <add> <add> for (int l = 0; l < 10; l++) { <add> Vertex d = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); <add> c.addEdge("link", d); <add> } <add> } <add> } <add> } <add> this.sqlgGraph.tx().commit(); <add> <add> System.out.println("==========================="); <add> <add> StopWatch stopWatch = new StopWatch(); <add> for (int i = 0; i < 1000; i++) { <add> stopWatch.start(); <add> List<Path> vertices = this.sqlgGraph.traversal() <add> .V().has("hubSite", true) <add> .repeat(__.out()) <add> .until(__.or(__.loops().is(P.gt(3)), __.has("hubSite", true))) <add>// .until(__.has("hubSite", true)) <add> .path() <add> .toList(); <add> Assert.assertEquals(10000, vertices.size()); <add> stopWatch.stop(); <add> System.out.println(stopWatch.toString()); <add> stopWatch.reset(); <add> } <add> } <add> <add> <add> // @Test <ide> public void testRepeatUtilFirstPerformance() { <ide> this.sqlgGraph.tx().normalBatchModeOn(); <ide> for (int i = 0; i < 10_000; i++) { <ide> <ide> } <ide> <del> // @Test <del> public void testRepeatStepPerformance() { <del> this.sqlgGraph.tx().normalBatchModeOn(); <del> for (int i = 0; i < 1000; i++) { <del> Vertex a; <del> if (i % 100 == 0) { <del> a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); <del> } else { <del> a = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <del> } <del> for (int j = 0; j < 10; j++) { <del> Vertex b = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <del> a.addEdge("link", b); <del> for (int k = 0; k < 10; k++) { <del> Vertex c; <del> if (k == 5) { <del> c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <del> } else { <del> c = this.sqlgGraph.addVertex(T.label, "A", "hubSite", false); <del> } <del> b.addEdge("link", c); <del> <del> for (int l = 0; l < 10; l++) { <del> Vertex d = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true); <del> c.addEdge("link", d); <del> } <del> } <del> } <del> } <del> this.sqlgGraph.tx().commit(); <del> <del> System.out.println("==========================="); <del> <del> StopWatch stopWatch = new StopWatch(); <del> for (int i = 0; i < 1000; i++) { <del> stopWatch.start(); <del> List<Path> vertices = this.sqlgGraph.traversal() <del> .V().has("hubSite", true) <del> .repeat(__.out()) <del> .until(__.or(__.loops().is(P.gt(3)), __.has("hubSite", true))) <del>// .until(__.has("hubSite", true)) <del> .path() <del> .toList(); <del> Assert.assertEquals(10000, vertices.size()); <del> stopWatch.stop(); <del> System.out.println(stopWatch.toString()); <del> stopWatch.reset(); <del> } <del> } <del> <ide> @Test <ide> public void testHubSites() { <ide> Vertex a0 = this.sqlgGraph.addVertex(T.label, "A", "hubSite", true);
Java
bsd-3-clause
cc1202ccb8076dc7fe64c87b43ce6058815dfb2e
0
NCIP/c3pr,NCIP/c3pr,NCIP/c3pr
package edu.duke.cabig.c3pr.domain.repository.impl; import java.util.Iterator; import java.util.List; import javax.persistence.Transient; import org.apache.log4j.Logger; import org.springframework.context.MessageSource; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.dao.EpochDao; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.dao.StratumGroupDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.domain.Arm; import edu.duke.cabig.c3pr.domain.BookRandomization; import edu.duke.cabig.c3pr.domain.BookRandomizationEntry; import edu.duke.cabig.c3pr.domain.Epoch; import edu.duke.cabig.c3pr.domain.NonTreatmentEpoch; import edu.duke.cabig.c3pr.domain.RegistrationDataEntryStatus; import edu.duke.cabig.c3pr.domain.RegistrationWorkFlowStatus; import edu.duke.cabig.c3pr.domain.ScheduledArm; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.ScheduledEpochDataEntryStatus; import edu.duke.cabig.c3pr.domain.ScheduledEpochWorkFlowStatus; import edu.duke.cabig.c3pr.domain.ScheduledNonTreatmentEpoch; import edu.duke.cabig.c3pr.domain.ScheduledTreatmentEpoch; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.factory.StudySubjectFactory; import edu.duke.cabig.c3pr.domain.repository.StudySubjectRepository; import edu.duke.cabig.c3pr.exception.C3PRBaseException; import edu.duke.cabig.c3pr.exception.C3PRCodedException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.service.impl.StudySubjectXMLImporterServiceImpl; @Transactional public class StudySubjectRepositoryImpl implements StudySubjectRepository { private StudySubjectDao studySubjectDao; private ParticipantDao participantDao; private EpochDao epochDao; private StratumGroupDao stratumGroupDao; private C3PRExceptionHelper exceptionHelper; private MessageSource c3prErrorMessages; private StudySubjectFactory studySubjectFactory; private Logger log = Logger.getLogger(StudySubjectXMLImporterServiceImpl.class.getName()); public void assignC3DIdentifier(StudySubject studySubject, String c3dIdentifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setC3DIdentifier(c3dIdentifierValue); studySubjectDao.save(loadedSubject); } public void assignCoOrdinatingCenterIdentifier(StudySubject studySubject, String identifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setCoOrdinatingCenterIdentifier(identifierValue); studySubjectDao.save(loadedSubject); } public boolean isEpochAccrualCeilingReached(int epochId) { Epoch epoch = epochDao.getById(epochId); if (epoch.isReserving()) { ScheduledEpoch scheduledEpoch = new ScheduledNonTreatmentEpoch(true); scheduledEpoch.setEpoch(epoch); List<StudySubject> list = studySubjectDao.searchByScheduledEpoch(scheduledEpoch); NonTreatmentEpoch nEpoch = (NonTreatmentEpoch) epoch; if (nEpoch.getAccrualCeiling() != null && list.size() >= nEpoch.getAccrualCeiling().intValue()) { return true; } } return false; } private StudySubject doRandomization(StudySubject studySubject) throws C3PRBaseException { // randomize subject switch (studySubject.getStudySite().getStudy().getRandomizationType()) { case PHONE_CALL: break; case BOOK: doBookRandomization(studySubject); break; case CALL_OUT: break; default: break; } return studySubject; } private void doBookRandomization(StudySubject studySubject) throws C3PRBaseException { ScheduledArm sa = new ScheduledArm(); ScheduledTreatmentEpoch ste = (ScheduledTreatmentEpoch) studySubject.getScheduledEpoch(); if (studySubject.getStudySite().getStudy().getStratificationIndicator()){ sa.setArm(studySubject.getStratumGroup().getNextArm()); if (sa.getArm() != null) { ste.addScheduledArm(sa); stratumGroupDao.merge(studySubject.getStratumGroup()); } } else { sa.setArm(getNextArmForUnstratifiedStudy(studySubject)); if (sa.getArm() != null) { ste.addScheduledArm(sa); } } } public StudySubject doLocalRegistration(StudySubject studySubject) throws C3PRCodedException { studySubject.updateDataEntryStatus(); if (!studySubject.isDataEntryComplete()) return studySubject; ScheduledEpoch scheduledEpoch = studySubject.getScheduledEpoch(); if (studySubject.getScheduledEpoch().getRequiresRandomization()) { try { this.doRandomization(studySubject); } catch (Exception e) { scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.UNAPPROVED); throw exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.RANDOMIZATION.CODE"), e); } if (((ScheduledTreatmentEpoch) studySubject.getScheduledEpoch()).getScheduledArm() == null) { scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.UNAPPROVED); throw exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.CANNOT_ASSIGN_ARM.CODE")); } else { // logic for accrual ceiling check scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED); } } else { // logic for accrual ceiling check scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED); } return this.save(studySubject); } /** * Saves the Imported StudySubject to the database. Moved it from the service as a part of the * refactoring effort. * * @param deserialedStudySubject * @return * @throws C3PRCodedException */ @Transactional(readOnly = false) public StudySubject importStudySubject(StudySubject deserialedStudySubject) throws C3PRCodedException { StudySubject studySubject = studySubjectFactory.buildStudySubject(deserialedStudySubject); if (studySubject.getParticipant().getId() != null) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(studySubject.getParticipant()); exampleSS.setStudySite(studySubject.getStudySite()); List<StudySubject> registrations = studySubjectDao.searchBySubjectAndStudySite(exampleSS); if (registrations.size() > 0) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE")); } } else { if (studySubject.getParticipant().validateParticipant()) participantDao.save(studySubject.getParticipant()); else { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE")); } } if (studySubject.getScheduledEpoch().getEpoch().getRequiresArm()) { ScheduledTreatmentEpoch scheduledTreatmentEpoch = (ScheduledTreatmentEpoch) studySubject .getScheduledEpoch(); if (scheduledTreatmentEpoch.getScheduledArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm().getId() == null) throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.IMPORT.REQUIRED.ARM.NOTFOUND.CODE")); } studySubject.setRegDataEntryStatus(studySubject.evaluateRegistrationDataEntryStatus()); studySubject.getScheduledEpoch().setScEpochDataEntryStatus(studySubject.evaluateScheduledEpochDataEntryStatus()); if (studySubject.getRegDataEntryStatus() == RegistrationDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.DATA_ENTRY_INCOMPLETE.CODE")); } if (studySubject.getScheduledEpoch().getScEpochDataEntryStatus() == ScheduledEpochDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SCHEDULEDEPOCH.DATA_ENTRY_INCOMPLETE.CODE")); } if (studySubject.getScheduledEpoch().isReserving()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.RESERVED); } else if (studySubject.getScheduledEpoch().getEpoch().isEnrolling()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.REGISTERED); } else { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.UNREGISTERED); } studySubjectDao.save(studySubject); log.debug("Registration saved with grid ID" + studySubject.getGridId()); return studySubject; } @Transient public Arm getNextArmForUnstratifiedStudy(StudySubject studySubject) throws C3PRBaseException { Arm arm = null; if (studySubject.getScheduledEpoch() instanceof ScheduledTreatmentEpoch){ if (((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).getTreatmentEpoch().hasBookRandomizationEntry()){ Iterator<BookRandomizationEntry> iter = ((BookRandomization)((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).getTreatmentEpoch().getRandomization()).getBookRandomizationEntry().iterator(); BookRandomizationEntry breTemp; while (iter.hasNext()) { breTemp = iter.next(); if (breTemp.getPosition().equals(((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).getCurrentPosition())) { synchronized (this) { ((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).setCurrentPosition(breTemp.getPosition()+1); arm = breTemp.getArm(); break; } } } } } if (arm == null) { throw new C3PRBaseException( "No Arm avalable for this Treatment Epoch. Maybe the Randomization Book is exhausted"); } return arm; } public void setStudySubjectDao(StudySubjectDao studySubjectDao) { this.studySubjectDao = studySubjectDao; } public void setEpochDao(EpochDao epochDao) { this.epochDao = epochDao; } public void setStratumGroupDao(StratumGroupDao stratumGroupDao) { this.stratumGroupDao = stratumGroupDao; } public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) { this.exceptionHelper = exceptionHelper; } public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } private int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null)); } public StudySubject save(StudySubject studySubject) { studySubject.updateDataEntryStatus(); if (studySubject.getId() != null) return studySubjectDao.merge(studySubject); studySubjectDao.save(studySubject); return studySubject; } public void setStudySubjectFactory(StudySubjectFactory studySubjectFactory) { this.studySubjectFactory = studySubjectFactory; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } }
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/repository/impl/StudySubjectRepositoryImpl.java
package edu.duke.cabig.c3pr.domain.repository.impl; import java.util.List; import org.apache.log4j.Logger; import org.springframework.context.MessageSource; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.dao.EpochDao; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.dao.StratumGroupDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.domain.Epoch; import edu.duke.cabig.c3pr.domain.NonTreatmentEpoch; import edu.duke.cabig.c3pr.domain.RegistrationDataEntryStatus; import edu.duke.cabig.c3pr.domain.RegistrationWorkFlowStatus; import edu.duke.cabig.c3pr.domain.ScheduledArm; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.ScheduledEpochDataEntryStatus; import edu.duke.cabig.c3pr.domain.ScheduledEpochWorkFlowStatus; import edu.duke.cabig.c3pr.domain.ScheduledNonTreatmentEpoch; import edu.duke.cabig.c3pr.domain.ScheduledTreatmentEpoch; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.factory.StudySubjectFactory; import edu.duke.cabig.c3pr.domain.repository.StudySubjectRepository; import edu.duke.cabig.c3pr.exception.C3PRBaseException; import edu.duke.cabig.c3pr.exception.C3PRCodedException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.service.impl.StudySubjectXMLImporterServiceImpl; @Transactional public class StudySubjectRepositoryImpl implements StudySubjectRepository { private StudySubjectDao studySubjectDao; private ParticipantDao participantDao; private EpochDao epochDao; private StratumGroupDao stratumGroupDao; private C3PRExceptionHelper exceptionHelper; private MessageSource c3prErrorMessages; private StudySubjectFactory studySubjectFactory; private Logger log = Logger.getLogger(StudySubjectXMLImporterServiceImpl.class.getName()); public void assignC3DIdentifier(StudySubject studySubject, String c3dIdentifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setC3DIdentifier(c3dIdentifierValue); studySubjectDao.save(loadedSubject); } public void assignCoOrdinatingCenterIdentifier(StudySubject studySubject, String identifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setCoOrdinatingCenterIdentifier(identifierValue); studySubjectDao.save(loadedSubject); } public boolean isEpochAccrualCeilingReached(int epochId) { Epoch epoch = epochDao.getById(epochId); if (epoch.isReserving()) { ScheduledEpoch scheduledEpoch = new ScheduledNonTreatmentEpoch(true); scheduledEpoch.setEpoch(epoch); List<StudySubject> list = studySubjectDao.searchByScheduledEpoch(scheduledEpoch); NonTreatmentEpoch nEpoch = (NonTreatmentEpoch) epoch; if (nEpoch.getAccrualCeiling() != null && list.size() >= nEpoch.getAccrualCeiling().intValue()) { return true; } } return false; } private StudySubject doRandomization(StudySubject studySubject) throws C3PRBaseException { // randomize subject switch (studySubject.getStudySite().getStudy().getRandomizationType()) { case PHONE_CALL: break; case BOOK: doBookRandomization(studySubject); break; case CALL_OUT: break; default: break; } return studySubject; } private void doBookRandomization(StudySubject studySubject) throws C3PRBaseException { ScheduledArm sa = new ScheduledArm(); ScheduledTreatmentEpoch ste = (ScheduledTreatmentEpoch) studySubject.getScheduledEpoch(); sa.setArm(studySubject.getStratumGroup().getNextArm()); if (sa.getArm() != null) { ste.addScheduledArm(sa); stratumGroupDao.merge(studySubject.getStratumGroup()); } } public StudySubject doLocalRegistration(StudySubject studySubject) throws C3PRCodedException { studySubject.updateDataEntryStatus(); if (!studySubject.isDataEntryComplete()) return studySubject; ScheduledEpoch scheduledEpoch = studySubject.getScheduledEpoch(); if (studySubject.getScheduledEpoch().getRequiresRandomization()) { try { this.doRandomization(studySubject); } catch (Exception e) { scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.UNAPPROVED); throw exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.RANDOMIZATION.CODE"), e); } if (((ScheduledTreatmentEpoch) studySubject.getScheduledEpoch()).getScheduledArm() == null) { scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.UNAPPROVED); throw exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.CANNOT_ASSIGN_ARM.CODE")); } else { // logic for accrual ceiling check scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED); } } else { // logic for accrual ceiling check scheduledEpoch.setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED); } return this.save(studySubject); } /** * Saves the Imported StudySubject to the database. Moved it from the service as a part of the * refactoring effort. * * @param deserialedStudySubject * @return * @throws C3PRCodedException */ @Transactional(readOnly = false) public StudySubject importStudySubject(StudySubject deserialedStudySubject) throws C3PRCodedException { StudySubject studySubject = studySubjectFactory.buildStudySubject(deserialedStudySubject); if (studySubject.getParticipant().getId() != null) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(studySubject.getParticipant()); exampleSS.setStudySite(studySubject.getStudySite()); List<StudySubject> registrations = studySubjectDao.searchBySubjectAndStudySite(exampleSS); if (registrations.size() > 0) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE")); } } else { if (studySubject.getParticipant().validateParticipant()) participantDao.save(studySubject.getParticipant()); else { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE")); } } if (studySubject.getScheduledEpoch().getEpoch().getRequiresArm()) { ScheduledTreatmentEpoch scheduledTreatmentEpoch = (ScheduledTreatmentEpoch) studySubject .getScheduledEpoch(); if (scheduledTreatmentEpoch.getScheduledArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm().getId() == null) throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.IMPORT.REQUIRED.ARM.NOTFOUND.CODE")); } studySubject.setRegDataEntryStatus(studySubject.evaluateRegistrationDataEntryStatus()); studySubject.getScheduledEpoch().setScEpochDataEntryStatus(studySubject.evaluateScheduledEpochDataEntryStatus()); if (studySubject.getRegDataEntryStatus() == RegistrationDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.DATA_ENTRY_INCOMPLETE.CODE")); } if (studySubject.getScheduledEpoch().getScEpochDataEntryStatus() == ScheduledEpochDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SCHEDULEDEPOCH.DATA_ENTRY_INCOMPLETE.CODE")); } if (studySubject.getScheduledEpoch().isReserving()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.RESERVED); } else if (studySubject.getScheduledEpoch().getEpoch().isEnrolling()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.REGISTERED); } else { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.UNREGISTERED); } studySubjectDao.save(studySubject); log.debug("Registration saved with grid ID" + studySubject.getGridId()); return studySubject; } public void setStudySubjectDao(StudySubjectDao studySubjectDao) { this.studySubjectDao = studySubjectDao; } public void setEpochDao(EpochDao epochDao) { this.epochDao = epochDao; } public void setStratumGroupDao(StratumGroupDao stratumGroupDao) { this.stratumGroupDao = stratumGroupDao; } public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) { this.exceptionHelper = exceptionHelper; } public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } private int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null)); } public StudySubject save(StudySubject studySubject) { studySubject.updateDataEntryStatus(); if (studySubject.getId() != null) return studySubjectDao.merge(studySubject); studySubjectDao.save(studySubject); return studySubject; } public void setStudySubjectFactory(StudySubjectFactory studySubjectFactory) { this.studySubjectFactory = studySubjectFactory; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } }
updated for straight randomization
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/repository/impl/StudySubjectRepositoryImpl.java
updated for straight randomization
<ide><path>odebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/repository/impl/StudySubjectRepositoryImpl.java <ide> package edu.duke.cabig.c3pr.domain.repository.impl; <ide> <add>import java.util.Iterator; <ide> import java.util.List; <add> <add>import javax.persistence.Transient; <ide> <ide> import org.apache.log4j.Logger; <ide> import org.springframework.context.MessageSource; <ide> import edu.duke.cabig.c3pr.dao.ParticipantDao; <ide> import edu.duke.cabig.c3pr.dao.StratumGroupDao; <ide> import edu.duke.cabig.c3pr.dao.StudySubjectDao; <add>import edu.duke.cabig.c3pr.domain.Arm; <add>import edu.duke.cabig.c3pr.domain.BookRandomization; <add>import edu.duke.cabig.c3pr.domain.BookRandomizationEntry; <ide> import edu.duke.cabig.c3pr.domain.Epoch; <ide> import edu.duke.cabig.c3pr.domain.NonTreatmentEpoch; <ide> import edu.duke.cabig.c3pr.domain.RegistrationDataEntryStatus; <ide> private void doBookRandomization(StudySubject studySubject) throws C3PRBaseException { <ide> ScheduledArm sa = new ScheduledArm(); <ide> ScheduledTreatmentEpoch ste = (ScheduledTreatmentEpoch) studySubject.getScheduledEpoch(); <del> sa.setArm(studySubject.getStratumGroup().getNextArm()); <del> if (sa.getArm() != null) { <del> ste.addScheduledArm(sa); <del> stratumGroupDao.merge(studySubject.getStratumGroup()); <add> if (studySubject.getStudySite().getStudy().getStratificationIndicator()){ <add> sa.setArm(studySubject.getStratumGroup().getNextArm()); <add> if (sa.getArm() != null) { <add> ste.addScheduledArm(sa); <add> stratumGroupDao.merge(studySubject.getStratumGroup()); <add> } <add> } else { <add> sa.setArm(getNextArmForUnstratifiedStudy(studySubject)); <add> if (sa.getArm() != null) { <add> ste.addScheduledArm(sa); <add> } <ide> } <ide> } <ide> <ide> return studySubject; <ide> } <ide> <add> @Transient <add> public Arm getNextArmForUnstratifiedStudy(StudySubject studySubject) throws C3PRBaseException { <add> Arm arm = null; <add> if (studySubject.getScheduledEpoch() instanceof ScheduledTreatmentEpoch){ <add> if (((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).getTreatmentEpoch().hasBookRandomizationEntry()){ <add> Iterator<BookRandomizationEntry> iter = ((BookRandomization)((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).getTreatmentEpoch().getRandomization()).getBookRandomizationEntry().iterator(); <add> BookRandomizationEntry breTemp; <add> <add> while (iter.hasNext()) { <add> breTemp = iter.next(); <add> if (breTemp.getPosition().equals(((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).getCurrentPosition())) { <add> synchronized (this) { <add> ((ScheduledTreatmentEpoch)studySubject.getScheduledEpoch()).setCurrentPosition(breTemp.getPosition()+1); <add> arm = breTemp.getArm(); <add> break; <add> } <add> } <add> } <add> } <add> } <add> <add> if (arm == null) { <add> throw new C3PRBaseException( <add> "No Arm avalable for this Treatment Epoch. Maybe the Randomization Book is exhausted"); <add> } <add> return arm; <add> } <add> <ide> <ide> public void setStudySubjectDao(StudySubjectDao studySubjectDao) { <ide> this.studySubjectDao = studySubjectDao; <ide> public void setParticipantDao(ParticipantDao participantDao) { <ide> this.participantDao = participantDao; <ide> } <add> <ide> }
Java
apache-2.0
5acd8fc8f05d262b06374277dc465183a6043e0e
0
simonsoft/cms-item
/** * Copyright (C) 2009-2017 Simonsoft Nordic AB * * 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 se.simonsoft.cms.item.workflow; import com.fasterxml.jackson.annotation.JsonGetter; import se.simonsoft.cms.item.CmsItemId; public interface WorkflowItemInput { /** * @return action name as a single token */ String getAction(); /** * @return item which the action operates on */ @JsonGetter("itemid") CmsItemId getItemId(); }
src/main/java/se/simonsoft/cms/item/workflow/WorkflowItemInput.java
/** * Copyright (C) 2009-2017 Simonsoft Nordic AB * * 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 se.simonsoft.cms.item.workflow; import com.fasterxml.jackson.annotation.JsonGetter; import se.simonsoft.cms.item.CmsItemId; public interface WorkflowItemInput { String getAction(); @JsonGetter("itemid") CmsItemId getItemId(); }
Add Javadoc.
src/main/java/se/simonsoft/cms/item/workflow/WorkflowItemInput.java
Add Javadoc.
<ide><path>rc/main/java/se/simonsoft/cms/item/workflow/WorkflowItemInput.java <ide> <ide> public interface WorkflowItemInput { <ide> <add> /** <add> * @return action name as a single token <add> */ <ide> String getAction(); <ide> <add> /** <add> * @return item which the action operates on <add> */ <ide> @JsonGetter("itemid") <ide> CmsItemId getItemId(); <ide> }
Java
mit
12c614467b372c868a9faf1e233fa16383cf6233
0
mprzybylak/presentation-rxjavaquick,mprzybylak/presentation-rxjavaquick,mprzybylak/presentation-rxjavaquick
package pl.mprzybylak.presentation.rxjavaquick; import io.reactivex.Observable; import org.junit.Test; import pl.mprzybylak.presentation.rxjavaquik.FibonacciNumberService; import pl.mprzybylak.presentation.rxjavaquik.Money; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; public class CreateObservableTest { @Test public void fromSingleObject() { // given String[] hello = new String[] {"f", "o", "o"}; AtomicReference<String[]> result = new AtomicReference<>(); // when Observable.just(hello).subscribe(result::set); // then assertThat(result.get()).isNotInstanceOf(String.class); assertThat(result.get()).isInstanceOf(String[].class); } @Test public void fromArray() { //given Money[] expensesForToday = { money(100), money(5), money(25), money(5), money(35) }; Money totalExpenses = money(0); // when Observable.fromArray(expensesForToday).subscribe(totalExpenses::add); // then assertThat(totalExpenses).isEqualTo(money(170)); } @Test public void fromIterable() { // given List<Money> expensesForToday = Arrays.asList(money(100), money(5), money(25), money(5), money(35)); Money totalExpenses = money(0); // when Observable.fromIterable(expensesForToday).subscribe(totalExpenses::add); // then assertThat(totalExpenses).isEqualTo(money(170)); } @Test public void lazyMethodCall() { // given final AtomicInteger counter = new AtomicInteger(0); Callable<Integer> tick = counter::incrementAndGet; AtomicInteger firstTick = new AtomicInteger(0); AtomicInteger secondTick = new AtomicInteger(0); AtomicInteger thirdTick = new AtomicInteger(0); // when Observable<Integer> observable = Observable.fromCallable(tick); observable.subscribe(firstTick::set); observable.subscribe(secondTick::set); observable.subscribe(thirdTick::set); // then assertThat(firstTick.get()).isEqualTo(1); assertThat(secondTick.get()).isEqualTo(2); assertThat(thirdTick.get()).isEqualTo(3); } @Test public void lazyObservableCreation() { // given AtomicInteger firstResult = new AtomicInteger(0); AtomicInteger secondResult = new AtomicInteger(0); AtomicInteger thirdResult = new AtomicInteger(0); AtomicInteger value = new AtomicInteger(1); Observable<Integer> deferredObservable = Observable.defer(() -> Observable.just(value.get())); // when value.set(10); deferredObservable.subscribe(firstResult::set); value.set(100); deferredObservable.subscribe(secondResult::set); value.set(1000); deferredObservable.subscribe(thirdResult::set); // then assertThat(firstResult.get()).isEqualTo(10); assertThat(secondResult.get()).isEqualTo(100); assertThat(thirdResult.get()).isEqualTo(1000); } @Test public void fromFuture() { // given Future<Integer> fibonacciComputation = new FibonacciNumberService().countNthFibonacciNumber(20); AtomicInteger fibonacciNumber = new AtomicInteger(0); // when Observable.fromFuture(fibonacciComputation).subscribe(fibonacciNumber::set); // then assertThat(fibonacciNumber.get()).isEqualTo(6765); } @Test public void orderedSequenceOfConsecutiveNumbers() { // given List<Integer> sequence = new ArrayList<>(10); // when Observable.range(0, 10).subscribe(sequence::add); // then assertThat(sequence.size()).isEqualTo(10); assertThat(sequence.get(0)).isEqualTo(0); assertThat(sequence.get(sequence.size() - 1)).isEqualTo(9); } private Money money(long value) { return new Money(value); } }
src/test/java/pl/mprzybylak/presentation/rxjavaquick/CreateObservableTest.java
package pl.mprzybylak.presentation.rxjavaquick; import io.reactivex.Observable; import org.junit.Test; import pl.mprzybylak.presentation.rxjavaquik.FibonacciNumberService; import pl.mprzybylak.presentation.rxjavaquik.Money; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; public class CreateObservableTest { @Test public void fromSingleObject() { // given String[] hello = new String[] {"f", "o", "o"}; AtomicReference<String[]> result = new AtomicReference<>(); // when Observable.just(hello).subscribe(result::set); // then assertThat(result.get()).isNotInstanceOf(String.class); assertThat(result.get()).isInstanceOf(String[].class); } @Test public void fromArray() { //given Money[] expensesForToday = { money(100), money(5), money(25), money(5), money(35) }; Money totalExpenses = money(0); // when Observable.fromArray(expensesForToday).subscribe(totalExpenses::add); // then assertThat(totalExpenses).isEqualTo(money(170)); } @Test public void fromIterable() { // given List<Money> expensesForToday = Arrays.asList(money(100), money(5), money(25), money(5), money(35)); Money totalExpenses = money(0); // when Observable.fromIterable(expensesForToday).subscribe(totalExpenses::add); // then assertThat(totalExpenses).isEqualTo(money(170)); } @Test public void lazyMethodCall() { // given final AtomicInteger counter = new AtomicInteger(0); Callable<Integer> tick = counter::incrementAndGet; AtomicInteger firstTick = new AtomicInteger(0); AtomicInteger secondTick = new AtomicInteger(0); AtomicInteger thirdTick = new AtomicInteger(0); // when Observable<Integer> observable = Observable.fromCallable(tick); observable.subscribe(firstTick::set); observable.subscribe(secondTick::set); observable.subscribe(thirdTick::set); // then assertThat(firstTick.get()).isEqualTo(1); assertThat(secondTick.get()).isEqualTo(2); assertThat(thirdTick.get()).isEqualTo(3); } @Test public void fromFuture() { // given Future<Integer> fibonacciComputation = new FibonacciNumberService().countNthFibonacciNumber(20); AtomicInteger fibonacciNumber = new AtomicInteger(0); // when Observable.fromFuture(fibonacciComputation).subscribe(fibonacciNumber::set); // then assertThat(fibonacciNumber.get()).isEqualTo(6765); } @Test public void orderedSequenceOfConsecutiveNumbers() { // given List<Integer> sequence = new ArrayList<>(10); // when Observable.range(0, 10).subscribe(sequence::add); // then assertThat(sequence.size()).isEqualTo(10); assertThat(sequence.get(0)).isEqualTo(0); assertThat(sequence.get(sequence.size() - 1)).isEqualTo(9); } @Test public void defer() { // given AtomicInteger firstResult = new AtomicInteger(0); AtomicInteger secondResult = new AtomicInteger(0); AtomicInteger thirdResult = new AtomicInteger(0); AtomicInteger value = new AtomicInteger(1); Observable<Integer> deferredObservable = Observable.defer(() -> Observable.just(value.get())); // when value.set(10); deferredObservable.subscribe(firstResult::set); value.set(100); deferredObservable.subscribe(secondResult::set); value.set(1000); deferredObservable.subscribe(thirdResult::set); // then assertThat(firstResult.get()).isEqualTo(10); assertThat(secondResult.get()).isEqualTo(100); assertThat(thirdResult.get()).isEqualTo(1000); } private Money money(long value) { return new Money(value); } }
defer is quite similar to fromCallable, so defer example is moved closer to fromCallable
src/test/java/pl/mprzybylak/presentation/rxjavaquick/CreateObservableTest.java
defer is quite similar to fromCallable, so defer example is moved closer to fromCallable
<ide><path>rc/test/java/pl/mprzybylak/presentation/rxjavaquick/CreateObservableTest.java <ide> } <ide> <ide> @Test <add> public void lazyObservableCreation() { <add> <add> // given <add> AtomicInteger firstResult = new AtomicInteger(0); <add> AtomicInteger secondResult = new AtomicInteger(0); <add> AtomicInteger thirdResult = new AtomicInteger(0); <add> <add> AtomicInteger value = new AtomicInteger(1); <add> Observable<Integer> deferredObservable = Observable.defer(() -> Observable.just(value.get())); <add> <add> // when <add> value.set(10); <add> deferredObservable.subscribe(firstResult::set); <add> <add> value.set(100); <add> deferredObservable.subscribe(secondResult::set); <add> <add> value.set(1000); <add> deferredObservable.subscribe(thirdResult::set); <add> <add> // then <add> assertThat(firstResult.get()).isEqualTo(10); <add> assertThat(secondResult.get()).isEqualTo(100); <add> assertThat(thirdResult.get()).isEqualTo(1000); <add> } <add> <add> @Test <ide> public void fromFuture() { <ide> <ide> // given <ide> assertThat(sequence.get(sequence.size() - 1)).isEqualTo(9); <ide> } <ide> <del> <del> @Test <del> public void defer() { <del> <del> // given <del> AtomicInteger firstResult = new AtomicInteger(0); <del> AtomicInteger secondResult = new AtomicInteger(0); <del> AtomicInteger thirdResult = new AtomicInteger(0); <del> <del> AtomicInteger value = new AtomicInteger(1); <del> Observable<Integer> deferredObservable = Observable.defer(() -> Observable.just(value.get())); <del> <del> // when <del> value.set(10); <del> deferredObservable.subscribe(firstResult::set); <del> <del> value.set(100); <del> deferredObservable.subscribe(secondResult::set); <del> <del> value.set(1000); <del> deferredObservable.subscribe(thirdResult::set); <del> <del> // then <del> assertThat(firstResult.get()).isEqualTo(10); <del> assertThat(secondResult.get()).isEqualTo(100); <del> assertThat(thirdResult.get()).isEqualTo(1000); <del> } <del> <ide> private Money money(long value) { <ide> return new Money(value); <ide> }
Java
apache-2.0
3b24ea59e3452e0d86a958919d323fca4c4e33c4
0
SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base
/* * Copyright 2021, 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.protobuf; import com.google.common.base.Converter; import com.google.protobuf.Duration; import com.google.protobuf.util.Durations; import io.spine.string.Stringifiers; import javax.annotation.Nullable; import java.io.Serializable; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.protobuf.util.Durations.compare; import static com.google.protobuf.util.Durations.fromMillis; import static com.google.protobuf.util.Durations.fromNanos; import static com.google.protobuf.util.Durations.fromSeconds; import static com.google.protobuf.util.Durations.toMillis; import static java.util.Objects.requireNonNull; /** * Utility class for working with durations in addition to those available from the * {@link com.google.protobuf.util.Durations Durations} class in the Protobuf Util library. * * <p>Use {@code import static io.spine.protobuf.Durations2.*} for compact initialization * like this: * <pre> * {@code * Duration d = add(hours(2), minutes(30)); * } * </pre> * * @see com.google.protobuf.util.Durations Durations */ @SuppressWarnings({"UtilityClass", "ClassWithTooManyMethods"}) public final class Durations2 { public static final Duration ZERO = fromMillis(0L); /** Prevent instantiation of this utility class. */ private Durations2() { } /** * Obtains an instance of {@code Duration} representing the passed number of minutes. * * @deprecated please use {@link Durations#fromMinutes(long)}. */ @Deprecated public static Duration fromMinutes(long minutes) { return Durations.fromMinutes(minutes); } /** * Obtains an instance of {@code Duration} representing the passed number of hours. * * @deprecated please use {@link Durations#fromHours(long)}. */ @Deprecated public static Duration fromHours(long hours) { return Durations.fromHours(hours); } /* * Methods for brief computations with Durations like * add(hours(2), minutes(30)); ******************************************************/ /** * Obtains an instance of {@code Duration} representing the passed number of nanoseconds. * * @param nanos * the number of nanoseconds, positive or negative * @return a non-null {@code Duration} */ public static Duration nanos(long nanos) { return fromNanos(nanos); } /** * Obtains an instance of {@code Duration} representing the passed number of milliseconds. * * @param milliseconds * the number of milliseconds, positive or negative * @return a non-null {@code Duration} */ public static Duration milliseconds(long milliseconds) { return fromMillis(milliseconds); } /** * Obtains an instance of {@code Duration} representing the passed number of seconds. * * @param seconds * the number of seconds, positive or negative * @return a non-null {@code Duration} */ public static Duration seconds(long seconds) { return fromSeconds(seconds); } /** * This method allows for more compact code of creation of * {@code Duration} instance with minutes. */ public static Duration minutes(long minutes) { return Durations.fromMinutes(minutes); } /** * This method allows for more compact code of creation of * {@code Duration} instance with hours. */ public static Duration hours(long hours) { return Durations.fromHours(hours); } /** * Adds two durations one of which or both can be {@code null}. * * <p>This method supplements * the {@linkplain com.google.protobuf.util.Durations#add(Duration, Duration) utility} from * Protobuf Utils for accepting {@code null}s. * * @param d1 * a duration to add, could be {@code null} * @param d2 * another duration to add, could be {@code null} * @return <ul> * <li>sum of two durations if both of them are {@code non-null} * <li>another {@code non-null} value, if one is {@code null} * <li>{@link #ZERO} if both values are {@code null} * </ul> * @see com.google.protobuf.util.Durations#add(Duration, Duration) */ public static Duration add(@Nullable Duration d1, @Nullable Duration d2) { if (d1 == null && d2 == null) { return ZERO; } if (d1 == null) { return d2; } if (d2 == null) { return d1; } Duration result = Durations.add(d1, d2); return result; } /** * This method allows for more compact code of creation of * {@code Duration} instance with hours and minutes. */ public static Duration hoursAndMinutes(long hours, long minutes) { Duration result = add(hours(hours), minutes(minutes)); return result; } /** * Convert a duration to the number of nanoseconds. * * @deprecated please use {@link Durations#toNanos(Duration)}. */ @Deprecated public static long toNanos(Duration duration) { return Durations.toNanos(duration); } /** * Convert a duration to the number of seconds. * * @deprecated please use {@link Durations#toSeconds(Duration)}. */ @Deprecated public static long toSeconds(Duration duration) { return Durations.toSeconds(duration); } /** * Converts passed duration to long value of minutes. * * @deprecated please use {@link Durations#toMinutes(Duration)}. */ @Deprecated public static long toMinutes(Duration duration) { return Durations.toMinutes(duration); } /** * Returns the number of hours in the passed duration. * * @deprecated please use {@link Durations#toHours(Duration)}. */ @Deprecated public static long getHours(Duration value) { return Durations.toHours(value); } /** * Returns the only remainder of minutes from the passed duration subtracting * the amount of full hours. * * @deprecated please use {@code Durations.toMinutes(value) % 60}. */ @Deprecated public static int getMinutes(Duration value) { checkNotNull(value); long allMinutes = Durations.toMinutes(value); @SuppressWarnings("MagicNumber") // not that magic. int minutesPerHour = 60; long remainder = allMinutes % minutesPerHour; int result = Long.valueOf(remainder) .intValue(); return result; } /** * Returns {@code true} of the passed value is greater or equal zero, * {@code false} otherwise. */ public static boolean isPositiveOrZero(Duration value) { checkNotNull(value); long millis = toMillis(value); boolean result = millis >= 0; return result; } /** * Returns {@code true} if the passed value is greater than zero, * {@code false} otherwise. */ public static boolean isPositive(Duration value) { checkNotNull(value); boolean secondsPositive = value.getSeconds() > 0; boolean nanosPositive = value.getNanos() > 0; boolean result = secondsPositive || nanosPositive; return result; } /** Returns {@code true} if the passed value is zero, {@code false} otherwise. */ public static boolean isZero(Duration value) { checkNotNull(value); boolean noSeconds = value.getSeconds() == 0; boolean noNanos = value.getNanos() == 0; boolean result = noSeconds && noNanos; return result; } /** * Returns {@code true} if the first argument is greater than the second, * {@code false} otherwise. */ public static boolean isGreaterThan(Duration value, Duration another) { boolean result = compare(value, another) > 0; return result; } /** * Returns {@code true} if the first argument is less than the second, * {@code false} otherwise. */ public static boolean isLessThan(Duration value, Duration another) { boolean result = compare(value, another) < 0; return result; } /** * Returns {@code true} if the passed duration is negative, {@code false} otherwise. * * @deprecated please use {@link Durations#isNegative(Duration)}. */ @Deprecated public static boolean isNegative(Duration value) { return Durations.isNegative(value); } /** * Converts the passed Java Time value. */ public static Duration of(java.time.Duration value) { checkNotNull(value); Duration result = converter().convert(value); return requireNonNull(result); } /** * Converts the passed value to Java Time value. */ public static java.time.Duration toJavaTime(Duration value) { checkNotNull(value); java.time.Duration result = converter().reverse() .convert(value); return requireNonNull(result); } /** * Parses the string with a duration. * * <p>Unlike {@link com.google.protobuf.util.Durations#parse(String) its Protobuf counterpart}, * this method does not throw a checked exception. * * @throws IllegalArgumentException * if the string is not of required format */ public static Duration parse(String str) { checkNotNull(str); Duration result = Stringifiers.forDuration() .reverse() .convert(str); return requireNonNull(result); } /** * Obtains the instance of Java Time converter. */ public static Converter<java.time.Duration, Duration> converter() { return JtConverter.INSTANCE; } /** * Converts from Java Time {@code Duration} to Protobuf {@code Duration} and back. */ private static final class JtConverter extends Converter<java.time.Duration, Duration> implements Serializable { private static final long serialVersionUID = 0L; private static final JtConverter INSTANCE = new JtConverter(); @Override protected Duration doForward(java.time.Duration duration) { return Duration.newBuilder() .setSeconds(duration.getSeconds()) .setNanos(duration.getNano()) .build(); } @Override protected java.time.Duration doBackward(Duration duration) { return java.time.Duration.ofSeconds(duration.getSeconds(), duration.getNanos()); } @Override public String toString() { return "Durations2.converter()"; } private Object readResolve() { return INSTANCE; } } }
base/src/main/java/io/spine/protobuf/Durations2.java
/* * Copyright 2021, 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.protobuf; import com.google.common.base.Converter; import com.google.protobuf.Duration; import com.google.protobuf.util.Durations; import io.spine.string.Stringifiers; import javax.annotation.Nullable; import java.io.Serializable; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.protobuf.util.Durations.compare; import static com.google.protobuf.util.Durations.fromMillis; import static com.google.protobuf.util.Durations.fromNanos; import static com.google.protobuf.util.Durations.fromSeconds; import static com.google.protobuf.util.Durations.toMillis; import static java.util.Objects.requireNonNull; /** * Utility class for working with durations in addition to those available from the * {@link com.google.protobuf.util.Durations Durations} class in the Protobuf Util library. * * <p>Use {@code import static io.spine.protobuf.Durations2.*} for compact initialization * like this: * <pre> * {@code * Duration d = add(hours(2), minutes(30)); * } * </pre> * * @see com.google.protobuf.util.Durations Durations */ @SuppressWarnings({"UtilityClass", "ClassWithTooManyMethods"}) public final class Durations2 { public static final Duration ZERO = fromMillis(0L); /** The count of minutes in one hour. */ @SuppressWarnings("NumericCastThatLosesPrecision") private static final int MINUTES_PER_HOUR = (int) TimeUnit.HOURS.toMinutes(1); /** Prevent instantiation of this utility class. */ private Durations2() { } /** * Obtains an instance of {@code Duration} representing the passed number of minutes. * * @deprecated please use {@link Durations#fromMinutes(long)}. */ @Deprecated public static Duration fromMinutes(long minutes) { return Durations.fromMinutes(minutes); } /** * Obtains an instance of {@code Duration} representing the passed number of hours. * * @deprecated please use {@link Durations#fromHours(long)}. */ @Deprecated public static Duration fromHours(long hours) { return Durations.fromHours(hours); } /* * Methods for brief computations with Durations like * add(hours(2), minutes(30)); ******************************************************/ /** * Obtains an instance of {@code Duration} representing the passed number of nanoseconds. * * @param nanos * the number of nanoseconds, positive or negative * @return a non-null {@code Duration} */ public static Duration nanos(long nanos) { return fromNanos(nanos); } /** * Obtains an instance of {@code Duration} representing the passed number of milliseconds. * * @param milliseconds * the number of milliseconds, positive or negative * @return a non-null {@code Duration} */ public static Duration milliseconds(long milliseconds) { return fromMillis(milliseconds); } /** * Obtains an instance of {@code Duration} representing the passed number of seconds. * * @param seconds * the number of seconds, positive or negative * @return a non-null {@code Duration} */ public static Duration seconds(long seconds) { return fromSeconds(seconds); } /** * This method allows for more compact code of creation of * {@code Duration} instance with minutes. */ public static Duration minutes(long minutes) { return Durations.fromMinutes(minutes); } /** * This method allows for more compact code of creation of * {@code Duration} instance with hours. */ public static Duration hours(long hours) { return Durations.fromHours(hours); } /** * Adds two durations one of which or both can be {@code null}. * * <p>This method supplements * the {@linkplain com.google.protobuf.util.Durations#add(Duration, Duration) utility} from * Protobuf Utils for accepting {@code null}s. * * @param d1 * a duration to add, could be {@code null} * @param d2 * another duration to add, could be {@code null} * @return <ul> * <li>sum of two durations if both of them are {@code non-null} * <li>another {@code non-null} value, if one is {@code null} * <li>{@link #ZERO} if both values are {@code null} * </ul> * @see com.google.protobuf.util.Durations#add(Duration, Duration) */ public static Duration add(@Nullable Duration d1, @Nullable Duration d2) { if (d1 == null && d2 == null) { return ZERO; } if (d1 == null) { return d2; } if (d2 == null) { return d1; } Duration result = Durations.add(d1, d2); return result; } /** * This method allows for more compact code of creation of * {@code Duration} instance with hours and minutes. */ public static Duration hoursAndMinutes(long hours, long minutes) { Duration result = add(hours(hours), minutes(minutes)); return result; } /** * Convert a duration to the number of nanoseconds. * * @deprecated please use {@link Durations#toNanos(Duration)}. */ @Deprecated public static long toNanos(Duration duration) { return Durations.toNanos(duration); } /** * Convert a duration to the number of seconds. * * @deprecated please use {@link Durations#toSeconds(Duration)}. */ @Deprecated public static long toSeconds(Duration duration) { return Durations.toSeconds(duration); } /** * Converts passed duration to long value of minutes. * * @deprecated please use {@link Durations#toMinutes(Duration)}. */ @Deprecated public static long toMinutes(Duration duration) { return Durations.toMinutes(duration); } /** * Returns the number of hours in the passed duration. * * @deprecated please use {@link Durations#toHours(Duration)}. */ @Deprecated public static long getHours(Duration value) { return Durations.toHours(value); } /** * Returns the only remainder of minutes from the passed duration subtracting * the amount of full hours. * * @deprecated please use {@code Durations.toMinutes(value) % 60}. */ @Deprecated public static int getMinutes(Duration value) { checkNotNull(value); long allMinutes = Durations.toMinutes(value); long remainder = allMinutes % MINUTES_PER_HOUR; int result = Long.valueOf(remainder) .intValue(); return result; } /** * Returns {@code true} of the passed value is greater or equal zero, * {@code false} otherwise. */ public static boolean isPositiveOrZero(Duration value) { checkNotNull(value); long millis = toMillis(value); boolean result = millis >= 0; return result; } /** * Returns {@code true} if the passed value is greater than zero, * {@code false} otherwise. */ public static boolean isPositive(Duration value) { checkNotNull(value); boolean secondsPositive = value.getSeconds() > 0; boolean nanosPositive = value.getNanos() > 0; boolean result = secondsPositive || nanosPositive; return result; } /** Returns {@code true} if the passed value is zero, {@code false} otherwise. */ public static boolean isZero(Duration value) { checkNotNull(value); boolean noSeconds = value.getSeconds() == 0; boolean noNanos = value.getNanos() == 0; boolean result = noSeconds && noNanos; return result; } /** * Returns {@code true} if the first argument is greater than the second, * {@code false} otherwise. */ public static boolean isGreaterThan(Duration value, Duration another) { boolean result = compare(value, another) > 0; return result; } /** * Returns {@code true} if the first argument is less than the second, * {@code false} otherwise. */ public static boolean isLessThan(Duration value, Duration another) { boolean result = compare(value, another) < 0; return result; } /** * Returns {@code true} if the passed duration is negative, {@code false} otherwise. * * @deprecated please use {@link Durations#isNegative(Duration)}. */ @Deprecated public static boolean isNegative(Duration value) { return Durations.isNegative(value); } /** * Converts the passed Java Time value. */ public static Duration of(java.time.Duration value) { checkNotNull(value); Duration result = converter().convert(value); return requireNonNull(result); } /** * Converts the passed value to Java Time value. */ public static java.time.Duration toJavaTime(Duration value) { checkNotNull(value); java.time.Duration result = converter().reverse() .convert(value); return requireNonNull(result); } /** * Parses the string with a duration. * * <p>Unlike {@link com.google.protobuf.util.Durations#parse(String) its Protobuf counterpart}, * this method does not throw a checked exception. * * @throws IllegalArgumentException * if the string is not of required format */ public static Duration parse(String str) { checkNotNull(str); Duration result = Stringifiers.forDuration() .reverse() .convert(str); return requireNonNull(result); } /** * Obtains the instance of Java Time converter. */ public static Converter<java.time.Duration, Duration> converter() { return JtConverter.INSTANCE; } /** * Converts from Java Time {@code Duration} to Protobuf {@code Duration} and back. */ private static final class JtConverter extends Converter<java.time.Duration, Duration> implements Serializable { private static final long serialVersionUID = 0L; private static final JtConverter INSTANCE = new JtConverter(); @Override protected Duration doForward(java.time.Duration duration) { return Duration.newBuilder() .setSeconds(duration.getSeconds()) .setNanos(duration.getNano()) .build(); } @Override protected java.time.Duration doBackward(Duration duration) { return java.time.Duration.ofSeconds(duration.getSeconds(), duration.getNanos()); } @Override public String toString() { return "Durations2.converter()"; } private Object readResolve() { return INSTANCE; } } }
Remove redundant constant
base/src/main/java/io/spine/protobuf/Durations2.java
Remove redundant constant
<ide><path>ase/src/main/java/io/spine/protobuf/Durations2.java <ide> <ide> import javax.annotation.Nullable; <ide> import java.io.Serializable; <del>import java.util.concurrent.TimeUnit; <ide> <ide> import static com.google.common.base.Preconditions.checkNotNull; <ide> import static com.google.protobuf.util.Durations.compare; <ide> public final class Durations2 { <ide> <ide> public static final Duration ZERO = fromMillis(0L); <del> <del> /** The count of minutes in one hour. */ <del> @SuppressWarnings("NumericCastThatLosesPrecision") <del> private static final int MINUTES_PER_HOUR = (int) TimeUnit.HOURS.toMinutes(1); <ide> <ide> /** Prevent instantiation of this utility class. */ <ide> private Durations2() { <ide> public static int getMinutes(Duration value) { <ide> checkNotNull(value); <ide> long allMinutes = Durations.toMinutes(value); <del> long remainder = allMinutes % MINUTES_PER_HOUR; <add> @SuppressWarnings("MagicNumber") // not that magic. <add> int minutesPerHour = 60; <add> long remainder = allMinutes % minutesPerHour; <ide> int result = Long.valueOf(remainder) <ide> .intValue(); <ide> return result;
Java
apache-2.0
708b7e7a33536922f67ccc381efebbc03e93a9af
0
appNG/appng,appNG/appng,appNG/appng
/* * Copyright 2011-2021 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.appng.core.controller.rest.openapi; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBException; import org.apache.commons.lang3.StringUtils; import org.appng.api.Environment; import org.appng.api.InvalidConfigurationException; import org.appng.api.ProcessingException; import org.appng.api.Request; import org.appng.api.SiteProperties; import org.appng.api.model.Application; import org.appng.api.model.Site; import org.appng.api.support.ApplicationRequest; import org.appng.core.model.ApplicationProvider; import org.appng.openapi.model.ActionLink; import org.appng.openapi.model.Datasource; import org.appng.openapi.model.Field; import org.appng.openapi.model.FieldType; import org.appng.openapi.model.FieldValue; import org.appng.openapi.model.Filter; import org.appng.openapi.model.Icon; import org.appng.openapi.model.Item; import org.appng.openapi.model.Link; import org.appng.openapi.model.Link.TypeEnum; import org.appng.openapi.model.OptionType; import org.appng.openapi.model.Options; import org.appng.openapi.model.Page; import org.appng.openapi.model.PageSize; import org.appng.openapi.model.Parameter; import org.appng.openapi.model.Sort.OrderEnum; import org.appng.openapi.model.User; import org.appng.xml.platform.Data; import org.appng.xml.platform.Datafield; import org.appng.xml.platform.FieldDef; import org.appng.xml.platform.Label; import org.appng.xml.platform.Linkmode; import org.appng.xml.platform.MetaData; import org.appng.xml.platform.Option; import org.appng.xml.platform.PanelLocation; import org.appng.xml.platform.Params; import org.appng.xml.platform.Result; import org.appng.xml.platform.Resultset; import org.appng.xml.platform.Selection; import org.appng.xml.platform.SelectionGroup; import org.appng.xml.platform.Sort; import org.appng.xml.platform.Validation; import org.slf4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import lombok.extern.slf4j.Slf4j; @Slf4j @RestController abstract class OpenApiDataSource extends OpenApiOperation { public OpenApiDataSource(Site site, Application application, Request request, MessageSource messageSource, boolean supportPathParameters) throws JAXBException { super(site, application, request, messageSource, supportPathParameters); } // @formatter:off @GetMapping( path = { "/openapi/datasource/{id}", "/openapi/datasource/{id}/{pathVar1}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}/{pathVar3}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}/{pathVar3}/{pathVar4}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}/{pathVar3}/{pathVar4}/{pathVar5}" } ) // @formatter:on public ResponseEntity<Datasource> getDataSource(@PathVariable(name = "id") String dataSourceId, @PathVariable(required = false) Map<String, String> pathVariables, Environment environment, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ProcessingException, JAXBException, InvalidConfigurationException, org.appng.api.ProcessingException { ApplicationProvider applicationProvider = (ApplicationProvider) application; if (supportPathParameters) { org.appng.xml.platform.Datasource originalDatasource = applicationProvider.getApplicationConfig() .getDatasource(dataSourceId); if (null == originalDatasource) { LOGGER.debug("Datasource {} not found on application {} of site {}", dataSourceId, application.getName(), site.getName()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } applyPathParameters(pathVariables, originalDatasource.getConfig(), request); } org.appng.xml.platform.Datasource processedDataSource = applicationProvider.processDataSource( httpServletResponse, false, (ApplicationRequest) request, dataSourceId, marshallService); if (null == processedDataSource) { LOGGER.debug("Datasource {} not found on application {} of site {}", dataSourceId, application.getName(), site.getName()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if (httpServletResponse.getStatus() != HttpStatus.OK.value()) { LOGGER.debug("Datasource {} on application {} of site {} returned status {}", processedDataSource.getId(), application.getName(), site.getName(), httpServletResponse.getStatus()); return new ResponseEntity<>(HttpStatus.valueOf(httpServletResponse.getStatus())); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Processed datasource: {}", marshallService.marshallNonRoot(processedDataSource)); } Datasource datasource = transformDataSource(environment, httpServletResponse, applicationProvider, processedDataSource); return new ResponseEntity<Datasource>(datasource, HttpStatus.OK); } protected Datasource transformDataSource(Environment environment, HttpServletResponse httpServletResponse, ApplicationProvider applicationProvider, org.appng.xml.platform.Datasource processedDataSource) { MetaData metaData = processedDataSource.getConfig().getMetaData(); addValidationRules(metaData); Datasource datasource = new Datasource(); String id = processedDataSource.getId(); datasource.setId(id); User user = getUser(environment); Label title = processedDataSource.getConfig().getTitle(); if (null != title) { datasource.setTitle(title.getValue()); } datasource.setUser(user); datasource.setParameters(getParameters(processedDataSource.getConfig().getParams(), false)); datasource.setPermissions(getPermissions(processedDataSource.getConfig().getPermissions())); StringBuilder self = getSelf("/datasource/" + id); boolean hasQueryParams = appendParams(processedDataSource.getConfig().getParams(), self); datasource.setSelf(self.toString()); processedDataSource.getConfig().getLinkpanel().stream() .filter(lp -> !lp.getLocation().equals(PanelLocation.INLINE)).forEach(lp -> { lp.getLinks().forEach(l -> { datasource.addLinksItem(getLink(l)); }); }); processedDataSource.getConfig().getMetaData().getFields().forEach(f -> { if (!org.appng.xml.platform.FieldType.LINKPANEL.equals(f.getType())) { datasource.addFieldsItem(getField(self.toString(), id, f, hasQueryParams)); } }); Data data = processedDataSource.getData(); if (null != data) { String filterResetLink = addFilters(processedDataSource, datasource, hasQueryParams); datasource.setFilterResetPath(self.toString() + filterResetLink); Resultset resultset = data.getResultset(); if (null != resultset) { Page page = new Page(); page.setNumber(resultset.getChunk()); page.setIsFirst(page.getNumber() == resultset.getFirstchunk()); page.setIsLast(page.getNumber() == resultset.getLastchunk()); page.setSize(resultset.getChunksize()); page.setTotalItems(resultset.getHits()); page.setTotalPages(resultset.getLastchunk() + 1); page.setFirst(getPageLink(hasQueryParams, self.toString(), id, page.getSize(), 0)); if (!Boolean.TRUE.equals(page.getIsFirst())) { page.setPrevious( getPageLink(hasQueryParams, self.toString(), id, page.getSize(), page.getNumber() - 1)); } if (!Boolean.TRUE.equals(page.getIsLast())) { page.setNext( getPageLink(hasQueryParams, self.toString(), id, page.getSize(), page.getNumber() + 1)); } page.setLast( getPageLink(hasQueryParams, self.toString(), id, page.getSize(), resultset.getLastchunk())); resultset.getResults().forEach(r -> { datasource.addItemsItem(getItem(null, r, metaData, getBindClass(metaData))); }); int[] pageSizes = { 5, 10, 25, 50 }; for (int size : pageSizes) { PageSize pageSize = new PageSize(); pageSize.setSize(size); pageSize.setPath(getPageLink(hasQueryParams, self.toString(), id, size)); page.addPageSizesItem(pageSize); } datasource.setPage(page); } else { datasource.setItem(getItem(data.getSelections(), data.getResult(), metaData, getBindClass(metaData))); } } return datasource; } protected String getPageLink(boolean hasQueryParams, String self, String id, int pageSize, int page) { return getPageLink(hasQueryParams, self, id, pageSize) + ";page:" + page; } protected String getPageLink(boolean hasQueryParams, String self, String id, int pageSize) { return self.toString() + (hasQueryParams ? "&" : "?") + "sort" + StringUtils.capitalize(id) + "=pageSize:" + pageSize; } private String addFilters(org.appng.xml.platform.Datasource processedDataSource, Datasource datasource, boolean hasQueryParams) { StringBuilder filterResetLink = new StringBuilder(hasQueryParams ? "&" : "?"); List<SelectionGroup> selectionGroups = processedDataSource.getData().getSelectionGroups(); if (null != selectionGroups) { selectionGroups.forEach(sg -> { AtomicBoolean istFirst = new AtomicBoolean(!hasQueryParams); sg.getSelections().forEach(s -> { Filter filter = new Filter(); filter.setLabel(s.getTitle().getValue()); filter.setName(s.getId()); filter.setType(OptionType.valueOf(s.getType().name())); filter.setOptions(new Options()); filter.getOptions().setMultiple(filter.getType().equals(OptionType.CHECKBOX) || filter.getType().equals(OptionType.SELECT_MULTIPLE)); s.getOptions().forEach(o -> { filter.getOptions().addEntriesItem(getOption(s.getId(), o, Collections.emptyList())); }); datasource.addFiltersItem(filter); filterResetLink.append((istFirst.getAndSet(false) ? "?" : "&") + s.getId() + "="); }); }); } return filterResetLink.toString(); } protected Field getField(String self, String dataSourceId, FieldDef f, boolean hasQueryParams) { Field field = new Field(); field.setName(f.getName()); if (null != f.getLabel()) { field.setLabel(f.getLabel().getValue()); } field.setFieldType(FieldType.valueOf(f.getType().name())); field.setFormat(f.getFormat()); Sort s = f.getSort(); if (s != null) { org.appng.openapi.model.Sort sort = new org.appng.openapi.model.Sort(); if (null != s.getPrio()) { sort.setPrio(s.getPrio()); } if (null != s.getOrder()) { sort.setOrder(OrderEnum.fromValue(s.getOrder().name().toLowerCase())); } String sortParam = (hasQueryParams ? "&" : "?") + "sort" + StringUtils.capitalize(dataSourceId) + "=" + f.getBinding(); sort.setPathDesc(self + sortParam + ":desc"); sort.setPathAsc(self + sortParam + ":asc"); field.setSort(sort); } List<FieldDef> childFields = f.getFields(); if (null != childFields) { field.setFields(childFields.stream().map(fieldDef -> getField(self, dataSourceId, fieldDef, hasQueryParams)) .collect(Collectors.toMap(Field::getName, Function.identity()))); } Validation validation = f.getValidation(); if (null != validation) { validation.getRules().stream().forEach(r -> field.addRulesItem(getRule(r))); } return field; } protected Item getItem(List<Selection> selections, Result r, MetaData metaData, Class<?> bindClass) { Item item = new Item(); item.setFields(new HashMap<>()); item.setSelected(Boolean.TRUE.equals(r.isSelected())); r.getFields().forEach(f -> { Optional<FieldDef> fieldDef = metaData.getFields().stream().filter(mf -> mf.getName().equals(f.getName())) .findFirst(); FieldValue fieldValue = getFieldValue(f, fieldDef, bindClass); if (null != fieldValue && isSelectionType(fieldDef.get().getType()) && null != selections) { Selection selection = selections.parallelStream() .filter(s -> s.getId().equals(fieldDef.get().getName())).findFirst().orElse(null); List<FieldValue> collectedValues = new ArrayList<>(); if (null != selection) { List<Option> options = selection.getOptions(); collectedValues.addAll(collectSelectedOptions(options)); selection.getOptionGroups().forEach(g -> { collectedValues.addAll(collectSelectedOptions(g.getOptions())); }); if (collectedValues.size() == 1) { fieldValue.setValue(collectedValues.get(0).getValue()); } else { fieldValue.setValues(new HashMap<>()); for (FieldValue value : collectedValues) { fieldValue.getValues().put(value.getName(), value); } } } } item.getFields().put(fieldValue.getName(), fieldValue); }); r.getLinkpanel().forEach(lp -> { lp.getLinks().forEach(l -> { item.addLinksItem(getLink(l)); }); }); return item; } private List<FieldValue> collectSelectedOptions(List<Option> options) { return options.stream().filter(o -> Boolean.TRUE.equals(o.isSelected())).map(o -> { FieldValue childValue = new FieldValue(); childValue.setValue(o.getValue()); return childValue; }).collect(Collectors.toList()); } protected FieldValue getFieldValue(Datafield data, Optional<FieldDef> fieldDef, Class<?> bindClass) { if (fieldDef.isPresent()) { FieldValue fv = getFieldValue(data, fieldDef.get(), BeanUtils.findPropertyType(fieldDef.get().getBinding(), bindClass)); List<Datafield> childDataFields = data.getFields(); if (!childDataFields.isEmpty()) { final AtomicInteger i = new AtomicInteger(0); fv.setValues(new HashMap<>()); for (Datafield childData : childDataFields) { Optional<FieldDef> childField = getChildField(fieldDef.get(), data, i.get(), childData); FieldValue childValue = getFieldValue(childData, childField, bindClass); fv.getValues().put(childValue.getName(), childValue); i.incrementAndGet(); } } return fv; } FieldValue fv = new FieldValue(); fv.setName(data.getName()); return fv; } protected FieldValue getFieldValue(Datafield data, FieldDef field, Class<?> type) { FieldValue fv = new FieldValue(); fv.setName(data.getName()); data.getIcons().forEach(i -> { Icon icon = new Icon(); icon.setName(i.getContent()); icon.setLabel(i.getLabel()); fv.addIconsItem(icon); }); fv.setValue(getObjectValue(data, field, type, Collections.emptyList())); if (null != fv.getValue() && !org.appng.xml.platform.FieldType.DATE.equals(field.getType()) && StringUtils.isNotBlank(field.getFormat())) { fv.setFormattedValue(data.getValue()); } return fv; } protected Link getLink(org.appng.xml.platform.Linkable l) { Link link = null; if (l instanceof org.appng.xml.platform.Link) { link = new Link(); org.appng.xml.platform.Link ll = (org.appng.xml.platform.Link) l; link.setId(ll.getId()); link.setType(LINK_MAPPING.get(ll.getMode())); if (Linkmode.INTERN.equals(ll.getMode())) { String managerPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); String completePath = String.format("%s/%s/%s%s", managerPath, site.getName(), application.getName(), ll.getTarget()); link.setTarget(completePath); } else { link.setTarget(ll.getTarget()); } } else if (l instanceof org.appng.xml.platform.OpenapiAction) { ActionLink action = new ActionLink(); org.appng.xml.platform.OpenapiAction al = (org.appng.xml.platform.OpenapiAction) l; action.setId(al.getId()); Params params = ((org.appng.xml.platform.OpenapiAction) l).getParams(); if (null != params) { List<Parameter> parameters = new ArrayList<>(); params.getParam().forEach(p -> { Parameter param = new Parameter(); param.setName(p.getName()); param.setValue(p.getValue()); parameters.add(param); }); action.setParameters(parameters); } action.setTarget(al.getTarget()); action.setEventId(al.getEventId()); action.setInteractive(al.isInteractive()); action.setType(TypeEnum.ACTION); link = action; } link.setLabel(l.getLabel().getValue()); link.setIcon(l.getIcon().getContent()); link.setDefault(Boolean.TRUE.toString().equalsIgnoreCase(l.getDefault())); if (null != l.getConfirmation()) { link.setConfirmation(l.getConfirmation().getValue()); } return link; } protected static final Map<Linkmode, Link.TypeEnum> LINK_MAPPING = new HashMap<Linkmode, Link.TypeEnum>(); static { LINK_MAPPING.put(Linkmode.EXTERN, Link.TypeEnum.EXTERN); LINK_MAPPING.put(Linkmode.INTERN, Link.TypeEnum.PAGE); LINK_MAPPING.put(Linkmode.WEBSERVICE, Link.TypeEnum.INTERN); } Logger getLogger() { return LOGGER; } }
appng-core/src/main/java/org/appng/core/controller/rest/openapi/OpenApiDataSource.java
/* * Copyright 2011-2021 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.appng.core.controller.rest.openapi; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBException; import org.apache.commons.lang3.StringUtils; import org.appng.api.Environment; import org.appng.api.InvalidConfigurationException; import org.appng.api.ProcessingException; import org.appng.api.Request; import org.appng.api.SiteProperties; import org.appng.api.model.Application; import org.appng.api.model.Site; import org.appng.api.support.ApplicationRequest; import org.appng.core.model.ApplicationProvider; import org.appng.openapi.model.ActionLink; import org.appng.openapi.model.Datasource; import org.appng.openapi.model.Field; import org.appng.openapi.model.FieldType; import org.appng.openapi.model.FieldValue; import org.appng.openapi.model.Filter; import org.appng.openapi.model.Icon; import org.appng.openapi.model.Item; import org.appng.openapi.model.Link; import org.appng.openapi.model.Link.TypeEnum; import org.appng.openapi.model.OptionType; import org.appng.openapi.model.Options; import org.appng.openapi.model.Page; import org.appng.openapi.model.PageSize; import org.appng.openapi.model.Parameter; import org.appng.openapi.model.Sort.OrderEnum; import org.appng.openapi.model.User; import org.appng.xml.platform.Data; import org.appng.xml.platform.Datafield; import org.appng.xml.platform.FieldDef; import org.appng.xml.platform.Label; import org.appng.xml.platform.Linkmode; import org.appng.xml.platform.MetaData; import org.appng.xml.platform.Option; import org.appng.xml.platform.PanelLocation; import org.appng.xml.platform.Params; import org.appng.xml.platform.Result; import org.appng.xml.platform.Resultset; import org.appng.xml.platform.Selection; import org.appng.xml.platform.SelectionGroup; import org.appng.xml.platform.Sort; import org.appng.xml.platform.Validation; import org.slf4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import lombok.extern.slf4j.Slf4j; @Slf4j @RestController abstract class OpenApiDataSource extends OpenApiOperation { public OpenApiDataSource(Site site, Application application, Request request, MessageSource messageSource, boolean supportPathParameters) throws JAXBException { super(site, application, request, messageSource, supportPathParameters); } // @formatter:off @GetMapping( path = { "/openapi/datasource/{id}", "/openapi/datasource/{id}/{pathVar1}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}/{pathVar3}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}/{pathVar3}/{pathVar4}", "/openapi/datasource/{id}/{pathVar1}/{pathVar2}/{pathVar3}/{pathVar4}/{pathVar5}" } ) // @formatter:on public ResponseEntity<Datasource> getDataSource(@PathVariable(name = "id") String dataSourceId, @PathVariable(required = false) Map<String, String> pathVariables, Environment environment, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ProcessingException, JAXBException, InvalidConfigurationException, org.appng.api.ProcessingException { ApplicationProvider applicationProvider = (ApplicationProvider) application; if (supportPathParameters) { org.appng.xml.platform.Datasource originalDatasource = applicationProvider.getApplicationConfig() .getDatasource(dataSourceId); if (null == originalDatasource) { LOGGER.debug("Datasource {} not found on application {} of site {}", dataSourceId, application.getName(), site.getName()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } applyPathParameters(pathVariables, originalDatasource.getConfig(), request); } org.appng.xml.platform.Datasource processedDataSource = applicationProvider.processDataSource( httpServletResponse, false, (ApplicationRequest) request, dataSourceId, marshallService); if (null == processedDataSource) { LOGGER.debug("Datasource {} not found on application {} of site {}", dataSourceId, application.getName(), site.getName()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if (httpServletResponse.getStatus() != HttpStatus.OK.value()) { LOGGER.debug("Datasource {} on application {} of site {} returned status {}", processedDataSource.getId(), application.getName(), site.getName(), httpServletResponse.getStatus()); return new ResponseEntity<>(HttpStatus.valueOf(httpServletResponse.getStatus())); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Processed datasource: {}", marshallService.marshallNonRoot(processedDataSource)); } Datasource datasource = transformDataSource(environment, httpServletResponse, applicationProvider, processedDataSource); return new ResponseEntity<Datasource>(datasource, HttpStatus.OK); } protected Datasource transformDataSource(Environment environment, HttpServletResponse httpServletResponse, ApplicationProvider applicationProvider, org.appng.xml.platform.Datasource processedDataSource) { MetaData metaData = processedDataSource.getConfig().getMetaData(); addValidationRules(metaData); Datasource datasource = new Datasource(); String id = processedDataSource.getId(); datasource.setId(id); User user = getUser(environment); Label title = processedDataSource.getConfig().getTitle(); if (null != title) { datasource.setTitle(title.getValue()); } datasource.setUser(user); datasource.setParameters(getParameters(processedDataSource.getConfig().getParams(), false)); datasource.setPermissions(getPermissions(processedDataSource.getConfig().getPermissions())); StringBuilder self = getSelf("/datasource/" + id); boolean hasQueryParams = appendParams(processedDataSource.getConfig().getParams(), self); datasource.setSelf(self.toString()); processedDataSource.getConfig().getLinkpanel().stream() .filter(lp -> !lp.getLocation().equals(PanelLocation.INLINE)).forEach(lp -> { lp.getLinks().forEach(l -> { datasource.addLinksItem(getLink(l)); }); }); processedDataSource.getConfig().getMetaData().getFields().forEach(f -> { if (!org.appng.xml.platform.FieldType.LINKPANEL.equals(f.getType())) { datasource.addFieldsItem(getField(self.toString(), id, f, hasQueryParams)); } }); Data data = processedDataSource.getData(); if (null != data) { String filterResetLink = addFilters(processedDataSource, datasource, hasQueryParams); datasource.setFilterResetPath(self.toString() + filterResetLink); Resultset resultset = data.getResultset(); if (null != resultset) { Page page = new Page(); page.setNumber(resultset.getChunk()); page.setIsFirst(page.getNumber() == resultset.getFirstchunk()); page.setIsLast(page.getNumber() == resultset.getLastchunk()); page.setSize(resultset.getChunksize()); page.setTotalItems(resultset.getHits()); page.setTotalPages(resultset.getLastchunk() + 1); page.setFirst(getPageLink(hasQueryParams, self.toString(), id, page.getSize(), 0)); if (!Boolean.TRUE.equals(page.getIsFirst())) { page.setPrevious( getPageLink(hasQueryParams, self.toString(), id, page.getSize(), page.getNumber() - 1)); } if (!Boolean.TRUE.equals(page.getIsLast())) { page.setNext( getPageLink(hasQueryParams, self.toString(), id, page.getSize(), page.getNumber() + 1)); } page.setLast( getPageLink(hasQueryParams, self.toString(), id, page.getSize(), resultset.getLastchunk())); resultset.getResults().forEach(r -> { datasource.addItemsItem(getItem(null, r, metaData, getBindClass(metaData))); }); int[] pageSizes = { 5, 10, 25, 50 }; for (int size : pageSizes) { PageSize pageSize = new PageSize(); pageSize.setSize(size); pageSize.setPath(getPageLink(hasQueryParams, self.toString(), id, size)); page.addPageSizesItem(pageSize); } datasource.setPage(page); } else { datasource.setItem(getItem(data.getSelections(), data.getResult(), metaData, getBindClass(metaData))); } } return datasource; } protected String getPageLink(boolean hasQueryParams, String self, String id, int pageSize, int page) { return getPageLink(hasQueryParams, self, id, pageSize) + ";page:" + page; } protected String getPageLink(boolean hasQueryParams, String self, String id, int pageSize) { return self.toString() + (hasQueryParams ? "&" : "?") + "sort" + StringUtils.capitalize(id) + "=pageSize:" + pageSize; } private String addFilters(org.appng.xml.platform.Datasource processedDataSource, Datasource datasource, boolean hasQueryParams) { StringBuilder filterResetLink = new StringBuilder(hasQueryParams ? "&" : "?"); List<SelectionGroup> selectionGroups = processedDataSource.getData().getSelectionGroups(); if (null != selectionGroups) { selectionGroups.forEach(sg -> { AtomicBoolean istFirst = new AtomicBoolean(!hasQueryParams); sg.getSelections().forEach(s -> { Filter filter = new Filter(); filter.setLabel(s.getTitle().getValue()); filter.setName(s.getId()); filter.setType(OptionType.valueOf(s.getType().name())); filter.setOptions(new Options()); filter.getOptions().setMultiple(filter.getType().equals(OptionType.CHECKBOX) || filter.getType().equals(OptionType.SELECT_MULTIPLE)); s.getOptions().forEach(o -> { filter.getOptions().addEntriesItem(getOption(s.getId(), o, Collections.emptyList())); }); datasource.addFiltersItem(filter); filterResetLink.append((istFirst.getAndSet(false) ? "?" : "&") + s.getId() + "="); }); }); } return filterResetLink.toString(); } protected Field getField(String self, String dataSourceId, FieldDef f, boolean hasQueryParams) { Field field = new Field(); field.setName(f.getName()); if (null != f.getLabel()) { field.setLabel(f.getLabel().getValue()); } field.setFieldType(FieldType.valueOf(f.getType().name())); field.setFormat(f.getFormat()); Sort s = f.getSort(); if (s != null) { org.appng.openapi.model.Sort sort = new org.appng.openapi.model.Sort(); if (null != s.getPrio()) { sort.setPrio(s.getPrio()); } if (null != s.getOrder()) { sort.setOrder(OrderEnum.fromValue(s.getOrder().name().toLowerCase())); } String sortParam = (hasQueryParams ? "&" : "?") + "sort" + StringUtils.capitalize(dataSourceId) + "=" + f.getBinding(); sort.setPathDesc(self + sortParam + ":desc"); sort.setPathAsc(self + sortParam + ":asc"); field.setSort(sort); } List<FieldDef> childFields = f.getFields(); if (null != childFields) { for (FieldDef fieldDef : childFields) { Field child = getField(self, dataSourceId, fieldDef, hasQueryParams); field.getFields().put(child.getName(), child); } } Validation validation = f.getValidation(); if (null != validation) { validation.getRules().stream().forEach(r -> field.addRulesItem(getRule(r))); } return field; } protected Item getItem(List<Selection> selections, Result r, MetaData metaData, Class<?> bindClass) { Item item = new Item(); item.setFields(new HashMap<>()); item.setSelected(Boolean.TRUE.equals(r.isSelected())); r.getFields().forEach(f -> { Optional<FieldDef> fieldDef = metaData.getFields().stream().filter(mf -> mf.getName().equals(f.getName())) .findFirst(); FieldValue fieldValue = getFieldValue(f, fieldDef, bindClass); if (null != fieldValue && isSelectionType(fieldDef.get().getType()) && null != selections) { Selection selection = selections.parallelStream() .filter(s -> s.getId().equals(fieldDef.get().getName())).findFirst().orElse(null); List<FieldValue> collectedValues = new ArrayList<>(); if (null != selection) { List<Option> options = selection.getOptions(); collectedValues.addAll(collectSelectedOptions(options)); selection.getOptionGroups().forEach(g -> { collectedValues.addAll(collectSelectedOptions(g.getOptions())); }); if (collectedValues.size() == 1) { fieldValue.setValue(collectedValues.get(0).getValue()); } else { for (FieldValue value : collectedValues) { fieldValue.getValues().put(value.getName(), value); } } } } item.getFields().put(fieldValue.getName(), fieldValue); }); r.getLinkpanel().forEach(lp -> { lp.getLinks().forEach(l -> { item.addLinksItem(getLink(l)); }); }); return item; } private List<FieldValue> collectSelectedOptions(List<Option> options) { return options.stream().filter(o -> Boolean.TRUE.equals(o.isSelected())).map(o -> { FieldValue childValue = new FieldValue(); childValue.setValue(o.getValue()); return childValue; }).collect(Collectors.toList()); } protected FieldValue getFieldValue(Datafield data, Optional<FieldDef> fieldDef, Class<?> bindClass) { if (fieldDef.isPresent()) { FieldValue fv = getFieldValue(data, fieldDef.get(), BeanUtils.findPropertyType(fieldDef.get().getBinding(), bindClass)); List<Datafield> childDataFields = data.getFields(); if (null != childDataFields) { final AtomicInteger i = new AtomicInteger(0); for (Datafield childData : childDataFields) { Optional<FieldDef> childField = getChildField(fieldDef.get(), data, i.get(), childData); FieldValue childValue = getFieldValue(childData, childField, bindClass); fv.getValues().put(childValue.getName(), childValue); i.incrementAndGet(); } } return fv; } FieldValue fv = new FieldValue(); fv.setName(data.getName()); return fv; } protected FieldValue getFieldValue(Datafield data, FieldDef field, Class<?> type) { FieldValue fv = new FieldValue(); fv.setName(data.getName()); data.getIcons().forEach(i -> { Icon icon = new Icon(); icon.setName(i.getContent()); icon.setLabel(i.getLabel()); fv.addIconsItem(icon); }); fv.setValue(getObjectValue(data, field, type, Collections.emptyList())); if (null != fv.getValue() && !org.appng.xml.platform.FieldType.DATE.equals(field.getType()) && StringUtils.isNotBlank(field.getFormat())) { fv.setFormattedValue(data.getValue()); } return fv; } protected Link getLink(org.appng.xml.platform.Linkable l) { Link link = null; if (l instanceof org.appng.xml.platform.Link) { link = new Link(); org.appng.xml.platform.Link ll = (org.appng.xml.platform.Link) l; link.setId(ll.getId()); link.setType(LINK_MAPPING.get(ll.getMode())); if (Linkmode.INTERN.equals(ll.getMode())) { String managerPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); String completePath = String.format("%s/%s/%s%s", managerPath, site.getName(), application.getName(), ll.getTarget()); link.setTarget(completePath); } else { link.setTarget(ll.getTarget()); } } else if (l instanceof org.appng.xml.platform.OpenapiAction) { ActionLink action = new ActionLink(); org.appng.xml.platform.OpenapiAction al = (org.appng.xml.platform.OpenapiAction) l; action.setId(al.getId()); Params params = ((org.appng.xml.platform.OpenapiAction) l).getParams(); if (null != params) { List<Parameter> parameters = new ArrayList<>(); params.getParam().forEach(p -> { Parameter param = new Parameter(); param.setName(p.getName()); param.setValue(p.getValue()); parameters.add(param); }); action.setParameters(parameters); } action.setTarget(al.getTarget()); action.setEventId(al.getEventId()); action.setInteractive(al.isInteractive()); action.setType(TypeEnum.ACTION); link = action; } link.setLabel(l.getLabel().getValue()); link.setIcon(l.getIcon().getContent()); link.setDefault(Boolean.TRUE.toString().equalsIgnoreCase(l.getDefault())); if (null != l.getConfirmation()) { link.setConfirmation(l.getConfirmation().getValue()); } return link; } protected static final Map<Linkmode, Link.TypeEnum> LINK_MAPPING = new HashMap<Linkmode, Link.TypeEnum>(); static { LINK_MAPPING.put(Linkmode.EXTERN, Link.TypeEnum.EXTERN); LINK_MAPPING.put(Linkmode.INTERN, Link.TypeEnum.PAGE); LINK_MAPPING.put(Linkmode.WEBSERVICE, Link.TypeEnum.INTERN); } Logger getLogger() { return LOGGER; } }
APPNG-2396 avoid NPE
appng-core/src/main/java/org/appng/core/controller/rest/openapi/OpenApiDataSource.java
APPNG-2396 avoid NPE
<ide><path>ppng-core/src/main/java/org/appng/core/controller/rest/openapi/OpenApiDataSource.java <ide> import java.util.Optional; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.function.Function; <ide> import java.util.stream.Collectors; <ide> <ide> import javax.servlet.http.HttpServletRequest; <ide> } <ide> List<FieldDef> childFields = f.getFields(); <ide> if (null != childFields) { <del> for (FieldDef fieldDef : childFields) { <del> Field child = getField(self, dataSourceId, fieldDef, hasQueryParams); <del> field.getFields().put(child.getName(), child); <del> } <add> field.setFields(childFields.stream().map(fieldDef -> getField(self, dataSourceId, fieldDef, hasQueryParams)) <add> .collect(Collectors.toMap(Field::getName, Function.identity()))); <ide> } <ide> Validation validation = f.getValidation(); <ide> if (null != validation) { <ide> if (collectedValues.size() == 1) { <ide> fieldValue.setValue(collectedValues.get(0).getValue()); <ide> } else { <add> fieldValue.setValues(new HashMap<>()); <ide> for (FieldValue value : collectedValues) { <ide> fieldValue.getValues().put(value.getName(), value); <ide> } <ide> FieldValue fv = getFieldValue(data, fieldDef.get(), <ide> BeanUtils.findPropertyType(fieldDef.get().getBinding(), bindClass)); <ide> List<Datafield> childDataFields = data.getFields(); <del> if (null != childDataFields) { <add> if (!childDataFields.isEmpty()) { <ide> final AtomicInteger i = new AtomicInteger(0); <add> fv.setValues(new HashMap<>()); <ide> for (Datafield childData : childDataFields) { <ide> Optional<FieldDef> childField = getChildField(fieldDef.get(), data, i.get(), childData); <ide> FieldValue childValue = getFieldValue(childData, childField, bindClass);
Java
mpl-2.0
a7ddecd61c0ffcfae2459d1ffcb7a23cee5baf77
0
projectdanube/xdi2-filesys,projectdanube/xdi2-filesys
package xdi2.messaging.target.contributor.impl.filesys; import java.io.File; import java.net.URLEncoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xdi2.core.features.nodetypes.XdiAbstractEntity; import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered; import xdi2.core.features.nodetypes.XdiEntity; import xdi2.core.features.nodetypes.XdiEntityCollection; import xdi2.core.features.nodetypes.XdiEntityMember; import xdi2.core.syntax.XDIAddress; import xdi2.core.util.GraphUtil; import xdi2.messaging.GetOperation; import xdi2.messaging.MessageResult; import xdi2.messaging.context.ExecutionContext; import xdi2.messaging.exceptions.Xdi2MessagingException; import xdi2.messaging.target.MessagingTarget; import xdi2.messaging.target.Prototype; import xdi2.messaging.target.contributor.AbstractContributor; import xdi2.messaging.target.contributor.ContributorMount; import xdi2.messaging.target.contributor.ContributorResult; import xdi2.messaging.target.impl.graph.GraphMessagingTarget; @ContributorMount(contributorXDIAddresses={"(#test)"}) public class FileSysContributor extends AbstractContributor implements Prototype<FileSysContributor> { private static final Logger log = LoggerFactory.getLogger(FileSysContributor.class); private static final String DEFAULT_BASE_PATH = "."; private static final String DEFAULT_GRAPH_PATH = null; private static final XDIAddress XDI_ADD_EC_DIR = XDIAddress.create("[#dir]"); private static final XDIAddress XDI_ADD_EC_FILE = XDIAddress.create("[#file]"); private static final XDIAddress XDI_ADD_AS_NAME = XDIAddress.create("<#name>"); private static final XDIAddress XDI_ADD_AS_SIZE = XDIAddress.create("<#size>"); private String basePath; private String graphPath; public FileSysContributor() { super(); this.basePath = DEFAULT_BASE_PATH; this.graphPath = DEFAULT_GRAPH_PATH; this.getContributors().addContributor(new FileSysDirContributor()); } /* * Prototype */ @Override public FileSysContributor instanceFor(PrototypingContext prototypingContext) throws Xdi2MessagingException { // create new contributor FileSysContributor contributor = new FileSysContributor(); // set the something // contributor.setTokenGraph(this.getTokenGraph()); // done return contributor; } /* * Init and shutdown */ @Override public void init(MessagingTarget messagingTarget) throws Exception { super.init(messagingTarget); // determine base path if (this.getBasePath() == null) throw new Xdi2MessagingException("No base path.", null, null); if (! this.getBasePath().endsWith("/")) this.setBasePath(this.getBasePath() + "/"); // determine graph path if (this.getGraphPath() == null && messagingTarget instanceof GraphMessagingTarget) { String relativeGraphPath = URLEncoder.encode(GraphUtil.getOwnerXDIAddress(((GraphMessagingTarget) messagingTarget).getGraph()).toString(), "UTF-8"); this.setGraphPath(this.getBasePath() + relativeGraphPath); } if (this.getGraphPath() == null) throw new Xdi2MessagingException("No graph path.", null, null); } /* * Sub-Contributors */ @ContributorMount(contributorXDIAddresses={"#dir"}) private class FileSysDirContributor extends AbstractContributor { private FileSysDirContributor() { super(); this.getContributors().addContributor(new FileSysOtherContributor()); } @Override public ContributorResult executeGetOnAddress(XDIAddress[] contributorAddresses, XDIAddress contributorsXri, XDIAddress relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { XDIAddress fileSysContextXri = contributorAddresses[contributorAddresses.length - 2]; XDIAddress fileSysDirContextXri = contributorAddresses[contributorAddresses.length - 1]; log.debug("fileSysContextXri: " + fileSysContextXri + ", fileSysDirContextXri: " + fileSysDirContextXri); // map the directory File graphRootDir = new File(FileSysContributor.this.getGraphPath()); XdiEntity xdiEntity = XdiAbstractEntity.fromContextNode(messageResult.getGraph().setDeepContextNode(contributorsXri)); mapDir(graphRootDir, xdiEntity); // done return ContributorResult.SKIP_MESSAGING_TARGET; } } @ContributorMount(contributorXDIAddresses={"{}"}) private class FileSysOtherContributor extends AbstractContributor { private FileSysOtherContributor() { super(); } @Override public ContributorResult executeGetOnAddress(XDIAddress[] contributorAddresses, XDIAddress contributorsXri, XDIAddress relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { XDIAddress fileSysContextXri = contributorAddresses[contributorAddresses.length - 2]; XDIAddress fileSysDirContextXri = contributorAddresses[contributorAddresses.length - 1]; log.debug("fileSysContextXri: " + fileSysContextXri + ", fileSysDirContextXri: " + fileSysDirContextXri); // parse identifiers // done return new ContributorResult(true, false, true); } } /* * Helper methods */ private static void mapDir(File dir, XdiEntity xdiEntity) { XdiEntityCollection dirXdiEntityCollection = xdiEntity.getXdiEntityCollection(XDI_ADD_EC_DIR, true); XdiEntityCollection fileXdiEntityCollection = xdiEntity.getXdiEntityCollection(XDI_ADD_EC_FILE, true); for (File file : dir.listFiles()) { if (file.isDirectory()) { if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": Directory: " + file.getAbsolutePath()); XdiEntityMember dirXdiEntityMember = dirXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidXDIArc(XdiEntityCollection.class)); dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).setLiteralString(file.getName()); dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); mapDir(file, dirXdiEntityMember); } if (file.isFile()) { if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": File: " + file.getAbsolutePath()); XdiEntityMember fileXdiEntityMember = fileXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidXDIArc(XdiEntityCollection.class)); fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).setLiteralString(file.getName()); fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); } } } /* * Getters and setters */ public String getBasePath() { return this.basePath; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getGraphPath() { return this.graphPath; } public void setGraphPath(String graphPath) { this.graphPath = graphPath; } }
src/main/java/xdi2/messaging/target/contributor/impl/filesys/FileSysContributor.java
package xdi2.messaging.target.contributor.impl.filesys; import java.io.File; import java.net.URLEncoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xdi2.core.features.nodetypes.XdiAbstractEntity; import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered; import xdi2.core.features.nodetypes.XdiEntity; import xdi2.core.features.nodetypes.XdiEntityCollection; import xdi2.core.features.nodetypes.XdiEntityMember; import xdi2.core.syntax.XDIAddress; import xdi2.core.util.GraphUtil; import xdi2.messaging.GetOperation; import xdi2.messaging.MessageResult; import xdi2.messaging.context.ExecutionContext; import xdi2.messaging.exceptions.Xdi2MessagingException; import xdi2.messaging.target.MessagingTarget; import xdi2.messaging.target.Prototype; import xdi2.messaging.target.contributor.AbstractContributor; import xdi2.messaging.target.contributor.ContributorMount; import xdi2.messaging.target.contributor.ContributorResult; import xdi2.messaging.target.impl.graph.GraphMessagingTarget; @ContributorMount(contributorXDIAddresses={"(#test)"}) public class FileSysContributor extends AbstractContributor implements Prototype<FileSysContributor> { private static final Logger log = LoggerFactory.getLogger(FileSysContributor.class); private static final String DEFAULT_BASE_PATH = "."; private static final String DEFAULT_GRAPH_PATH = null; private static final XDIAddress XDI_ADD_EC_DIR = XDIAddress.create("[#dir]"); private static final XDIAddress XDI_ADD_EC_FILE = XDIAddress.create("[#file]"); private static final XDIAddress XDI_ADD_AS_NAME = XDIAddress.create("<#name>"); private static final XDIAddress XDI_ADD_AS_SIZE = XDIAddress.create("<#size>"); private String basePath; private String graphPath; public FileSysContributor() { super(); this.basePath = DEFAULT_BASE_PATH; this.graphPath = DEFAULT_GRAPH_PATH; this.getContributors().addContributor(new FileSysDirContributor()); } /* * Prototype */ @Override public FileSysContributor instanceFor(PrototypingContext prototypingContext) throws Xdi2MessagingException { // create new contributor FileSysContributor contributor = new FileSysContributor(); // set the something // contributor.setTokenGraph(this.getTokenGraph()); // done return contributor; } /* * Init and shutdown */ @Override public void init(MessagingTarget messagingTarget) throws Exception { super.init(messagingTarget); // determine base path if (this.getBasePath() == null) throw new Xdi2MessagingException("No base path.", null, null); if (! this.getBasePath().endsWith("/")) this.setBasePath(this.getBasePath() + "/"); // determine graph path if (this.getGraphPath() == null && messagingTarget instanceof GraphMessagingTarget) { String relativeGraphPath = URLEncoder.encode(GraphUtil.getOwnerXDIAddress(((GraphMessagingTarget) messagingTarget).getGraph()).toString(), "UTF-8"); this.setGraphPath(this.getBasePath() + relativeGraphPath); } if (this.getGraphPath() == null) throw new Xdi2MessagingException("No graph path.", null, null); } /* * Sub-Contributors */ @ContributorMount(contributorXDIAddresses={"#dir"}) private class FileSysDirContributor extends AbstractContributor { private FileSysDirContributor() { super(); this.getContributors().addContributor(new FileSysOtherContributor()); } @Override public ContributorResult executeGetOnAddress(XDIAddress[] contributorAddresses, XDIAddress contributorsXri, XDIAddress relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { XDIAddress fileSysContextXri = contributorAddresses[contributorAddresses.length - 2]; XDIAddress fileSysDirContextXri = contributorAddresses[contributorAddresses.length - 1]; log.debug("fileSysContextXri: " + fileSysContextXri + ", fileSysDirContextXri: " + fileSysDirContextXri); // map the directory File graphRootDir = new File(FileSysContributor.this.getGraphPath()); XdiEntity xdiEntity = XdiAbstractEntity.fromContextNode(messageResult.getGraph().setDeepContextNode(contributorsXri)); mapDir(graphRootDir, xdiEntity); // done return ContributorResult.SKIP_MESSAGING_TARGET; } } @ContributorMount(contributorXDIAddresses={"{}"}) private class FileSysOtherContributor extends AbstractContributor { private FileSysOtherContributor() { super(); } @Override public ContributorResult executeGetOnAddress(XDIAddress[] contributorAddresses, XDIAddress contributorsXri, XDIAddress relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException { XDIAddress fileSysContextXri = contributorAddresses[contributorAddresses.length - 2]; XDIAddress fileSysDirContextXri = contributorAddresses[contributorAddresses.length - 1]; log.debug("fileSysContextXri: " + fileSysContextXri + ", fileSysDirContextXri: " + fileSysDirContextXri); // parse identifiers // done return new ContributorResult(true, false, true); } } /* * Helper methods */ private static void mapDir(File dir, XdiEntity xdiEntity) { XdiEntityCollection dirXdiEntityCollection = xdiEntity.getXdiEntityCollection(XDI_ADD_EC_DIR, true); XdiEntityCollection fileXdiEntityCollection = xdiEntity.getXdiEntityCollection(XDI_ADD_EC_FILE, true); for (File file : dir.listFiles()) { if (file.isDirectory()) { if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": Directory: " + file.getAbsolutePath()); XdiEntityMember dirXdiEntityMember = dirXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidXDIArc(XdiEntityCollection.class)); dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).getXdiValue(true).setLiteralString(file.getName()); dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).getXdiValue(true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); mapDir(file, dirXdiEntityMember); } if (file.isFile()) { if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": File: " + file.getAbsolutePath()); XdiEntityMember fileXdiEntityMember = fileXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidXDIArc(XdiEntityCollection.class)); fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).getXdiValue(true).setLiteralString(file.getName()); fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).getXdiValue(true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); } } } /* * Getters and setters */ public String getBasePath() { return this.basePath; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getGraphPath() { return this.graphPath; } public void setGraphPath(String graphPath) { this.graphPath = graphPath; } }
no value node
src/main/java/xdi2/messaging/target/contributor/impl/filesys/FileSysContributor.java
no value node
<ide><path>rc/main/java/xdi2/messaging/target/contributor/impl/filesys/FileSysContributor.java <ide> if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": Directory: " + file.getAbsolutePath()); <ide> <ide> XdiEntityMember dirXdiEntityMember = dirXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidXDIArc(XdiEntityCollection.class)); <del> dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).getXdiValue(true).setLiteralString(file.getName()); <del> dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).getXdiValue(true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); <add> dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).setLiteralString(file.getName()); <add> dirXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); <ide> <ide> mapDir(file, dirXdiEntityMember); <ide> } <ide> if (log.isDebugEnabled()) log.debug("In " + dir.getAbsolutePath() + ": File: " + file.getAbsolutePath()); <ide> <ide> XdiEntityMember fileXdiEntityMember = fileXdiEntityCollection.setXdiMemberUnordered(XdiAbstractMemberUnordered.createRandomUuidXDIArc(XdiEntityCollection.class)); <del> fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).getXdiValue(true).setLiteralString(file.getName()); <del> fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).getXdiValue(true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); <add> fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_NAME, true).setLiteralString(file.getName()); <add> fileXdiEntityMember.getXdiAttribute(XDI_ADD_AS_SIZE, true).setLiteralNumber(Double.valueOf(file.getTotalSpace())); <ide> } <ide> } <ide> }
Java
apache-2.0
d55bf3b1c99692febca452b10487899e6bce3176
0
ingenieux/beanstalker,ingenieux/beanstalker
package br.com.ingenieux.mojo.beanstalk.env; /* * 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 com.amazonaws.services.elasticbeanstalk.model.CheckDNSAvailabilityRequest; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting; import com.amazonaws.services.elasticbeanstalk.model.CreateEnvironmentResult; import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsResult; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.AbstractMojoExecutionException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.ListIterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import br.com.ingenieux.mojo.aws.util.CredentialsUtil; import br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsCommand; import br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsContext; import br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsContextBuilder; import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesCommand; import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContext; import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContextBuilder; import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentCommand; import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContext; import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContextBuilder; import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand; import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContext; import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContextBuilder; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.isNotBlank; /** * Launches a new environment and, when done, replace with the existing, terminating when needed. It * combines both create-environment, wait-for-environment, swap-environment-cnames, and * terminate-environment * * @since 0.2.0 */ @Mojo(name = "replace-environment") // Best Guess Evar public class ReplaceEnvironmentMojo extends CreateEnvironmentMojo { /** * Pattern for Increasing in Replace Environment */ private static final Pattern PATTERN_NUMBERED = Pattern .compile("^(.*)-(\\d+)$"); /** * Max Environment Name Length */ private static final int MAX_ENVNAME_LEN = 23; /** * Minutes until timeout */ @Parameter(property = "beanstalk.timeoutMins", defaultValue = "20") Integer timeoutMins; /** * Skips if Same Version? */ @Parameter(property = "beanstalk.skipIfSameVersion", defaultValue = "true") boolean skipIfSameVersion = true; /** * Max Number of Attempts (for cnameSwap in Particular) */ @Parameter(property = "beanstalk.maxAttempts", defaultValue = "15") Integer maxAttempts = 15; /** * Do a 'Mock' Terminate Environment Call (useful for Debugging) */ @Parameter(property = "beanstalk.mockTerminateEnvironment", defaultValue = "false") boolean mockTerminateEnvironment = false; /** * Retry Interval, in Seconds */ @Parameter(property = "beanstalk.attemptRetryInterval", defaultValue = "60") int attemptRetryInterval = 60; /** * <p>List of R53 Domains</p> * * <p>Could be set as either:</p> <ul> <li>fqdn:hostedZoneId (e.g. "services.modafocas.org:Z3DJ4DL0DIEEJA")</li> * <li>hosted zone name - will be set to root. (e.g., "modafocas.org")</li> </ul> */ @Parameter(property = "beanstalk.domains") String[] domains; /** * Whether or not to copy option settings from old environment when replacing */ @Parameter(property = "beanstalk.copyOptionSettings", defaultValue = "true") boolean copyOptionSettings = true; /** * Whether or not to keep the Elastic Beanstalk platform (aka solutionStack) from the old environment when replacing */ @Parameter(property = "beanstalk.copySolutionStack", defaultValue = "true") boolean copySolutionStack = true; @Override protected EnvironmentDescription handleResults( Collection<EnvironmentDescription> environments) throws MojoExecutionException { // Don't care - We're an exception to the rule, you know. return null; } @Override protected Object executeInternal() throws Exception { solutionStack = lookupSolutionStack(solutionStack); /* * Is the desired cname not being used by other environments? If so, * just launch the environment */ if (!hasEnvironmentFor(applicationName, cnamePrefix)) { if (getLog().isInfoEnabled()) { getLog().info("Just launching a new environment."); } return super.executeInternal(); } /* * Gets the current environment using this cname */ EnvironmentDescription curEnv = getEnvironmentFor(applicationName, cnamePrefix); if (curEnv.getVersionLabel().equals(versionLabel) && skipIfSameVersion) { getLog().warn( format("Environment is running version %s and skipIfSameVersion is true. Returning", versionLabel)); return null; } /* * Decides on a environmentRef, and launches a new environment */ String cnamePrefixToCreate = getCNamePrefixToCreate(); if (getLog().isInfoEnabled()) { getLog().info( "Creating a new environment on " + cnamePrefixToCreate + ".elasticbeanstalk.com"); } if (copyOptionSettings) { copyOptionSettings(curEnv); } if (!solutionStack.equals(curEnv.getSolutionStackName()) && copySolutionStack) { if (getLog().isWarnEnabled()) { getLog().warn( format( "(btw, we're launching with solutionStack/ set to '%s' based on the existing env instead of the " + "default ('%s'). If this is not the desired behavior please set the copySolutionStack property to" + " false.", curEnv.getSolutionStackName(), solutionStack)); } solutionStack = curEnv.getSolutionStackName(); } String newEnvironmentName = getNewEnvironmentName(StringUtils.defaultString(this.environmentName, curEnv.getEnvironmentName())); if (getLog().isInfoEnabled()) { getLog().info("And it'll be named " + newEnvironmentName); } CreateEnvironmentResult createEnvResult = createEnvironment( cnamePrefixToCreate, newEnvironmentName); /* * Waits for completion */ EnvironmentDescription newEnvDesc = null; try { newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId()); } catch (Exception exc) { /* * Terminates the failed launched environment */ terminateEnvironment(createEnvResult.getEnvironmentId()); handleException(exc); return null; } /* * Swaps. Due to beanstalker-25, we're doing some extra logic we * actually woudln't want to. */ { boolean swapped = false; for (int i = 1; i <= maxAttempts; i++) { try { swapEnvironmentCNames(newEnvDesc.getEnvironmentId(), curEnv.getEnvironmentId(), cnamePrefix, newEnvDesc); swapped = true; break; } catch (Throwable exc) { if (exc instanceof MojoFailureException) { exc = Throwable.class.cast(MojoFailureException.class .cast(exc).getCause()); } getLog().warn( format("Attempt #%d/%d failed. Sleeping and retrying. Reason: %s (type: %s)", i, maxAttempts, exc.getMessage(), exc.getClass())); sleepInterval(attemptRetryInterval); } } if (!swapped) { getLog().info( "Failed to properly Replace Environment. Finishing the new one. And throwing you a failure"); terminateEnvironment(newEnvDesc.getEnvironmentId()); String message = "Unable to swap cnames. btw, see https://github.com/ingenieux/beanstalker/issues/25 and help us improve beanstalker"; getLog().warn(message); throw new MojoFailureException(message); } } /* * Terminates the previous environment */ terminateEnvironment(curEnv.getEnvironmentId()); return createEnvResult; } public void sleepInterval(int pollInterval) { getLog().info( format("Sleeping for %d seconds (and until %s)", pollInterval, new Date(System.currentTimeMillis() + 1000 * pollInterval))); try { Thread.sleep(1000 * pollInterval); } catch (InterruptedException e) { } } /** * Prior to Launching a New Environment, lets look and copy the most we can * * @param curEnv current environment */ private void copyOptionSettings(EnvironmentDescription curEnv) throws Exception { /** * Skip if we don't have anything */ if (null != this.optionSettings && this.optionSettings.length > 0) { return; } DescribeConfigurationSettingsResult configSettings = getService() .describeConfigurationSettings( new DescribeConfigurationSettingsRequest() .withApplicationName(applicationName) .withEnvironmentName( curEnv.getEnvironmentName())); List<ConfigurationOptionSetting> newOptionSettings = new ArrayList<ConfigurationOptionSetting>( configSettings.getConfigurationSettings().get(0) .getOptionSettings()); ListIterator<ConfigurationOptionSetting> listIterator = newOptionSettings .listIterator(); while (listIterator.hasNext()) { ConfigurationOptionSetting curOptionSetting = listIterator.next(); boolean bInvalid = harmfulOptionSettingP(curEnv.getEnvironmentId(), curOptionSetting); if (bInvalid) { getLog().info( format("Excluding Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting .getValue()))); listIterator.remove(); } else { getLog().info( format("Including Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting .getValue()))); } } Object __secGroups = project.getProperties().get( "beanstalk.securityGroups"); if (null != __secGroups) { String securityGroups = StringUtils.defaultString(__secGroups.toString()); if (!StringUtils.isBlank(securityGroups)) { ConfigurationOptionSetting newOptionSetting = new ConfigurationOptionSetting( "aws:autoscaling:launchconfiguration", "SecurityGroups", securityGroups); newOptionSettings.add(newOptionSetting); getLog().info( format("Including Option Setting: %s:%s['%s']", newOptionSetting.getNamespace(), newOptionSetting.getOptionName(), newOptionSetting.getValue())); } } /* * Then copy it back */ this.optionSettings = newOptionSettings .toArray(new ConfigurationOptionSetting[newOptionSettings .size()]); } /** * Swaps environment cnames * @param newEnvironmentId environment id * @param curEnvironmentId environment id * @param newEnv */ protected void swapEnvironmentCNames(String newEnvironmentId, String curEnvironmentId, String cnamePrefix, EnvironmentDescription newEnv) throws AbstractMojoExecutionException { getLog().info( "Swapping environment cnames " + newEnvironmentId + " and " + curEnvironmentId); { SwapCNamesContext context = SwapCNamesContextBuilder .swapCNamesContext()// .withSourceEnvironmentId(newEnvironmentId)// .withDestinationEnvironmentId(curEnvironmentId)// .build(); SwapCNamesCommand command = new SwapCNamesCommand(this); command.execute(context); } /* * Changes in Route53 as well. */ if (null != domains) { List<String> domainsToUse = new ArrayList<String>(); for (String s : domains) { if (isNotBlank(s)) { domainsToUse.add(s.trim()); } } if (!domainsToUse.isEmpty()) { final BindDomainsContext ctx = new BindDomainsContextBuilder().withCurEnv(newEnv).withDomains(domainsToUse) .build(); new BindDomainsCommand(this).execute( ctx); } else { getLog().info("Skipping r53 domain binding"); } } { WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder() .withApplicationName(applicationName)// .withStatusToWaitFor("Ready")// .withEnvironmentRef(newEnvironmentId)// .withTimeoutMins(timeoutMins)// .build(); WaitForEnvironmentCommand command = new WaitForEnvironmentCommand( this); command.execute(context); } } /** * Terminates and waits for an environment * * @param environmentId environment id to terminate */ protected void terminateEnvironment(String environmentId) throws AbstractMojoExecutionException { if (mockTerminateEnvironment) { getLog().info( format( "We're ignoring the termination of environment id '%s' (see mockTerminateEnvironment)", environmentId)); return; } Exception lastException = null; for (int i = 1; i <= maxAttempts; i++) { getLog().info( format("Terminating environmentId=%s (attempt %d/%d)", environmentId, i, maxAttempts)); try { TerminateEnvironmentContext terminatecontext = new TerminateEnvironmentContextBuilder() .withEnvironmentId(environmentId) .withTerminateResources(true).build(); TerminateEnvironmentCommand command = new TerminateEnvironmentCommand( this); command.execute(terminatecontext); return; } catch (Exception exc) { lastException = exc; } } throw new MojoFailureException("Unable to terminate environment " + environmentId, lastException); } /** * Waits for an environment to get ready. Throws an exception either if this environment couldn't * get into Ready state or there was a timeout * * @param environmentId environmentId to wait for * @return EnvironmentDescription in Ready state */ protected EnvironmentDescription waitForEnvironment(String environmentId) throws AbstractMojoExecutionException { getLog().info( "Waiting for environmentId " + environmentId + " to get into Ready state"); WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder() .withApplicationName(applicationName) .withStatusToWaitFor("Ready").withEnvironmentRef(environmentId) .withHealth("Green") .withTimeoutMins(timeoutMins).build(); WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(this); return command.execute(context); } /** * Creates a cname prefix if needed, or returns the desired one * * @return cname prefix to launch environment into */ protected String getCNamePrefixToCreate() { String cnamePrefixToReturn = cnamePrefix; int i = 0; while (hasEnvironmentFor(applicationName, cnamePrefixToReturn) || isNamedEnvironmentUnavailable( cnamePrefixToReturn)) { cnamePrefixToReturn = String.format("%s-%d", cnamePrefix, i++); } return cnamePrefixToReturn; } /** * Boolean predicate for environment existence * * @param applicationName application name * @param cnamePrefix cname prefix * @return true if the application name has this cname prefix */ protected boolean hasEnvironmentFor(String applicationName, String cnamePrefix) { return null != getEnvironmentFor(applicationName, cnamePrefix); } /** * Returns the environment description matching applicationName and environmentRef * * @param applicationName application name * @param cnamePrefix cname prefix * @return environment description */ protected EnvironmentDescription getEnvironmentFor(String applicationName, String cnamePrefix) { Collection<EnvironmentDescription> environments = getEnvironmentsFor(applicationName); String cnameToMatch = String.format("%s.elasticbeanstalk.com", cnamePrefix); /* * Finds a matching environment */ for (EnvironmentDescription envDesc : environments) { if (cnameToMatch.equals(envDesc.getCNAME())) { return envDesc; } } return null; } private String getNewEnvironmentName(String newEnvironmentName) { String result = newEnvironmentName; String environmentRadical = result; int i = 0; { Matcher matcher = PATTERN_NUMBERED.matcher(newEnvironmentName); if (matcher.matches()) { environmentRadical = matcher.group(1); i = 1 + Integer.valueOf(matcher.group(2)); } } while (containsNamedEnvironment(result) || isNamedEnvironmentUnavailable(result)) { result = formatAndTruncate("%s-%d", MAX_ENVNAME_LEN, environmentRadical, i++); } return result; } private boolean isNamedEnvironmentUnavailable(String cnamePrefix) { return !getService().checkDNSAvailability(new CheckDNSAvailabilityRequest(cnamePrefix)) .isAvailable(); } /** * Elastic Beanstalk Contains a Max EnvironmentName Limit. Lets truncate it, shall we? * * @param mask String.format Mask * @param maxLen Maximum Length * @param args String.format args * @return formatted String, or maxLen rightmost characters */ protected String formatAndTruncate(String mask, int maxLen, Object... args) { String result = String.format(mask, args); if (result.length() > maxLen) { result = result .substring(result.length() - maxLen, result.length()); } return result; } /** * Boolean predicate for named environment * * @param environmentName environment name * @return true if environment name exists */ protected boolean containsNamedEnvironment(String environmentName) { for (EnvironmentDescription envDesc : getEnvironmentsFor(applicationName)) { if (envDesc.getEnvironmentName().equals(environmentName)) { return true; } } return false; } }
beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/env/ReplaceEnvironmentMojo.java
package br.com.ingenieux.mojo.beanstalk.env; /* * 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 com.amazonaws.services.elasticbeanstalk.model.CheckDNSAvailabilityRequest; import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting; import com.amazonaws.services.elasticbeanstalk.model.CreateEnvironmentResult; import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsResult; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.AbstractMojoExecutionException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.ListIterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import br.com.ingenieux.mojo.aws.util.CredentialsUtil; import br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsCommand; import br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsContext; import br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsContextBuilder; import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesCommand; import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContext; import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContextBuilder; import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentCommand; import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContext; import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContextBuilder; import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand; import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContext; import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContextBuilder; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.isNotBlank; /** * Launches a new environment and, when done, replace with the existing, terminating when needed. It * combines both create-environment, wait-for-environment, swap-environment-cnames, and * terminate-environment * * @since 0.2.0 */ @Mojo(name = "replace-environment") // Best Guess Evar public class ReplaceEnvironmentMojo extends CreateEnvironmentMojo { /** * Pattern for Increasing in Replace Environment */ private static final Pattern PATTERN_NUMBERED = Pattern .compile("^(.*)-(\\d+)$"); /** * Max Environment Name Length */ private static final int MAX_ENVNAME_LEN = 23; /** * Minutes until timeout */ @Parameter(property = "beanstalk.timeoutMins", defaultValue = "20") Integer timeoutMins; /** * Skips if Same Version? */ @Parameter(property = "beanstalk.skipIfSameVersion", defaultValue = "true") boolean skipIfSameVersion = true; /** * Max Number of Attempts (for cnameSwap in Particular) */ @Parameter(property = "beanstalk.maxAttempts", defaultValue = "15") Integer maxAttempts = 15; /** * Do a 'Mock' Terminate Environment Call (useful for Debugging) */ @Parameter(property = "beanstalk.mockTerminateEnvironment", defaultValue = "false") boolean mockTerminateEnvironment = false; /** * Retry Interval, in Seconds */ @Parameter(property = "beanstalk.attemptRetryInterval", defaultValue = "60") int attemptRetryInterval = 60; /** * <p>List of R53 Domains</p> * * <p>Could be set as either:</p> <ul> <li>fqdn:hostedZoneId (e.g. "services.modafocas.org:Z3DJ4DL0DIEEJA")</li> * <li>hosted zone name - will be set to root. (e.g., "modafocas.org")</li> </ul> */ @Parameter(property = "beanstalk.domains") String[] domains; /** * Whether or not to copy option settings from old environment when replacing */ @Parameter(property = "beanstalk.copyOptionSettings", defaultValue = "true") boolean copyOptionSettings = true; @Override protected EnvironmentDescription handleResults( Collection<EnvironmentDescription> environments) throws MojoExecutionException { // Don't care - We're an exception to the rule, you know. return null; } @Override protected Object executeInternal() throws Exception { solutionStack = lookupSolutionStack(solutionStack); /* * Is the desired cname not being used by other environments? If so, * just launch the environment */ if (!hasEnvironmentFor(applicationName, cnamePrefix)) { if (getLog().isInfoEnabled()) { getLog().info("Just launching a new environment."); } return super.executeInternal(); } /* * Gets the current environment using this cname */ EnvironmentDescription curEnv = getEnvironmentFor(applicationName, cnamePrefix); if (curEnv.getVersionLabel().equals(versionLabel) && skipIfSameVersion) { getLog().warn( format("Environment is running version %s and skipIfSameVersion is true. Returning", versionLabel)); return null; } /* * Decides on a environmentRef, and launches a new environment */ String cnamePrefixToCreate = getCNamePrefixToCreate(); if (getLog().isInfoEnabled()) { getLog().info( "Creating a new environment on " + cnamePrefixToCreate + ".elasticbeanstalk.com"); } if (copyOptionSettings) { copyOptionSettings(curEnv); } if (!solutionStack.equals(curEnv.getSolutionStackName())) { if (getLog().isInfoEnabled()) { getLog().warn( format( "(btw, we're launching with solutionStack/ set to '%s' instead of the default ('%s'). " + "If this is not the case, then we kindly ask you to file a bug report on the mailing list :)", curEnv.getSolutionStackName(), solutionStack)); } solutionStack = curEnv.getSolutionStackName(); } String newEnvironmentName = getNewEnvironmentName(StringUtils .defaultString(this.environmentName, curEnv .getEnvironmentName())); if (getLog().isInfoEnabled()) { getLog().info("And it'll be named " + newEnvironmentName); } CreateEnvironmentResult createEnvResult = createEnvironment( cnamePrefixToCreate, newEnvironmentName); /* * Waits for completion */ EnvironmentDescription newEnvDesc = null; try { newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId()); } catch (Exception exc) { /* * Terminates the failed launched environment */ terminateEnvironment(createEnvResult.getEnvironmentId()); handleException(exc); return null; } /* * Swaps. Due to beanstalker-25, we're doing some extra logic we * actually woudln't want to. */ { boolean swapped = false; for (int i = 1; i <= maxAttempts; i++) { try { swapEnvironmentCNames(newEnvDesc.getEnvironmentId(), curEnv.getEnvironmentId(), cnamePrefix, newEnvDesc); swapped = true; break; } catch (Throwable exc) { if (exc instanceof MojoFailureException) { exc = Throwable.class.cast(MojoFailureException.class .cast(exc).getCause()); } getLog().warn( format("Attempt #%d/%d failed. Sleeping and retrying. Reason: %s (type: %s)", i, maxAttempts, exc.getMessage(), exc.getClass())); sleepInterval(attemptRetryInterval); } } if (!swapped) { getLog().info( "Failed to properly Replace Environment. Finishing the new one. And throwing you a failure"); terminateEnvironment(newEnvDesc.getEnvironmentId()); String message = "Unable to swap cnames. btw, see https://github.com/ingenieux/beanstalker/issues/25 and help us improve beanstalker"; getLog().warn(message); throw new MojoFailureException(message); } } /* * Terminates the previous environment */ terminateEnvironment(curEnv.getEnvironmentId()); return createEnvResult; } public void sleepInterval(int pollInterval) { getLog().info( format("Sleeping for %d seconds (and until %s)", pollInterval, new Date(System.currentTimeMillis() + 1000 * pollInterval))); try { Thread.sleep(1000 * pollInterval); } catch (InterruptedException e) { } } /** * Prior to Launching a New Environment, lets look and copy the most we can * * @param curEnv current environment */ private void copyOptionSettings(EnvironmentDescription curEnv) throws Exception { /** * Skip if we don't have anything */ if (null != this.optionSettings && this.optionSettings.length > 0) { return; } DescribeConfigurationSettingsResult configSettings = getService() .describeConfigurationSettings( new DescribeConfigurationSettingsRequest() .withApplicationName(applicationName) .withEnvironmentName( curEnv.getEnvironmentName())); List<ConfigurationOptionSetting> newOptionSettings = new ArrayList<ConfigurationOptionSetting>( configSettings.getConfigurationSettings().get(0) .getOptionSettings()); ListIterator<ConfigurationOptionSetting> listIterator = newOptionSettings .listIterator(); while (listIterator.hasNext()) { ConfigurationOptionSetting curOptionSetting = listIterator.next(); boolean bInvalid = harmfulOptionSettingP(curEnv.getEnvironmentId(), curOptionSetting); if (bInvalid) { getLog().info( format("Excluding Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting .getValue()))); listIterator.remove(); } else { getLog().info( format("Including Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), CredentialsUtil.redact(curOptionSetting .getValue()))); } } Object __secGroups = project.getProperties().get( "beanstalk.securityGroups"); if (null != __secGroups) { String securityGroups = StringUtils.defaultString(__secGroups.toString()); if (!StringUtils.isBlank(securityGroups)) { ConfigurationOptionSetting newOptionSetting = new ConfigurationOptionSetting( "aws:autoscaling:launchconfiguration", "SecurityGroups", securityGroups); newOptionSettings.add(newOptionSetting); getLog().info( format("Including Option Setting: %s:%s['%s']", newOptionSetting.getNamespace(), newOptionSetting.getOptionName(), newOptionSetting.getValue())); } } /* * Then copy it back */ this.optionSettings = newOptionSettings .toArray(new ConfigurationOptionSetting[newOptionSettings .size()]); } /** * Swaps environment cnames * @param newEnvironmentId environment id * @param curEnvironmentId environment id * @param newEnv */ protected void swapEnvironmentCNames(String newEnvironmentId, String curEnvironmentId, String cnamePrefix, EnvironmentDescription newEnv) throws AbstractMojoExecutionException { getLog().info( "Swapping environment cnames " + newEnvironmentId + " and " + curEnvironmentId); { SwapCNamesContext context = SwapCNamesContextBuilder .swapCNamesContext()// .withSourceEnvironmentId(newEnvironmentId)// .withDestinationEnvironmentId(curEnvironmentId)// .build(); SwapCNamesCommand command = new SwapCNamesCommand(this); command.execute(context); } /* * Changes in Route53 as well. */ if (null != domains) { List<String> domainsToUse = new ArrayList<String>(); for (String s : domains) { if (isNotBlank(s)) { domainsToUse.add(s.trim()); } } if (!domainsToUse.isEmpty()) { final BindDomainsContext ctx = new BindDomainsContextBuilder().withCurEnv(newEnv).withDomains(domainsToUse) .build(); new BindDomainsCommand(this).execute( ctx); } else { getLog().info("Skipping r53 domain binding"); } } { WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder() .withApplicationName(applicationName)// .withStatusToWaitFor("Ready")// .withEnvironmentRef(newEnvironmentId)// .withTimeoutMins(timeoutMins)// .build(); WaitForEnvironmentCommand command = new WaitForEnvironmentCommand( this); command.execute(context); } } /** * Terminates and waits for an environment * * @param environmentId environment id to terminate */ protected void terminateEnvironment(String environmentId) throws AbstractMojoExecutionException { if (mockTerminateEnvironment) { getLog().info( format( "We're ignoring the termination of environment id '%s' (see mockTerminateEnvironment)", environmentId)); return; } Exception lastException = null; for (int i = 1; i <= maxAttempts; i++) { getLog().info( format("Terminating environmentId=%s (attempt %d/%d)", environmentId, i, maxAttempts)); try { TerminateEnvironmentContext terminatecontext = new TerminateEnvironmentContextBuilder() .withEnvironmentId(environmentId) .withTerminateResources(true).build(); TerminateEnvironmentCommand command = new TerminateEnvironmentCommand( this); command.execute(terminatecontext); return; } catch (Exception exc) { lastException = exc; } } throw new MojoFailureException("Unable to terminate environment " + environmentId, lastException); } /** * Waits for an environment to get ready. Throws an exception either if this environment couldn't * get into Ready state or there was a timeout * * @param environmentId environmentId to wait for * @return EnvironmentDescription in Ready state */ protected EnvironmentDescription waitForEnvironment(String environmentId) throws AbstractMojoExecutionException { getLog().info( "Waiting for environmentId " + environmentId + " to get into Ready state"); WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder() .withApplicationName(applicationName) .withStatusToWaitFor("Ready").withEnvironmentRef(environmentId) .withHealth("Green") .withTimeoutMins(timeoutMins).build(); WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(this); return command.execute(context); } /** * Creates a cname prefix if needed, or returns the desired one * * @return cname prefix to launch environment into */ protected String getCNamePrefixToCreate() { String cnamePrefixToReturn = cnamePrefix; int i = 0; while (hasEnvironmentFor(applicationName, cnamePrefixToReturn) || isNamedEnvironmentUnavailable( cnamePrefixToReturn)) { cnamePrefixToReturn = String.format("%s-%d", cnamePrefix, i++); } return cnamePrefixToReturn; } /** * Boolean predicate for environment existence * * @param applicationName application name * @param cnamePrefix cname prefix * @return true if the application name has this cname prefix */ protected boolean hasEnvironmentFor(String applicationName, String cnamePrefix) { return null != getEnvironmentFor(applicationName, cnamePrefix); } /** * Returns the environment description matching applicationName and environmentRef * * @param applicationName application name * @param cnamePrefix cname prefix * @return environment description */ protected EnvironmentDescription getEnvironmentFor(String applicationName, String cnamePrefix) { Collection<EnvironmentDescription> environments = getEnvironmentsFor(applicationName); String cnameToMatch = String.format("%s.elasticbeanstalk.com", cnamePrefix); /* * Finds a matching environment */ for (EnvironmentDescription envDesc : environments) { if (cnameToMatch.equals(envDesc.getCNAME())) { return envDesc; } } return null; } private String getNewEnvironmentName(String newEnvironmentName) { String result = newEnvironmentName; String environmentRadical = result; int i = 0; { Matcher matcher = PATTERN_NUMBERED.matcher(newEnvironmentName); if (matcher.matches()) { environmentRadical = matcher.group(1); i = 1 + Integer.valueOf(matcher.group(2)); } } while (containsNamedEnvironment(result) || isNamedEnvironmentUnavailable(result)) { result = formatAndTruncate("%s-%d", MAX_ENVNAME_LEN, environmentRadical, i++); } return result; } private boolean isNamedEnvironmentUnavailable(String cnamePrefix) { return !getService().checkDNSAvailability(new CheckDNSAvailabilityRequest(cnamePrefix)) .isAvailable(); } /** * Elastic Beanstalk Contains a Max EnvironmentName Limit. Lets truncate it, shall we? * * @param mask String.format Mask * @param maxLen Maximum Length * @param args String.format args * @return formatted String, or maxLen rightmost characters */ protected String formatAndTruncate(String mask, int maxLen, Object... args) { String result = String.format(mask, args); if (result.length() > maxLen) { result = result .substring(result.length() - maxLen, result.length()); } return result; } /** * Boolean predicate for named environment * * @param environmentName environment name * @return true if environment name exists */ protected boolean containsNamedEnvironment(String environmentName) { for (EnvironmentDescription envDesc : getEnvironmentsFor(applicationName)) { if (envDesc.getEnvironmentName().equals(environmentName)) { return true; } } return false; } }
Added copySolutionStack property with default value set to true to maintain existing plugin behavior. This property allows configuration of the plugin's replace env behavior https://github.com/ingenieux/beanstalker/issues/55
beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/env/ReplaceEnvironmentMojo.java
Added copySolutionStack property with default value set to true to maintain existing plugin behavior. This property allows configuration of the plugin's replace env behavior https://github.com/ingenieux/beanstalker/issues/55
<ide><path>eanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/env/ReplaceEnvironmentMojo.java <ide> @Parameter(property = "beanstalk.copyOptionSettings", defaultValue = "true") <ide> boolean copyOptionSettings = true; <ide> <add> /** <add> * Whether or not to keep the Elastic Beanstalk platform (aka solutionStack) from the old environment when replacing <add> */ <add> @Parameter(property = "beanstalk.copySolutionStack", defaultValue = "true") <add> boolean copySolutionStack = true; <add> <ide> @Override <ide> protected EnvironmentDescription handleResults( <ide> Collection<EnvironmentDescription> environments) <ide> } <ide> <ide> /* <del> * Gets the current environment using this cname <add> * Gets the current environment using this cname <ide> */ <ide> EnvironmentDescription curEnv = getEnvironmentFor(applicationName, <ide> cnamePrefix); <ide> <ide> if (getLog().isInfoEnabled()) { <ide> getLog().info( <del> "Creating a new environment on " + cnamePrefixToCreate <del> + ".elasticbeanstalk.com"); <add> "Creating a new environment on " + cnamePrefixToCreate + ".elasticbeanstalk.com"); <ide> } <ide> <ide> if (copyOptionSettings) { <ide> copyOptionSettings(curEnv); <ide> } <ide> <del> if (!solutionStack.equals(curEnv.getSolutionStackName())) { <del> if (getLog().isInfoEnabled()) { <del> getLog().warn( <add> if (!solutionStack.equals(curEnv.getSolutionStackName()) && copySolutionStack) { <add> if (getLog().isWarnEnabled()) { <add> getLog().warn( <ide> format( <del> "(btw, we're launching with solutionStack/ set to '%s' instead of the default ('%s'). " <del> + "If this is not the case, then we kindly ask you to file a bug report on the mailing list :)", <add> "(btw, we're launching with solutionStack/ set to '%s' based on the existing env instead of the " <add> + "default ('%s'). If this is not the desired behavior please set the copySolutionStack property to" <add> + " false.", <ide> curEnv.getSolutionStackName(), solutionStack)); <ide> } <ide> <ide> solutionStack = curEnv.getSolutionStackName(); <ide> } <ide> <del> String newEnvironmentName = getNewEnvironmentName(StringUtils <del> .defaultString(this.environmentName, <del> curEnv <del> .getEnvironmentName())); <add> String newEnvironmentName = getNewEnvironmentName(StringUtils.defaultString(this.environmentName, <add> curEnv.getEnvironmentName())); <ide> <ide> if (getLog().isInfoEnabled()) { <ide> getLog().info("And it'll be named " + newEnvironmentName);
Java
agpl-3.0
d2ef1e3a61450d3d2f4b2ac04ff762dcf9228397
0
PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeContainer; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.arbil.ui.ArbilTableModel; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.arbil.userstorage.ArbilSessionStorage; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.kindata.GraphSorter; import nl.mpi.kinnate.kindata.VisiblePanelSetting; import nl.mpi.kinnate.kindata.VisiblePanelSetting.PanelType; import nl.mpi.kinnate.svg.GraphPanel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.EntityService; import nl.mpi.kinnate.entityindexer.EntityServiceException; import nl.mpi.kinnate.entityindexer.QueryParser; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter; import nl.mpi.kinnate.kintypestrings.ParserHighlight; import nl.mpi.kinnate.ui.DocumentNewMenu.DocumentType; /** * Document : KinTypeStringTestPanel * Created on : Sep 29, 2010, 12:52:01 PM * Author : Peter Withers */ public class KinDiagramPanel extends JPanel implements SavePanel, KinTermSavePanel, ArbilDataNodeContainer { private EntityCollection entityCollection; private KinTypeStringInput kinTypeStringInput; private GraphPanel graphPanel; private GraphSorter graphSorter; private EgoSelectionPanel egoSelectionPanel; private HidePane kinTermHidePane; private HidePane kinTypeHidePane; private KinTermTabPane kinTermPanel; private EntityService entityIndex; private JProgressBar progressBar; public ArbilTable imdiTable; static private File defaultDiagramTemplate; private HashMap<ArbilDataNode, UniqueIdentifier> registeredArbilDataNode; private HashSet<ArbilNode> arbilDataNodesFirstLoadDone; private String defaultString = "# The kin type strings entered here will determine how the entities show on the graph below\n"; public static String defaultGraphString = "# The kin type strings entered here will determine how the entities show on the graph below\n" + "# Enter one string per line.\n" //+ "# By default all relations of the selected entity will be shown.\n" + "# for example:\n" // + "EmWMMM\n" // + "E:1:FFE\n" // + "EmWMMM:1:\n" // + "E:1:FFE\n" + "Em:Charles II of Spain:W:Marie Louise d'Orl�ans\n" + "Em:Charles II of Spain:F:Philip IV of Spain:F:Philip III of Spain:F:Philip II of Spain:F:Charles V, Holy Roman Emperor:F:Philip I of Castile\n" + "Em:Charles II of Spain:M:Mariana of Austria:M:Maria Anna of Spain:M:Margaret of Austria:M:Maria Anna of Bavaria\n" + "M:Mariana of Austria:F:Ferdinand III, Holy Roman Emperor:\n" + "F:Philip IV of Spain:M:Margaret of Austria\n" + "F:Ferdinand III, Holy Roman Emperor:\n" + "M:Maria Anna of Spain:\n" + "F:Philip III of Spain\n" + "M:Margaret of Austria\n" + "\n"; // + "FS:1:BSSWMDHFF:1:\n" // + "M:2:SSDHMFM:2:\n" // + "F:3:SSDHMF:3:\n" // + ""; // + "E=[Bob]MFM\n" // + "E=[Bob]MZ\n" // + "E=[Bob]F\n" // + "E=[Bob]M\n" // + "E=[Bob]S"; // private String kinTypeStrings[] = new String[]{}; public KinDiagramPanel(File existingFile) { initKinDiagramPanel(existingFile, null); } public KinDiagramPanel(DocumentType documentType) { initKinDiagramPanel(null, documentType); } private void initKinDiagramPanel(File existingFile, DocumentType documentType) { entityCollection = new EntityCollection(); progressBar = new JProgressBar(); EntityData[] svgStoredEntities = null; graphPanel = new GraphPanel(this); kinTypeStringInput = new KinTypeStringInput(defaultString); if (existingFile != null && existingFile.exists()) { svgStoredEntities = graphPanel.readSvg(existingFile); String kinTermContents = null; for (String currentKinTypeString : graphPanel.getKinTypeStrigs()) { if (currentKinTypeString.trim().length() > 0) { if (kinTermContents == null) { kinTermContents = ""; } else { kinTermContents = kinTermContents + "\n"; } kinTermContents = kinTermContents + currentKinTypeString.trim(); } } kinTypeStringInput.setText(kinTermContents); } else { if (documentType == null) { // this is the default document that users see when they run the application for the first time documentType = DocumentType.Simple; } boolean showKinTerms = false; boolean showArchiveLinker = false; boolean showDiagramTree = false; boolean showEntitySearch = false; boolean showIndexerSettings = false; boolean showKinTypeStrings = false; boolean showMetaData = false; switch (documentType) { case ArchiveLinker: showMetaData = true; showDiagramTree = true; showArchiveLinker = true; break; case CustomQuery: showMetaData = true; showKinTypeStrings = true; showDiagramTree = true; showIndexerSettings = true; break; case EntitySearch: showMetaData = true; showEntitySearch = true; showDiagramTree = true; break; case KinTerms: showKinTerms = true; break; case KinTypeString: // showDiagramTree = true; showKinTypeStrings = true; break; case Simple: showMetaData = true; showDiagramTree = true; break; case Query: showMetaData = true; showDiagramTree = true; showKinTypeStrings = true; default: break; } graphPanel.generateDefaultSvg(); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTerms, 150, showKinTerms); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.ArchiveLinker, 150, showArchiveLinker); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.DiagramTree, 150, showDiagramTree); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.EntitySearch, 150, showEntitySearch); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.IndexerSettings, 150, showIndexerSettings); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTypeStrings, 150, showKinTypeStrings); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.MetaData, 150, showMetaData); } this.setLayout(new BorderLayout()); ArbilTableModel imdiTableModel = new ArbilTableModel(); progressBar.setVisible(false); graphPanel.add(progressBar, BorderLayout.PAGE_START); imdiTable = new ArbilTable(imdiTableModel, "Selected Nodes"); TableCellDragHandler tableCellDragHandler = new TableCellDragHandler(); imdiTable.setTransferHandler(tableCellDragHandler); imdiTable.setDragEnabled(true); registeredArbilDataNode = new HashMap<ArbilDataNode, UniqueIdentifier>(); arbilDataNodesFirstLoadDone = new HashSet<ArbilNode>(); egoSelectionPanel = new EgoSelectionPanel(imdiTable, graphPanel); kinTermPanel = new KinTermTabPane(this, graphPanel.getkinTermGroups()); // kinTypeStringInput.setText(defaultString); JPanel kinGraphPanel = new JPanel(new BorderLayout()); kinTypeHidePane = new HidePane(HidePane.HidePanePosition.top, 0); IndexerParametersPanel indexerParametersPanel = new IndexerParametersPanel(this, graphPanel, tableCellDragHandler); // JPanel advancedPanel = new JPanel(new BorderLayout()); JScrollPane tableScrollPane = new JScrollPane(imdiTable); // advancedPanel.add(tableScrollPane, BorderLayout.CENTER); //HidePane indexParamHidePane = new HidePane(HidePane.HidePanePosition.right, 0); //advancedPanel.add(indexParamHidePane, BorderLayout.LINE_END); HidePane tableHidePane = new HidePane(HidePane.HidePanePosition.bottom, 0); KinDragTransferHandler dragTransferHandler = new KinDragTransferHandler(this); graphPanel.setTransferHandler(dragTransferHandler); egoSelectionPanel.setTransferHandler(dragTransferHandler); EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, graphPanel, imdiTable); entitySearchPanel.setTransferHandler(dragTransferHandler); HidePane egoSelectionHidePane = new HidePane(HidePane.HidePanePosition.left, 0); kinTermHidePane = new HidePane(HidePane.HidePanePosition.right, 0); graphPanel.setArbilTableModel(imdiTableModel, tableHidePane); for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) { switch (panelSetting.getPanelType()) { case ArchiveLinker: panelSetting.setTargetPanel(kinTermHidePane, new ArchiveEntityLinkerPanel(imdiTable, dragTransferHandler), "Archive Linker"); break; case DiagramTree: panelSetting.setTargetPanel(egoSelectionHidePane, egoSelectionPanel, "Diagram Tree"); break; case EntitySearch: panelSetting.setTargetPanel(kinTermHidePane, entitySearchPanel, "Search Entities"); break; case IndexerSettings: panelSetting.setTargetPanel(kinTypeHidePane, indexerParametersPanel, "Indexer Parameters"); break; case KinTerms: panelSetting.setTargetPanel(kinTermHidePane, kinTermPanel, "Kin Terms"); break; case KinTypeStrings: panelSetting.setTargetPanel(kinTypeHidePane, new JScrollPane(kinTypeStringInput), "Kin Type Strings"); break; case MetaData: panelSetting.setTargetPanel(tableHidePane, tableScrollPane, "Metadata"); break; } } tableHidePane.toggleHiddenState(); // put the metadata table plane into the closed state kinGraphPanel.add(kinTypeHidePane, BorderLayout.PAGE_START); kinGraphPanel.add(egoSelectionHidePane, BorderLayout.LINE_START); kinGraphPanel.add(graphPanel, BorderLayout.CENTER); kinGraphPanel.add(kinTermHidePane, BorderLayout.LINE_END); kinGraphPanel.add(tableHidePane, BorderLayout.PAGE_END); this.add(kinGraphPanel); entityIndex = new QueryParser(svgStoredEntities); graphSorter = new GraphSorter(); kinTypeStringInput.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { synchronized (e) { redrawIfKinTermsChanged(); } } }); } static public File getDefaultDiagramFile() { if (defaultDiagramTemplate == null) { defaultDiagramTemplate = new File(ArbilSessionStorage.getSingleInstance().getStorageDirectory(), "DefaultKinDiagram.svg"); } return defaultDiagramTemplate; } public void redrawIfKinTermsChanged() { if (kinTypeStringInput.hasChanges()) { graphPanel.setKinTypeStrigs(kinTypeStringInput.getCurrentStrings()); drawGraph(); } } boolean graphThreadRunning = false; boolean graphUpdateRequired = false; public synchronized void drawGraph() { graphUpdateRequired = true; if (!graphThreadRunning) { graphThreadRunning = true; new Thread() { @Override public void run() { // todo: there are probably other synchronisation issues to resolve here. while (graphUpdateRequired) { graphUpdateRequired = false; try { String[] kinTypeStrings = graphPanel.getKinTypeStrigs(); ParserHighlight[] parserHighlight = new ParserHighlight[kinTypeStrings.length]; progressBar.setValue(0); progressBar.setVisible(true); boolean isQuery = false; if (!graphPanel.dataStoreSvg.egoEntities.isEmpty() || !graphPanel.dataStoreSvg.requiredEntities.isEmpty()) { isQuery = true; } else { for (String currentLine : kinTypeStrings) { if (currentLine.contains("=")) { isQuery = true; break; } } } if (isQuery) { EntityData[] graphNodes = entityIndex.processKinTypeStrings(null, graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, kinTypeStrings, parserHighlight, graphPanel.getIndexParameters(), progressBar); graphSorter.setEntitys(graphNodes); // register interest Arbil updates and update the graph when data is edited in the table // registerCurrentNodes(graphSorter.getDataNodes()); graphPanel.drawNodes(graphSorter); egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes(), graphPanel.getIndexParameters()); } else { KinTypeStringConverter graphData = new KinTypeStringConverter(); graphData.readKinTypes(kinTypeStrings, graphPanel.getkinTermGroups(), graphPanel.dataStoreSvg, parserHighlight); graphPanel.drawNodes(graphData); egoSelectionPanel.setTransientNodes(graphData.getDataNodes()); // KinDiagramPanel.this.doLayout(); } kinTypeStringInput.highlightKinTerms(parserHighlight, kinTypeStrings); // kinTypeStrings = graphPanel.getKinTypeStrigs(); } catch (EntityServiceException exception) { GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to load all entities required", "Draw Graph"); } progressBar.setVisible(false); } graphThreadRunning = false; } }.start(); } } // @Deprecated // public void setDisplayNodes(String typeString, String[] egoIdentifierArray) { // // todo: should this be replaced by the required nodes? // if (kinTypeStringInput.getText().equals(defaultString)) { // kinTypeStringInput.setText(""); // } // String kinTermContents = kinTypeStringInput.getText(); // for (String currentId : egoIdentifierArray) { // kinTermContents = kinTermContents + typeString + "=[" + currentId + "]\n"; // } // kinTypeStringInput.setText(kinTermContents); // graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n")); //// kinTypeStrings = graphPanel.getKinTypeStrigs(); // drawGraph(); // } public void setEgoNodes(UniqueIdentifier[] egoIdentifierArray) { // todo: this does not update the ego highlight on the graph and the trees. graphPanel.dataStoreSvg.egoEntities = new HashSet<UniqueIdentifier>(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void addEgoNodes(UniqueIdentifier[] egoIdentifierArray) { // todo: this does not update the ego highlight on the graph and the trees. graphPanel.dataStoreSvg.egoEntities.addAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void removeEgoNodes(UniqueIdentifier[] egoIdentifierArray) { // todo: this does not update the ego highlight on the graph and the trees. graphPanel.dataStoreSvg.egoEntities.removeAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void addRequiredNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void removeRequiredNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.requiredEntities.removeAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public boolean hasSaveFileName() { return (graphPanel.hasSaveFileName() && getDefaultDiagramFile() != graphPanel.getFileName()); } public File getFileName() { return graphPanel.getFileName(); } public boolean requiresSave() { return graphPanel.requiresSave(); } public void setRequiresSave() { graphPanel.setRequiresSave(); } public void saveToFile() { graphPanel.saveToFile(); } public void saveToFile(File saveFile) { graphPanel.saveToFile(saveFile); } public void updateGraph() { this.drawGraph(); } public void exportKinTerms() { kinTermPanel.getSelectedKinTermPanel().exportKinTerms(); } public void hideShow() { kinTermHidePane.toggleHiddenState(); } public void importKinTerms() { kinTermPanel.getSelectedKinTermPanel().importKinTerms(); } public void addKinTermGroup() { graphPanel.addKinTermGroup(); kinTermPanel.updateKinTerms(graphPanel.getkinTermGroups()); } public VisiblePanelSetting[] getVisiblePanels() { return graphPanel.dataStoreSvg.getVisiblePanels(); } public void setPanelState(PanelType panelType, int panelWidth, boolean panelVisible) { // todo: show / hide the requested panel graphPanel.dataStoreSvg.setPanelState(panelType, panelWidth, panelVisible); } public void setSelectedKinTypeSting(String kinTypeStrings) { kinTermPanel.setAddableKinTypeSting(kinTypeStrings); } public boolean isHidden() { return kinTermHidePane.isHidden(); } public EntityData[] getGraphEntities() { return graphSorter.getDataNodes(); } public void registerArbilNode(UniqueIdentifier uniqueIdentifier, ArbilDataNode arbilDataNode) { // todo: i think this is resolved but double check the issue where arbil nodes update frequency is too high and breaks basex // todo: load the nodes in the KinDataNode when putting them in the table and pass on the reload requests here when they occur // todo: replace the data node registering process. // for (EntityData entityData : currentEntities) { // ArbilDataNode arbilDataNode = null; if (!registeredArbilDataNode.containsKey(arbilDataNode)) { arbilDataNode.registerContainer(this); registeredArbilDataNode.put(arbilDataNode, uniqueIdentifier); } // try { // String metadataPath = entityData.getEntityPath(); // if (metadataPath != null) { // // todo: this should not load the arbil node only register an interest //// and this needs to be tested // arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNodeWithoutLoading(new URI(metadataPath)); // registeredArbilDataNode.put(entityData.getUniqueIdentifier(), arbilDataNode); // arbilDataNode.registerContainer(this); // // todo: keep track of registered nodes and remove the unrequired ones here // } else { // GuiHelper.linorgBugCatcher.logError(new Exception("Error getting path for: " + entityData.getUniqueIdentifier().getAttributeIdentifier() + " : " + entityData.getLabel()[0])); // } // } catch (URISyntaxException exception) { // GuiHelper.linorgBugCatcher.logError(exception); // } // } else { // arbilDataNode = registeredArbilDataNode.get(entityData.getUniqueIdentifier()); // } // if (arbilDataNode != null) { // entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false); // } // } } public void entityRelationsChanged(UniqueIdentifier[] selectedIdentifiers) { // this method does not need to update the database because the link changing process has already done that // remove the stored graph locations of the selected ids graphPanel.clearEntityLocations(selectedIdentifiers); graphPanel.getIndexParameters().valuesChanged = true; drawGraph(); } public void dataNodeIconCleared(ArbilNode arbilNode) { if (arbilDataNodesFirstLoadDone.contains(arbilNode)) { // todo: this needs to be updated to be multi threaded so users can link or save multiple nodes at once boolean dataBaseRequiresUpdate = false; boolean redrawRequired = false; if (arbilNode instanceof ArbilDataNode) { ArbilDataNode arbilDataNode = (ArbilDataNode) arbilNode; UniqueIdentifier uniqueIdentifier = registeredArbilDataNode.get(arbilDataNode); // find the entity data for this arbil data node for (EntityData entityData : graphSorter.getDataNodes()) { if (entityData.getUniqueIdentifier().equals(uniqueIdentifier)) { // check if the metadata has been changed // todo: something here fails to act on multiple nodes that have changed (it is the db update that was missed) if (entityData.metadataRequiresSave && !arbilDataNode.getNeedsSaveToDisk(false)) { dataBaseRequiresUpdate = true; redrawRequired = true; } // clear or set the needs save flag entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false); if (entityData.metadataRequiresSave) { redrawRequired = true; } } } if (dataBaseRequiresUpdate) { entityCollection.updateDatabase(arbilDataNode.getURI()); graphPanel.getIndexParameters().valuesChanged = true; } } if (redrawRequired) { drawGraph(); } } if (!arbilNode.isLoading()) { // this is to make sure that the initial loading process does not cause db updates nor graph redraws arbilDataNodesFirstLoadDone.add(arbilNode); } } public void dataNodeChildAdded(ArbilNode destination, ArbilNode newChildNode) { throw new UnsupportedOperationException("Not supported yet."); } public void dataNodeRemoved(ArbilNode adn) { throw new UnsupportedOperationException("Not supported yet."); } }
desktop/src/main/java/nl/mpi/kinnate/ui/KinDiagramPanel.java
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeContainer; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.arbil.ui.ArbilTableModel; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.arbil.userstorage.ArbilSessionStorage; import nl.mpi.kinnate.KinTermSavePanel; import nl.mpi.kinnate.kindata.GraphSorter; import nl.mpi.kinnate.kindata.VisiblePanelSetting; import nl.mpi.kinnate.kindata.VisiblePanelSetting.PanelType; import nl.mpi.kinnate.svg.GraphPanel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.EntityService; import nl.mpi.kinnate.entityindexer.EntityServiceException; import nl.mpi.kinnate.entityindexer.QueryParser; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter; import nl.mpi.kinnate.kintypestrings.ParserHighlight; import nl.mpi.kinnate.ui.DocumentNewMenu.DocumentType; /** * Document : KinTypeStringTestPanel * Created on : Sep 29, 2010, 12:52:01 PM * Author : Peter Withers */ public class KinDiagramPanel extends JPanel implements SavePanel, KinTermSavePanel, ArbilDataNodeContainer { private EntityCollection entityCollection; private KinTypeStringInput kinTypeStringInput; private GraphPanel graphPanel; private GraphSorter graphSorter; private EgoSelectionPanel egoSelectionPanel; private HidePane kinTermHidePane; private HidePane kinTypeHidePane; private KinTermTabPane kinTermPanel; private EntityService entityIndex; private JProgressBar progressBar; public ArbilTable imdiTable; static private File defaultDiagramTemplate; private HashMap<ArbilDataNode, UniqueIdentifier> registeredArbilDataNode; private HashSet<ArbilNode> arbilDataNodesFirstLoadDone; private String defaultString = "# The kin type strings entered here will determine how the entities show on the graph below\n"; public static String defaultGraphString = "# The kin type strings entered here will determine how the entities show on the graph below\n" + "# Enter one string per line.\n" //+ "# By default all relations of the selected entity will be shown.\n" + "# for example:\n" // + "EmWMMM\n" // + "E:1:FFE\n" // + "EmWMMM:1:\n" // + "E:1:FFE\n" + "Em:Charles II of Spain:W:Marie Louise d'Orl�ans\n" + "Em:Charles II of Spain:F:Philip IV of Spain:F:Philip III of Spain:F:Philip II of Spain:F:Charles V, Holy Roman Emperor:F:Philip I of Castile\n" + "Em:Charles II of Spain:M:Mariana of Austria:M:Maria Anna of Spain:M:Margaret of Austria:M:Maria Anna of Bavaria\n" + "M:Mariana of Austria:F:Ferdinand III, Holy Roman Emperor:\n" + "F:Philip IV of Spain:M:Margaret of Austria\n" + "F:Ferdinand III, Holy Roman Emperor:\n" + "M:Maria Anna of Spain:\n" + "F:Philip III of Spain\n" + "M:Margaret of Austria\n" + "\n"; // + "FS:1:BSSWMDHFF:1:\n" // + "M:2:SSDHMFM:2:\n" // + "F:3:SSDHMF:3:\n" // + ""; // + "E=[Bob]MFM\n" // + "E=[Bob]MZ\n" // + "E=[Bob]F\n" // + "E=[Bob]M\n" // + "E=[Bob]S"; // private String kinTypeStrings[] = new String[]{}; public KinDiagramPanel(File existingFile) { initKinDiagramPanel(existingFile, null); } public KinDiagramPanel(DocumentType documentType) { initKinDiagramPanel(null, documentType); } private void initKinDiagramPanel(File existingFile, DocumentType documentType) { entityCollection = new EntityCollection(); progressBar = new JProgressBar(); EntityData[] svgStoredEntities = null; graphPanel = new GraphPanel(this); kinTypeStringInput = new KinTypeStringInput(defaultString); if (existingFile != null && existingFile.exists()) { svgStoredEntities = graphPanel.readSvg(existingFile); String kinTermContents = null; for (String currentKinTypeString : graphPanel.getKinTypeStrigs()) { if (currentKinTypeString.trim().length() > 0) { if (kinTermContents == null) { kinTermContents = ""; } else { kinTermContents = kinTermContents + "\n"; } kinTermContents = kinTermContents + currentKinTypeString.trim(); } } kinTypeStringInput.setText(kinTermContents); } else { if (documentType == null) { // this is the default document that users see when they run the application for the first time documentType = DocumentType.Simple; } boolean showKinTerms = false; boolean showArchiveLinker = false; boolean showDiagramTree = false; boolean showEntitySearch = false; boolean showIndexerSettings = false; boolean showKinTypeStrings = false; boolean showMetaData = false; switch (documentType) { case ArchiveLinker: showMetaData = true; showDiagramTree = true; showArchiveLinker = true; break; case CustomQuery: showMetaData = true; showKinTypeStrings = true; showDiagramTree = true; showIndexerSettings = true; break; case EntitySearch: showMetaData = true; showEntitySearch = true; showDiagramTree = true; break; case KinTerms: showKinTerms = true; break; case KinTypeString: // showDiagramTree = true; showKinTypeStrings = true; break; case Simple: showMetaData = true; showDiagramTree = true; break; case Query: showMetaData = true; showDiagramTree = true; showKinTypeStrings = true; default: break; } graphPanel.generateDefaultSvg(); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTerms, 150, showKinTerms); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.ArchiveLinker, 150, showArchiveLinker); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.DiagramTree, 150, showDiagramTree); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.EntitySearch, 150, showEntitySearch); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.IndexerSettings, 150, showIndexerSettings); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTypeStrings, 150, showKinTypeStrings); graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.MetaData, 150, showMetaData); } this.setLayout(new BorderLayout()); ArbilTableModel imdiTableModel = new ArbilTableModel(); progressBar.setVisible(false); graphPanel.add(progressBar, BorderLayout.PAGE_START); imdiTable = new ArbilTable(imdiTableModel, "Selected Nodes"); TableCellDragHandler tableCellDragHandler = new TableCellDragHandler(); imdiTable.setTransferHandler(tableCellDragHandler); imdiTable.setDragEnabled(true); registeredArbilDataNode = new HashMap<ArbilDataNode, UniqueIdentifier>(); arbilDataNodesFirstLoadDone = new HashSet<ArbilNode>(); egoSelectionPanel = new EgoSelectionPanel(imdiTable, graphPanel); kinTermPanel = new KinTermTabPane(this, graphPanel.getkinTermGroups()); // kinTypeStringInput.setText(defaultString); JPanel kinGraphPanel = new JPanel(new BorderLayout()); kinTypeHidePane = new HidePane(HidePane.HidePanePosition.top, 0); IndexerParametersPanel indexerParametersPanel = new IndexerParametersPanel(this, graphPanel, tableCellDragHandler); // JPanel advancedPanel = new JPanel(new BorderLayout()); JScrollPane tableScrollPane = new JScrollPane(imdiTable); // advancedPanel.add(tableScrollPane, BorderLayout.CENTER); //HidePane indexParamHidePane = new HidePane(HidePane.HidePanePosition.right, 0); //advancedPanel.add(indexParamHidePane, BorderLayout.LINE_END); HidePane tableHidePane = new HidePane(HidePane.HidePanePosition.bottom, 0); KinDragTransferHandler dragTransferHandler = new KinDragTransferHandler(this); graphPanel.setTransferHandler(dragTransferHandler); egoSelectionPanel.setTransferHandler(dragTransferHandler); EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, graphPanel, imdiTable); entitySearchPanel.setTransferHandler(dragTransferHandler); HidePane egoSelectionHidePane = new HidePane(HidePane.HidePanePosition.left, 0); kinTermHidePane = new HidePane(HidePane.HidePanePosition.right, 0); graphPanel.setArbilTableModel(imdiTableModel, tableHidePane); for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) { switch (panelSetting.getPanelType()) { case ArchiveLinker: panelSetting.setTargetPanel(kinTermHidePane, new ArchiveEntityLinkerPanel(imdiTable, dragTransferHandler), "Archive Linker"); break; case DiagramTree: panelSetting.setTargetPanel(egoSelectionHidePane, egoSelectionPanel, "Diagram Tree"); break; case EntitySearch: panelSetting.setTargetPanel(egoSelectionHidePane, entitySearchPanel, "Search Entities"); break; case IndexerSettings: panelSetting.setTargetPanel(kinTypeHidePane, indexerParametersPanel, "Indexer Parameters"); break; case KinTerms: panelSetting.setTargetPanel(kinTermHidePane, kinTermPanel, "Kin Terms"); break; case KinTypeStrings: panelSetting.setTargetPanel(kinTypeHidePane, new JScrollPane(kinTypeStringInput), "Kin Type Strings"); break; case MetaData: panelSetting.setTargetPanel(tableHidePane, tableScrollPane, "Metadata"); break; } } tableHidePane.toggleHiddenState(); // put the metadata table plane into the closed state kinGraphPanel.add(kinTypeHidePane, BorderLayout.PAGE_START); kinGraphPanel.add(egoSelectionHidePane, BorderLayout.LINE_START); kinGraphPanel.add(graphPanel, BorderLayout.CENTER); kinGraphPanel.add(kinTermHidePane, BorderLayout.LINE_END); kinGraphPanel.add(tableHidePane, BorderLayout.PAGE_END); this.add(kinGraphPanel); entityIndex = new QueryParser(svgStoredEntities); graphSorter = new GraphSorter(); kinTypeStringInput.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { synchronized (e) { redrawIfKinTermsChanged(); } } }); } static public File getDefaultDiagramFile() { if (defaultDiagramTemplate == null) { defaultDiagramTemplate = new File(ArbilSessionStorage.getSingleInstance().getStorageDirectory(), "DefaultKinDiagram.svg"); } return defaultDiagramTemplate; } public void redrawIfKinTermsChanged() { if (kinTypeStringInput.hasChanges()) { graphPanel.setKinTypeStrigs(kinTypeStringInput.getCurrentStrings()); drawGraph(); } } boolean graphThreadRunning = false; boolean graphUpdateRequired = false; public synchronized void drawGraph() { graphUpdateRequired = true; if (!graphThreadRunning) { graphThreadRunning = true; new Thread() { @Override public void run() { // todo: there are probably other synchronisation issues to resolve here. while (graphUpdateRequired) { graphUpdateRequired = false; try { String[] kinTypeStrings = graphPanel.getKinTypeStrigs(); ParserHighlight[] parserHighlight = new ParserHighlight[kinTypeStrings.length]; progressBar.setValue(0); progressBar.setVisible(true); boolean isQuery = false; if (!graphPanel.dataStoreSvg.egoEntities.isEmpty() || !graphPanel.dataStoreSvg.requiredEntities.isEmpty()) { isQuery = true; } else { for (String currentLine : kinTypeStrings) { if (currentLine.contains("=")) { isQuery = true; break; } } } if (isQuery) { EntityData[] graphNodes = entityIndex.processKinTypeStrings(null, graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, kinTypeStrings, parserHighlight, graphPanel.getIndexParameters(), progressBar); graphSorter.setEntitys(graphNodes); // register interest Arbil updates and update the graph when data is edited in the table // registerCurrentNodes(graphSorter.getDataNodes()); graphPanel.drawNodes(graphSorter); egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes()); } else { KinTypeStringConverter graphData = new KinTypeStringConverter(); graphData.readKinTypes(kinTypeStrings, graphPanel.getkinTermGroups(), graphPanel.dataStoreSvg, parserHighlight); graphPanel.drawNodes(graphData); egoSelectionPanel.setTransientNodes(graphData.getDataNodes()); // KinDiagramPanel.this.doLayout(); } kinTypeStringInput.highlightKinTerms(parserHighlight, kinTypeStrings); // kinTypeStrings = graphPanel.getKinTypeStrigs(); } catch (EntityServiceException exception) { GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to load all entities required", "Draw Graph"); } progressBar.setVisible(false); } graphThreadRunning = false; } }.start(); } } // @Deprecated // public void setDisplayNodes(String typeString, String[] egoIdentifierArray) { // // todo: should this be replaced by the required nodes? // if (kinTypeStringInput.getText().equals(defaultString)) { // kinTypeStringInput.setText(""); // } // String kinTermContents = kinTypeStringInput.getText(); // for (String currentId : egoIdentifierArray) { // kinTermContents = kinTermContents + typeString + "=[" + currentId + "]\n"; // } // kinTypeStringInput.setText(kinTermContents); // graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n")); //// kinTypeStrings = graphPanel.getKinTypeStrigs(); // drawGraph(); // } public void setEgoNodes(UniqueIdentifier[] egoIdentifierArray) { // todo: this does not update the ego highlight on the graph and the trees. graphPanel.dataStoreSvg.egoEntities = new HashSet<UniqueIdentifier>(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void addEgoNodes(UniqueIdentifier[] egoIdentifierArray) { // todo: this does not update the ego highlight on the graph and the trees. graphPanel.dataStoreSvg.egoEntities.addAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void removeEgoNodes(UniqueIdentifier[] egoIdentifierArray) { // todo: this does not update the ego highlight on the graph and the trees. graphPanel.dataStoreSvg.egoEntities.removeAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void addRequiredNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public void removeRequiredNodes(UniqueIdentifier[] egoIdentifierArray) { graphPanel.dataStoreSvg.requiredEntities.removeAll(Arrays.asList(egoIdentifierArray)); drawGraph(); } public boolean hasSaveFileName() { return (graphPanel.hasSaveFileName() && getDefaultDiagramFile() != graphPanel.getFileName()); } public File getFileName() { return graphPanel.getFileName(); } public boolean requiresSave() { return graphPanel.requiresSave(); } public void setRequiresSave() { graphPanel.setRequiresSave(); } public void saveToFile() { graphPanel.saveToFile(); } public void saveToFile(File saveFile) { graphPanel.saveToFile(saveFile); } public void updateGraph() { this.drawGraph(); } public void exportKinTerms() { kinTermPanel.getSelectedKinTermPanel().exportKinTerms(); } public void hideShow() { kinTermHidePane.toggleHiddenState(); } public void importKinTerms() { kinTermPanel.getSelectedKinTermPanel().importKinTerms(); } public void addKinTermGroup() { graphPanel.addKinTermGroup(); kinTermPanel.updateKinTerms(graphPanel.getkinTermGroups()); } public VisiblePanelSetting[] getVisiblePanels() { return graphPanel.dataStoreSvg.getVisiblePanels(); } public void setPanelState(PanelType panelType, int panelWidth, boolean panelVisible) { // todo: show / hide the requested panel graphPanel.dataStoreSvg.setPanelState(panelType, panelWidth, panelVisible); } public void setSelectedKinTypeSting(String kinTypeStrings) { kinTermPanel.setAddableKinTypeSting(kinTypeStrings); } public boolean isHidden() { return kinTermHidePane.isHidden(); } public EntityData[] getGraphEntities() { return graphSorter.getDataNodes(); } public void registerArbilNode(UniqueIdentifier uniqueIdentifier, ArbilDataNode arbilDataNode) { // todo: i think this is resolved but double check the issue where arbil nodes update frequency is too high and breaks basex // todo: load the nodes in the KinDataNode when putting them in the table and pass on the reload requests here when they occur // todo: replace the data node registering process. // for (EntityData entityData : currentEntities) { // ArbilDataNode arbilDataNode = null; if (!registeredArbilDataNode.containsKey(arbilDataNode)) { arbilDataNode.registerContainer(this); registeredArbilDataNode.put(arbilDataNode, uniqueIdentifier); } // try { // String metadataPath = entityData.getEntityPath(); // if (metadataPath != null) { // // todo: this should not load the arbil node only register an interest //// and this needs to be tested // arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNodeWithoutLoading(new URI(metadataPath)); // registeredArbilDataNode.put(entityData.getUniqueIdentifier(), arbilDataNode); // arbilDataNode.registerContainer(this); // // todo: keep track of registered nodes and remove the unrequired ones here // } else { // GuiHelper.linorgBugCatcher.logError(new Exception("Error getting path for: " + entityData.getUniqueIdentifier().getAttributeIdentifier() + " : " + entityData.getLabel()[0])); // } // } catch (URISyntaxException exception) { // GuiHelper.linorgBugCatcher.logError(exception); // } // } else { // arbilDataNode = registeredArbilDataNode.get(entityData.getUniqueIdentifier()); // } // if (arbilDataNode != null) { // entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false); // } // } } public void entityRelationsChanged(UniqueIdentifier[] selectedIdentifiers) { // this method does not need to update the database because the link changing process has already done that // remove the stored graph locations of the selected ids graphPanel.clearEntityLocations(selectedIdentifiers); graphPanel.getIndexParameters().valuesChanged = true; drawGraph(); } public void dataNodeIconCleared(ArbilNode arbilNode) { if (arbilDataNodesFirstLoadDone.contains(arbilNode)) { // todo: this needs to be updated to be multi threaded so users can link or save multiple nodes at once boolean dataBaseRequiresUpdate = false; boolean redrawRequired = false; if (arbilNode instanceof ArbilDataNode) { ArbilDataNode arbilDataNode = (ArbilDataNode) arbilNode; UniqueIdentifier uniqueIdentifier = registeredArbilDataNode.get(arbilDataNode); // find the entity data for this arbil data node for (EntityData entityData : graphSorter.getDataNodes()) { if (entityData.getUniqueIdentifier().equals(uniqueIdentifier)) { // check if the metadata has been changed // todo: something here fails to act on multiple nodes that have changed (it is the db update that was missed) if (entityData.metadataRequiresSave && !arbilDataNode.getNeedsSaveToDisk(false)) { dataBaseRequiresUpdate = true; redrawRequired = true; } // clear or set the needs save flag entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false); if (entityData.metadataRequiresSave) { redrawRequired = true; } } } if (dataBaseRequiresUpdate) { entityCollection.updateDatabase(arbilDataNode.getURI()); graphPanel.getIndexParameters().valuesChanged = true; } } if (redrawRequired) { drawGraph(); } } if (!arbilNode.isLoading()) { // this is to make sure that the initial loading process does not cause db updates nor graph redraws arbilDataNodesFirstLoadDone.add(arbilNode); } } public void dataNodeChildAdded(ArbilNode destination, ArbilNode newChildNode) { throw new UnsupportedOperationException("Not supported yet."); } public void dataNodeRemoved(ArbilNode adn) { throw new UnsupportedOperationException("Not supported yet."); } }
Synchronised the database access. Allowed the tree to initiate data node loading from the database so that relatives that are not on the graph can be browsed in and add from the tree.
desktop/src/main/java/nl/mpi/kinnate/ui/KinDiagramPanel.java
Synchronised the database access. Allowed the tree to initiate data node loading from the database so that relatives that are not on the graph can be browsed in and add from the tree.
<ide><path>esktop/src/main/java/nl/mpi/kinnate/ui/KinDiagramPanel.java <ide> panelSetting.setTargetPanel(egoSelectionHidePane, egoSelectionPanel, "Diagram Tree"); <ide> break; <ide> case EntitySearch: <del> panelSetting.setTargetPanel(egoSelectionHidePane, entitySearchPanel, "Search Entities"); <add> panelSetting.setTargetPanel(kinTermHidePane, entitySearchPanel, "Search Entities"); <ide> break; <ide> case IndexerSettings: <ide> panelSetting.setTargetPanel(kinTypeHidePane, indexerParametersPanel, "Indexer Parameters"); <ide> // register interest Arbil updates and update the graph when data is edited in the table <ide> // registerCurrentNodes(graphSorter.getDataNodes()); <ide> graphPanel.drawNodes(graphSorter); <del> egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes()); <add> egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes(), graphPanel.getIndexParameters()); <ide> } else { <ide> KinTypeStringConverter graphData = new KinTypeStringConverter(); <ide> graphData.readKinTypes(kinTypeStrings, graphPanel.getkinTermGroups(), graphPanel.dataStoreSvg, parserHighlight);
Java
apache-2.0
6f98b12f933e3fb27a289772b4ed10a82c96d72d
0
taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language
package org.purl.wf4ever.robundle.fs; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestBundleFileSystem { private BundleFileSystem fs; @Before public void newFS() throws Exception { fs = BundleFileSystemProvider.newFileSystemFromTemporary(); // System.out.println(fs.getSource()); } @After public void closeFS() throws IOException { fs.close(); Files.deleteIfExists(fs.getSource()); } /** * Test that BundleFileSystem does not allow a ZIP file to also become a * directory. See http://stackoverflow.com/questions/16588321/ as Java 7'z * ZIPFS normally allows this (!) * * @throws Exception */ @Test public void fileAndDirectory() throws Exception { Path folder = fs.getPath("folder"); assertFalse(Files.exists(folder)); Files.createFile(folder); assertTrue(Files.exists(folder)); assertTrue(Files.isRegularFile(folder)); assertFalse(Files.isDirectory(folder)); try { Files.createDirectory(folder); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } assertFalse(Files.isDirectory(folder)); try { Files.createDirectories(folder); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } Path child = folder.resolve("child"); try { Files.createFile(child); fail("Should have thrown NotDirectoryException"); } catch (NotDirectoryException ex) { } assertFalse(Files.exists(child)); assertTrue(Files.isRegularFile(folder)); assertFalse(Files.isDirectory(folder)); assertFalse(Files.isDirectory(child.getParent())); assertFalse(Files.isDirectory(fs.getPath("folder/"))); } /** * Test that BundleFileSystem does not allow a ZIP directory to also become * a file. See http://stackoverflow.com/questions/16588321/ as Java 7'z * ZIPFS normally allows this (!) * * @throws Exception */ @Test public void directoryAndFile() throws Exception { Path folderSlash = fs.getPath("folder/"); assertFalse(Files.exists(folderSlash)); Files.createDirectory(folderSlash); assertTrue(Files.exists(folderSlash)); assertFalse(Files.isRegularFile(folderSlash)); assertTrue(Files.isDirectory(folderSlash)); try { Files.createDirectory(folderSlash); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } try { Files.createFile(folderSlash); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } Path folder = fs.getPath("folder"); try { Files.createFile(folder); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } Path child = folderSlash.resolve("child"); Files.createFile(child); assertTrue(Files.exists(folder)); assertTrue(Files.exists(folderSlash)); assertFalse(Files.isRegularFile(folder)); assertFalse(Files.isRegularFile(folderSlash)); assertTrue(Files.isDirectory(folder)); assertTrue(Files.isDirectory(folderSlash)); } }
src/test/java/org/purl/wf4ever/robundle/fs/TestBundleFileSystem.java
package org.purl.wf4ever.robundle.fs; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestBundleFileSystem { private BundleFileSystem fs; @Before public void newFS() throws Exception { fs = BundleFileSystemProvider.newFileSystemFromTemporary(); // System.out.println(fs.getSource()); } @After public void closeFS() throws IOException { fs.close(); Files.deleteIfExists(fs.getSource()); } /** * Test that BundleFileSystem does not allow a ZIP file to also become a * directory. See http://stackoverflow.com/questions/16588321/ as Java 7'z * ZIPFS normally allows this (!) * * @throws Exception */ @Test public void fileAndDirectory() throws Exception { Path folder = fs.getPath("folder"); assertFalse(Files.exists(folder)); Files.createFile(folder); assertTrue(Files.exists(folder)); assertTrue(Files.isRegularFile(folder)); assertFalse(Files.isDirectory(folder)); try { Files.createDirectory(folder); // Disable for now, just to see where this leads fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } assertFalse(Files.isDirectory(folder)); try { Files.createDirectories(folder); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } Path child = folder.resolve("child"); try { Files.createFile(child); fail("Should have thrown NotDirectoryException"); } catch (NotDirectoryException ex) { } assertFalse(Files.exists(child)); assertTrue(Files.isRegularFile(folder)); assertFalse(Files.isDirectory(folder)); assertFalse(Files.isDirectory(child.getParent())); assertFalse(Files.isDirectory(fs.getPath("folder/"))); } /** * Test that BundleFileSystem does not allow a ZIP directory to also become * a file. See http://stackoverflow.com/questions/16588321/ as Java 7'z * ZIPFS normally allows this (!) * * @throws Exception */ @Test public void directoryAndFile() throws Exception { Path folder = fs.getPath("folder/"); assertFalse(Files.exists(folder)); Files.createDirectory(folder); assertTrue(Files.exists(folder)); assertFalse(Files.isRegularFile(folder)); assertTrue(Files.isDirectory(folder)); try { Files.createDirectory(folder); fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } try { Files.createFile(folder); // Disable for now, just to see where this leads fail("Should have thrown FileAlreadyExistsException"); } catch (FileAlreadyExistsException ex) { } Path child = folder.resolve("child"); Files.createFile(child); assertTrue(Files.isRegularFile(folder)); assertFalse(Files.isDirectory(fs.getPath("folder/"))); } }
Expected behavour for fileAndDirectory and directoryAndFile
src/test/java/org/purl/wf4ever/robundle/fs/TestBundleFileSystem.java
Expected behavour for fileAndDirectory and directoryAndFile
<ide><path>rc/test/java/org/purl/wf4ever/robundle/fs/TestBundleFileSystem.java <ide> <ide> try { <ide> Files.createDirectory(folder); <del> // Disable for now, just to see where this leads <ide> fail("Should have thrown FileAlreadyExistsException"); <ide> } catch (FileAlreadyExistsException ex) { <ide> } <ide> */ <ide> @Test <ide> public void directoryAndFile() throws Exception { <del> Path folder = fs.getPath("folder/"); <del> assertFalse(Files.exists(folder)); <add> Path folderSlash = fs.getPath("folder/"); <add> assertFalse(Files.exists(folderSlash)); <ide> <del> Files.createDirectory(folder); <del> assertTrue(Files.exists(folder)); <del> assertFalse(Files.isRegularFile(folder)); <del> assertTrue(Files.isDirectory(folder)); <add> Files.createDirectory(folderSlash); <add> assertTrue(Files.exists(folderSlash)); <add> assertFalse(Files.isRegularFile(folderSlash)); <add> assertTrue(Files.isDirectory(folderSlash)); <ide> <ide> try { <del> Files.createDirectory(folder); <add> Files.createDirectory(folderSlash); <ide> fail("Should have thrown FileAlreadyExistsException"); <ide> } catch (FileAlreadyExistsException ex) { <ide> } <ide> <ide> try { <del> Files.createFile(folder); <del> // Disable for now, just to see where this leads <add> Files.createFile(folderSlash); <ide> fail("Should have thrown FileAlreadyExistsException"); <ide> } catch (FileAlreadyExistsException ex) { <ide> } <ide> <del> Path child = folder.resolve("child"); <add> Path folder = fs.getPath("folder"); <add> try { <add> Files.createFile(folder); <add> fail("Should have thrown FileAlreadyExistsException"); <add> } catch (FileAlreadyExistsException ex) { <add> } <add> <add> Path child = folderSlash.resolve("child"); <ide> Files.createFile(child); <ide> <del> assertTrue(Files.isRegularFile(folder)); <del> assertFalse(Files.isDirectory(fs.getPath("folder/"))); <add> assertTrue(Files.exists(folder)); <add> assertTrue(Files.exists(folderSlash)); <add> <add> assertFalse(Files.isRegularFile(folder)); <add> assertFalse(Files.isRegularFile(folderSlash)); <add> <add> assertTrue(Files.isDirectory(folder)); <add> assertTrue(Files.isDirectory(folderSlash)); <add> <add> <ide> } <ide> <ide> }
JavaScript
mit
6072a6cb984ebe105ca2346729500ee797ca2353
0
c933103/KC3Kai,Tibo442/KC3Kai,dragonjet/KC3Kai,Madobe/KC3Kai,Madobe/KC3Kai,jy19/KC3Kai,Slayers148/KC3Kai,DynamicSTOP/KC3Kai,Tibo442/KC3Kai,KC3Kai/KC3Kai,sinsinpub/KC3Kai,hufuhufu/KC3Kai,Adrymne/KC3Kai,ReiFan49/KC3Kai,KC-TH/KC3Kai,KC3Kai/KC3Kai,KC-TH/KC3Kai,nekoworkshop/KC3Kai,Yukinyaa/KC3Kai,Adrymne/KC3Kai,jy19/KC3Kai,ethrundr/KC3Kai,hufuhufu/KC3Kai,ReiFan49/KC3Kai,rephira/KC3Kai,sinsinpub/KC3Kai,reinforce/KC3Kai,DynamicSTOP/KC3Kai,DynamicSTOP/KC3Kai,bamboo3250/KC3Kai,rephira/KC3Kai,Javran/KC3Kai,Yukinyaa/KC3Kai,sinsinpub/KC3Kai,androhgomez/KC3Kai,androhgomez/KC3Kai,c933103/KC3Kai,KC3Kai/KC3Kai,reinforce/KC3Kai,Madobe/KC3Kai,Javran/KC3Kai,dragonjet/KC3Kai,kololz/KC3Kai,Adrymne/KC3Kai,reinforce/KC3Kai,c933103/KC3Kai,ethrundr/KC3Kai,Javran/KC3Kai,Diablohu/KC3Kai,Slayers148/KC3Kai,kololz/KC3Kai,bamboo3250/KC3Kai,Diablohu/KC3Kai,nekoworkshop/KC3Kai,rephira/KC3Kai,Tibo442/KC3Kai,kololz/KC3Kai
/* Timer.js KC3改 Timer Object Contains a single timer which contains number of seconds left Has functions for TimerManager to use */ (function(){ "use strict"; window.KC3Timer = function(element, type, num){ this.alerted = false; this.type = type; this.num = num; this.element = element; this.deactivate(); }; KC3Timer.prototype.show = function(element){ this.element.show(); }; KC3Timer.prototype.hide = function(element){ this.element.hide(); }; KC3Timer.prototype.activate = function(completion, faceId, expedNum){ this.active = true; this.completion = completion; if(typeof faceId != "undefined"){ if(faceId>0){ this.faceId = faceId; } } if(typeof expedNum != "undefined"){ this.expedNum = expedNum; } var remaining = this.completion - (new Date()).getTime(); remaining = Math.ceil((remaining - (ConfigManager.alert_diff*1000))/1000); if(remaining <= 0){ this.alerted = true; } }; KC3Timer.prototype.deactivate = function(){ this.active = false; this.completion = 0; this.faceId = 0; this.expedNum = 0; $(".timer-img img", this.element).hide(); $(".timer-expnum", this.element).text(""); $(".timer-time", this.element).text(""); }; KC3Timer.prototype.time = function(){ $(".timer-time", this.element).text( this.text() ); }; KC3Timer.prototype.expnum = function(){ if(this.expedNum > 0){ $(".timer-expnum", this.element).text( this.expedNum ); } }; KC3Timer.prototype.face = function( faceId){ if(typeof faceId != "undefined"){ this.faceId = faceId; } if(this.faceId > 0){ $(".timer-img img", this.element).attr("src", KC3Meta.shipIcon(this.faceId, "../../../../assets/img/ui/empty.png")); $(".timer-img", this.element).attr("title", KC3Meta.shipName( KC3Master.ship(this.faceId).api_name ) ); $(".timer-img img", this.element).show(); }else{ $(".timer-img", this.element).attr("title", ""); $(".timer-img img", this.element).hide(); } }; KC3Timer.prototype.updateElement = function(element){ this.element = element; }; KC3Timer.prototype.text = function(){ if(this.active){ var remaining = this.completion - (new Date()).getTime(); var timerAllowance = (this.type == 2)?0:ConfigManager.alert_diff; remaining = Math.ceil((remaining - (timerAllowance*1000))/1000); if(remaining > 0){ this.alerted = false; var hrs = Math.floor(remaining/3600); remaining = remaining - (hrs * 3600); if(hrs < 10){ hrs = "0"+hrs; } var min = Math.floor(remaining/60); remaining = remaining - (min * 60); if(min < 10){ min = "0"+min; } if(remaining < 10){ remaining = "0"+remaining; } return hrs+":"+min+":"+remaining; }else{ this.completionAlert(); return "Complete!"; } }else{ return ""; } }; KC3Timer.prototype.completionAlert = function(){ if(this.alerted){ return false; } this.alerted = true; // Sound Alerts var notifSound; switch(ConfigManager.alert_type){ case 1: notifSound = new Audio("../../../../assets/snd/ding.mp3"); break; case 2: notifSound = new Audio(ConfigManager.alert_custom); break; default: notifSound = false; break; } if(notifSound){ notifSound.volume = ConfigManager.alert_volume / 100; notifSound.play(); } // Desktop notification if(ConfigManager.alert_desktop){ var notifData = { type: "basic" }; var shipName; // Notification types show varying messages switch(this.type){ case 0: var thisFleet = PlayerManager.fleets[this.num+1]; notifData.title = "Expedition Complete!"; notifData.message = "Fleet "+(this.num+2)+" just arrived from Expedition #"+thisFleet.mission[1]; notifData.iconUrl = "../../assets/img/quests/expedition.jpg"; break; case 1: shipName = KC3ShipManager.get( PlayerManager.repairShips[this.num+1] ).name(); notifData.title = "Repairs Complete!"; notifData.message = shipName+" is out of the repair dock!"; notifData.iconUrl = "../../assets/img/quests/supply.jpg"; break; case 2: shipName = KC3Meta.shipName( KC3Master.ship( this.faceId ).api_name ); notifData.title = "Construction Complete!"; if(ConfigManager.info_face){ notifData.message = "New face "+shipName+" has been constructed!"; }else{ notifData.message = "A newface is ready to see you in the construction docks!"; } notifData.iconUrl = "../../assets/img/quests/build.jpg"; break; default:break; } // Tell background page to show the notification, cant do it here (new RMsg("service", "notify_desktop", { notifId: this.type+"_"+this.num, data: notifData })).execute(); } }; })();
src/library/objects/Timer.js
/* Timer.js KC3改 Timer Object Contains a single timer which contains number of seconds left Has functions for TimerManager to use */ (function(){ "use strict"; window.KC3Timer = function(element, type, num){ this.alerted = false; this.type = type; this.num = num; this.element = element; this.deactivate(); }; KC3Timer.prototype.show = function(element){ this.element.show(); }; KC3Timer.prototype.hide = function(element){ this.element.hide(); }; KC3Timer.prototype.activate = function(completion, faceId, expedNum){ this.active = true; this.completion = completion; if(typeof faceId != "undefined"){ if(faceId>0){ this.faceId = faceId; } } if(typeof expedNum != "undefined"){ this.expedNum = expedNum; } var remaining = this.completion - (new Date()).getTime(); remaining = Math.ceil((remaining - (ConfigManager.alert_diff*1000))/1000); if(remaining <= 0){ this.alerted = true; } }; KC3Timer.prototype.deactivate = function(){ this.active = false; this.completion = 0; this.faceId = 0; this.expedNum = 0; $(".timer-img img", this.element).hide(); $(".timer-expnum", this.element).text(""); $(".timer-time", this.element).text(""); }; KC3Timer.prototype.time = function(){ $(".timer-time", this.element).text( this.text() ); }; KC3Timer.prototype.expnum = function(){ if(this.expedNum > 0){ $(".timer-expnum", this.element).text( this.expedNum ); } }; KC3Timer.prototype.face = function( faceId){ if(typeof faceId != "undefined"){ this.faceId = faceId; } if(this.faceId > 0){ $(".timer-img img", this.element).attr("src", KC3Meta.shipIcon(this.faceId, "../../../../assets/img/ui/empty.png")); $(".timer-img", this.element).attr("title", KC3Meta.shipName( KC3Master.ship(this.faceId).api_name ) ); $(".timer-img img", this.element).show(); }else{ $(".timer-img img", this.element).hide(); } }; KC3Timer.prototype.updateElement = function(element){ this.element = element; }; KC3Timer.prototype.text = function(){ if(this.active){ var remaining = this.completion - (new Date()).getTime(); var timerAllowance = (this.type == 2)?0:ConfigManager.alert_diff; remaining = Math.ceil((remaining - (timerAllowance*1000))/1000); if(remaining > 0){ this.alerted = false; var hrs = Math.floor(remaining/3600); remaining = remaining - (hrs * 3600); if(hrs < 10){ hrs = "0"+hrs; } var min = Math.floor(remaining/60); remaining = remaining - (min * 60); if(min < 10){ min = "0"+min; } if(remaining < 10){ remaining = "0"+remaining; } return hrs+":"+min+":"+remaining; }else{ this.completionAlert(); return "Complete!"; } }else{ return ""; } }; KC3Timer.prototype.completionAlert = function(){ if(this.alerted){ return false; } this.alerted = true; // Sound Alerts var notifSound; switch(ConfigManager.alert_type){ case 1: notifSound = new Audio("../../../../assets/snd/ding.mp3"); break; case 2: notifSound = new Audio(ConfigManager.alert_custom); break; default: notifSound = false; break; } if(notifSound){ notifSound.volume = ConfigManager.alert_volume / 100; notifSound.play(); } // Desktop notification if(ConfigManager.alert_desktop){ var notifData = { type: "basic" }; var shipName; // Notification types show varying messages switch(this.type){ case 0: var thisFleet = PlayerManager.fleets[this.num+1]; notifData.title = "Expedition Complete!"; notifData.message = "Fleet "+(this.num+2)+" just arrived from Expedition #"+thisFleet.mission[1]; notifData.iconUrl = "../../assets/img/quests/expedition.jpg"; break; case 1: shipName = KC3ShipManager.get( PlayerManager.repairShips[this.num+1] ).name(); notifData.title = "Repairs Complete!"; notifData.message = shipName+" is out of the repair dock!"; notifData.iconUrl = "../../assets/img/quests/supply.jpg"; break; case 2: shipName = KC3Meta.shipName( KC3Master.ship( this.faceId ).api_name ); notifData.title = "Construction Complete!"; if(ConfigManager.info_face){ notifData.message = "New face "+shipName+" has been constructed!"; }else{ notifData.message = "A newface is ready to see you in the construction docks!"; } notifData.iconUrl = "../../assets/img/quests/build.jpg"; break; default:break; } // Tell background page to show the notification, cant do it here (new RMsg("service", "notify_desktop", { notifId: this.type+"_"+this.num, data: notifData })).execute(); } }; })();
[Fix #517] Clear tooltip on timers with no face
src/library/objects/Timer.js
[Fix #517] Clear tooltip on timers with no face
<ide><path>rc/library/objects/Timer.js <ide> $(".timer-img", this.element).attr("title", KC3Meta.shipName( KC3Master.ship(this.faceId).api_name ) ); <ide> $(".timer-img img", this.element).show(); <ide> }else{ <add> $(".timer-img", this.element).attr("title", ""); <ide> $(".timer-img img", this.element).hide(); <ide> } <ide> };
Java
mit
2a0e60dddc478cdf05ffa2deb3cabe27fab80db3
0
Ali-Amir/battlecode2016
package armstrong; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.hibernate.search.analyzer.Discriminator; //import com.sun.xml.internal.bind.v2.runtime.Location; import battlecode.common.*; public class RobotPlayer{ static Random rnd; static RobotController rc; static int[] tryDirections = {0,-1,1,-2,2}; static RobotType[] buildList = new RobotType[]{RobotType.GUARD,RobotType.TURRET}; static RobotType lastBuilt = RobotType.ARCHON; static Set<Integer> marriedScouts = new HashSet<>(); static Set<Integer> marriedTurrets = new HashSet<>(); static int husbandTurretID = -1; static boolean broadcastNextTurn = false; static int[] toBroadcastNextTurn = new int[3]; static int MESSAGE_MARRIAGE = 0; static int MESSAGE_ENEMY = 1; public static void run(RobotController rcIn){ rc = rcIn; rnd = new Random(rc.getID()); while(true){ try{ if(rc.getType()==RobotType.ARCHON){ archonCode(); }else if(rc.getType()==RobotType.TURRET){ turretCode(); }else if(rc.getType()==RobotType.TTM){ ttmCode(); }else if(rc.getType()==RobotType.GUARD){ guardCode(); }else if(rc.getType()==RobotType.SOLDIER){ guardCode(); }else if(rc.getType()==RobotType.SCOUT){ scoutCode(); } }catch(Exception e){ e.printStackTrace(); } Clock.yield(); } } private static MapLocation getTurretEnemy(Signal s){ int[] message = s.getMessage(); if(s.getTeam().equals(rc.getTeam()) && message != null && s.getLocation().distanceSquaredTo(rc.getLocation()) <= 2){ if(message[0] == MESSAGE_ENEMY){ return decodeLocation(message[1]); } } return null; } private static void turretCode() throws GameActionException { RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); for(Signal s: incomingSignals){ MapLocation enemyLocation = getTurretEnemy(s); if(enemyLocation != null && rc.canAttackLocation(enemyLocation)){ rc.attackLocation(enemyLocation); } } if(enemyArray.length>0){ if(rc.isWeaponReady()){ //look for adjacent enemies to attack for(MapLocation oneEnemy:enemyArray){ if(rc.canAttackLocation(oneEnemy)){ rc.setIndicatorString(0,"trying to attack"); rc.attackLocation(oneEnemy); break; } } } //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ rc.pack(); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ //TODO Fix logic here choose the condition for packing //rc.pack(); RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ rc.pack(); } } } } private static int encodeLocation(MapLocation lc){ final int maxOffset = 16000; final int range = 2 * maxOffset; int x = lc.x; int y = lc.y; x += maxOffset; y += maxOffset; return (range + 1) * x + y; } private static MapLocation decodeLocation(int code){ final int maxOffset = 16000; final int range = 2 * maxOffset; int x = code/(range + 1); int y = code%(range + 1); return new MapLocation(x, y); } private static void ttmCode() throws GameActionException { RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); if(enemyArray.length>0){ rc.unpack(); //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0]; Direction toEnemy = rc.getLocation().directionTo(goal); tryToMove(toEnemy); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); tryToMove(away); }else{//maybe a friend is in need! RobotInfo[] alliesToHelp = rc.senseNearbyRobots(1000000,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){//found a friend most in need Direction towardFriend = rc.getLocation().directionTo(weakestOne); tryToMove(towardFriend); } } } } } private static void guardCode() throws GameActionException { RobotInfo[] enemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); if(enemyArray.length>0){ if(rc.isWeaponReady()){ //look for adjacent enemies to attack for(RobotInfo oneEnemy:enemyArray){ if(rc.canAttackLocation(oneEnemy.location)){ rc.setIndicatorString(0,"trying to attack"); rc.attackLocation(oneEnemy.location); break; } } } //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0].location; Direction toEnemy = rc.getLocation().directionTo(goal); tryToMove(toEnemy); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); tryToMove(away); }else{//maybe a friend is in need! RobotInfo[] alliesToHelp = rc.senseNearbyRobots(1000000,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){//found a friend most in need Direction towardFriend = rc.getLocation().directionTo(weakestOne); tryToMove(towardFriend); } } } } } private static MapLocation[] combineThings(RobotInfo[] visibleEnemyArray, Signal[] incomingSignals) { ArrayList<MapLocation> attackableEnemyArray = new ArrayList<MapLocation>(); for(RobotInfo r:visibleEnemyArray){ attackableEnemyArray.add(r.location); } for(Signal s:incomingSignals){ if(s.getTeam()==rc.getTeam().opponent()){ MapLocation enemySignalLocation = s.getLocation(); int distanceToSignalingEnemy = rc.getLocation().distanceSquaredTo(enemySignalLocation); if(distanceToSignalingEnemy<=rc.getType().attackRadiusSquared){ attackableEnemyArray.add(enemySignalLocation); } } } MapLocation[] finishedArray = new MapLocation[attackableEnemyArray.size()]; for(int i=0;i<attackableEnemyArray.size();i++){ finishedArray[i]=attackableEnemyArray.get(i); } return finishedArray; } public static void tryToMove(Direction forward) throws GameActionException{ if(rc.isCoreReady()){ for(int deltaD:tryDirections){ Direction maybeForward = Direction.values()[(forward.ordinal()+deltaD+8)%8]; if(rc.canMove(maybeForward)){ rc.move(maybeForward); return; } } if(rc.getType().canClearRubble()){ //failed to move, look to clear rubble MapLocation ahead = rc.getLocation().add(forward); if(rc.senseRubble(ahead)>=GameConstants.RUBBLE_OBSTRUCTION_THRESH){ rc.clearRubble(forward); } } } } private static RobotInfo findWeakestRobot(RobotInfo[] listOfRobots){ double weakestSoFar = 0; RobotInfo weakest = null; for(RobotInfo r:listOfRobots){ double weakness = r.maxHealth-r.health; //double weakness = (r.maxHealth-r.health)*1.0/r.maxHealth; if(weakness>weakestSoFar){ weakest = r; weakestSoFar=weakness; } } return weakest; } private static MapLocation findWeakest(RobotInfo[] listOfRobots){ double weakestSoFar = 0; MapLocation weakestLocation = null; for(RobotInfo r:listOfRobots){ double weakness = r.maxHealth-r.health; //double weakness = (r.maxHealth-r.health)*1.0/r.maxHealth; if(weakness>weakestSoFar){ weakestLocation = r.location; weakestSoFar=weakness; } } return weakestLocation; } //Gets an unmarried turret or scout private static RobotInfo getLonelyRobot(RobotInfo[] robots,RobotType targetType,Set<Integer> married){ for(RobotInfo robot: robots){ if(robot.type == targetType && !married.contains(robot.ID)){ return robot; } } return null; } //Checks private static int getHusbandTurretID(Signal s){ if(s.getTeam().equals(rc.getTeam()) && s.getMessage() != null){ if(s.getMessage()[0] == rc.getID()){ return s.getMessage()[1]; } } return -1; } private static void scoutCode() throws GameActionException{ RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); //MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); for(Signal s: incomingSignals){ husbandTurretID = getHusbandTurretID(s); if(husbandTurretID != -1){ break; } } if(husbandTurretID != -1){ rc.setIndicatorString(0, "My husband ID is" + husbandTurretID); } else{ rc.setIndicatorString(1, "I am a scout with no husband"); } //TODO can be improved by using previous information of the location of the husband RobotInfo[] visibleAlliesArray = rc.senseNearbyRobots(); RobotInfo husband = null; for(int i = 0; i < visibleAlliesArray.length; i++){ if(visibleAlliesArray[i].ID == husbandTurretID){ husband = visibleAlliesArray[i]; } } RobotInfo targetRobot = findWeakestRobot(visibleEnemyArray); MapLocation target = null; if(targetRobot != null){ target = targetRobot.location; rc.setIndicatorString(2, "Target is at location (" + target.x + "," + target.y + ")"); rc.setIndicatorString(3, "Target is of type:" + targetRobot.type); } if(husband != null){ Direction toHusband = rc.getLocation().directionTo(husband.location); if(rc.getLocation().distanceSquaredTo(husband.location)<= 2){ if(target != null){ rc.broadcastMessageSignal(MESSAGE_ENEMY, encodeLocation(target),rc.getLocation().distanceSquaredTo(husband.location)); } }else{ if(rc.isCoreReady()){ tryToMove(toHusband); } } } } private static RobotInfo[] getArray(ArrayList<RobotInfo> selectedList){ RobotInfo[] selectedArray = new RobotInfo[selectedList.size()]; for(int i = 0;i < selectedList.size();i ++){ selectedArray[i] = selectedList.get(i); } return selectedArray; } private static void archonCode() throws GameActionException { if(broadcastNextTurn){ rc.broadcastMessageSignal(toBroadcastNextTurn[0], toBroadcastNextTurn[1], toBroadcastNextTurn[2]); broadcastNextTurn = false; } if(rc.isCoreReady()){ Direction randomDir = randomDirection(); boolean backupTurret = false; RobotInfo choosenTurret = null; RobotType toBuild; if(lastBuilt == RobotType.TURRET){ //We can improve on this //for instance we can combine the two sense statements we have. RobotInfo[] alliesNearBy = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared,rc.getTeam()); //turretsNearBy = filterRobotsbyType(alliesNearBy, targetType) choosenTurret = getLonelyRobot(alliesNearBy,RobotType.TURRET,marriedTurrets); if(choosenTurret != null){ toBuild = RobotType.SCOUT; backupTurret = true; }else{ toBuild = buildList[rnd.nextInt(buildList.length)]; } }else{ toBuild = buildList[rnd.nextInt(buildList.length)]; } if(rc.getTeamParts()>100){ if(rc.canBuild(randomDir, toBuild)){ rc.build(randomDir,toBuild); lastBuilt = toBuild; if(backupTurret){ RobotInfo[] alliesVeryNear = rc.senseNearbyRobots(2,rc.getTeam()); RobotInfo choosenScout = getLonelyRobot(alliesVeryNear, RobotType.SCOUT, marriedScouts); if(choosenTurret == null){ rc.disintegrate(); } //rc.broadcastMessageSignal(choosenScout.ID,choosenTurret.ID, choosenTurret.location.distanceSquaredTo(rc.getLocation())); toBroadcastNextTurn[0] = choosenScout.ID; toBroadcastNextTurn[1] = choosenTurret.ID; toBroadcastNextTurn[2] = 8; broadcastNextTurn = true; marriedTurrets.add(choosenTurret.ID); marriedScouts.add(choosenScout.ID); } return; } } RobotInfo[] alliesToHelp = rc.senseNearbyRobots(RobotType.ARCHON.attackRadiusSquared,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){ rc.repair(weakestOne); return; } } } private static Direction randomDirection() { return Direction.values()[(int)(rnd.nextDouble()*8)]; } //filters robots by type private static RobotInfo[] filterRobotsbyType(RobotInfo[] robots, RobotType targetType){ ArrayList<RobotInfo> selectedList = new ArrayList<>(); for(RobotInfo r:robots){ if(r.type.equals(targetType)){ selectedList.add(r); } } return getArray(selectedList); } }
battlecode-scaffold-master/src/armstrong/RobotPlayer.java
package armstrong; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.hibernate.search.analyzer.Discriminator; import battlecode.common.*; public class RobotPlayer{ static Random rnd; static RobotController rc; static int[] tryDirections = {0,-1,1,-2,2}; static RobotType[] buildList = new RobotType[]{RobotType.GUARD,RobotType.TURRET}; static RobotType lastBuilt = RobotType.ARCHON; static Set<Integer> marriedScouts = new HashSet<>(); static Set<Integer> marriedTurrets = new HashSet<>(); static int husbandTurretID = -1; static boolean broadcastNextTurn = false; static int[] toBroadcastNextTurn = new int[3]; public static void run(RobotController rcIn){ rc = rcIn; rnd = new Random(rc.getID()); while(true){ try{ if(rc.getType()==RobotType.ARCHON){ archonCode(); }else if(rc.getType()==RobotType.TURRET){ turretCode(); }else if(rc.getType()==RobotType.TTM){ ttmCode(); }else if(rc.getType()==RobotType.GUARD){ guardCode(); }else if(rc.getType()==RobotType.SOLDIER){ guardCode(); }else if(rc.getType()==RobotType.SCOUT){ scoutCode(); } }catch(Exception e){ e.printStackTrace(); } Clock.yield(); } } private static void turretCode() throws GameActionException { RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); if(enemyArray.length>0){ if(rc.isWeaponReady()){ //look for adjacent enemies to attack for(MapLocation oneEnemy:enemyArray){ if(rc.canAttackLocation(oneEnemy)){ rc.setIndicatorString(0,"trying to attack"); rc.attackLocation(oneEnemy); break; } } } //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0]; Direction toEnemy = rc.getLocation().directionTo(goal); rc.pack(); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); rc.pack(); } } } } private static void ttmCode() throws GameActionException { RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); if(enemyArray.length>0){ rc.unpack(); //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0]; Direction toEnemy = rc.getLocation().directionTo(goal); tryToMove(toEnemy); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); tryToMove(away); }else{//maybe a friend is in need! RobotInfo[] alliesToHelp = rc.senseNearbyRobots(1000000,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){//found a friend most in need Direction towardFriend = rc.getLocation().directionTo(weakestOne); tryToMove(towardFriend); } } } } } private static void guardCode() throws GameActionException { RobotInfo[] enemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); if(enemyArray.length>0){ if(rc.isWeaponReady()){ //look for adjacent enemies to attack for(RobotInfo oneEnemy:enemyArray){ if(rc.canAttackLocation(oneEnemy.location)){ rc.setIndicatorString(0,"trying to attack"); rc.attackLocation(oneEnemy.location); break; } } } //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0].location; Direction toEnemy = rc.getLocation().directionTo(goal); tryToMove(toEnemy); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); tryToMove(away); }else{//maybe a friend is in need! RobotInfo[] alliesToHelp = rc.senseNearbyRobots(1000000,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){//found a friend most in need Direction towardFriend = rc.getLocation().directionTo(weakestOne); tryToMove(towardFriend); } } } } } private static MapLocation[] combineThings(RobotInfo[] visibleEnemyArray, Signal[] incomingSignals) { ArrayList<MapLocation> attackableEnemyArray = new ArrayList<MapLocation>(); for(RobotInfo r:visibleEnemyArray){ attackableEnemyArray.add(r.location); } for(Signal s:incomingSignals){ if(s.getTeam()==rc.getTeam().opponent()){ MapLocation enemySignalLocation = s.getLocation(); int distanceToSignalingEnemy = rc.getLocation().distanceSquaredTo(enemySignalLocation); if(distanceToSignalingEnemy<=rc.getType().attackRadiusSquared){ attackableEnemyArray.add(enemySignalLocation); } } } MapLocation[] finishedArray = new MapLocation[attackableEnemyArray.size()]; for(int i=0;i<attackableEnemyArray.size();i++){ finishedArray[i]=attackableEnemyArray.get(i); } return finishedArray; } public static void tryToMove(Direction forward) throws GameActionException{ if(rc.isCoreReady()){ for(int deltaD:tryDirections){ Direction maybeForward = Direction.values()[(forward.ordinal()+deltaD+8)%8]; if(rc.canMove(maybeForward)){ rc.move(maybeForward); return; } } if(rc.getType().canClearRubble()){ //failed to move, look to clear rubble MapLocation ahead = rc.getLocation().add(forward); if(rc.senseRubble(ahead)>=GameConstants.RUBBLE_OBSTRUCTION_THRESH){ rc.clearRubble(forward); } } } } private static MapLocation findWeakest(RobotInfo[] listOfRobots){ double weakestSoFar = 0; MapLocation weakestLocation = null; for(RobotInfo r:listOfRobots){ double weakness = r.maxHealth-r.health; //double weakness = (r.maxHealth-r.health)*1.0/r.maxHealth; if(weakness>weakestSoFar){ weakestLocation = r.location; weakestSoFar=weakness; } } return weakestLocation; } //Gets an unmarried turret or scout private static RobotInfo getLonelyRobot(RobotInfo[] robots,RobotType targetType,Set<Integer> married){ for(RobotInfo robot: robots){ if(robot.type == targetType && !married.contains(robot.ID)){ return robot; } } return null; } //Checks private static int getHusbandTurretID(Signal s){ if(s.getTeam().equals(rc.getTeam()) && s.getMessage() != null){ if(s.getMessage()[0] == rc.getID()){ return s.getMessage()[1]; } } return -1; } private static void scoutCode(){ RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); for(Signal s: incomingSignals){ husbandTurretID = getHusbandTurretID(s); if(husbandTurretID != -1){ break; } } if(husbandTurretID != -1){ rc.setIndicatorString(0, "My husband ID is" + husbandTurretID); } else{ rc.setIndicatorString(1, "I am a scout with no husband"); } //TODO can be improved by using previous information of the location of the husband RobotInfo[] visibleAlliesArray = rc.senseNearbyRobots(); RobotInfo husband = null; for(int i = 0; i < visibleAlliesArray.length; i++){ if(visibleAlliesArray[i].ID == husbandTurretID){ husband = visibleAlliesArray[i]; } } if(husband != null){ Direction toHusband = rc.getLocation().directionTo(husband.location); try { if(rc.getLocation().distanceSquaredTo(husband.location)>= 2){ tryToMove(toHusband); } } catch (GameActionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private static RobotInfo[] getArray(ArrayList<RobotInfo> selectedList){ RobotInfo[] selectedArray = new RobotInfo[selectedList.size()]; for(int i = 0;i < selectedList.size();i ++){ selectedArray[i] = selectedList.get(i); } return selectedArray; } private static void archonCode() throws GameActionException { if(broadcastNextTurn){ rc.broadcastMessageSignal(toBroadcastNextTurn[0], toBroadcastNextTurn[1], toBroadcastNextTurn[2]); broadcastNextTurn = false; } if(rc.isCoreReady()){ Direction randomDir = randomDirection(); boolean backupTurret = false; RobotInfo choosenTurret = null; RobotType toBuild; if(lastBuilt == RobotType.TURRET){ //We can improve on this //for instance we can combine the two sense statements we have. RobotInfo[] alliesNearBy = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared,rc.getTeam()); //turretsNearBy = filterRobotsbyType(alliesNearBy, targetType) choosenTurret = getLonelyRobot(alliesNearBy,RobotType.TURRET,marriedTurrets); if(choosenTurret != null){ toBuild = RobotType.SCOUT; backupTurret = true; }else{ toBuild = buildList[rnd.nextInt(buildList.length)]; } }else{ toBuild = buildList[rnd.nextInt(buildList.length)]; } if(rc.getTeamParts()>100){ if(rc.canBuild(randomDir, toBuild)){ rc.build(randomDir,toBuild); lastBuilt = toBuild; if(backupTurret){ RobotInfo[] alliesVeryNear = rc.senseNearbyRobots(2,rc.getTeam()); RobotInfo choosenScout = getLonelyRobot(alliesVeryNear, RobotType.SCOUT, marriedScouts); if(choosenTurret == null){ rc.disintegrate(); } //rc.broadcastMessageSignal(choosenScout.ID,choosenTurret.ID, choosenTurret.location.distanceSquaredTo(rc.getLocation())); toBroadcastNextTurn[0] = choosenScout.ID; toBroadcastNextTurn[1] = choosenTurret.ID; toBroadcastNextTurn[2] = 8; broadcastNextTurn = true; marriedTurrets.add(choosenTurret.ID); marriedScouts.add(choosenScout.ID); } return; } } RobotInfo[] alliesToHelp = rc.senseNearbyRobots(RobotType.ARCHON.attackRadiusSquared,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){ rc.repair(weakestOne); return; } } } private static Direction randomDirection() { return Direction.values()[(int)(rnd.nextDouble()*8)]; } //filters robots by type private static RobotInfo[] filterRobotsbyType(RobotInfo[] robots, RobotType targetType){ ArrayList<RobotInfo> selectedList = new ArrayList<>(); for(RobotInfo r:robots){ if(r.type.equals(targetType)){ selectedList.add(r); } } return getArray(selectedList); } }
Every scout is follows a certain turrets and keep telling him about enemies around.
battlecode-scaffold-master/src/armstrong/RobotPlayer.java
Every scout is follows a certain turrets and keep telling him about enemies around.
<ide><path>attlecode-scaffold-master/src/armstrong/RobotPlayer.java <ide> import java.util.Set; <ide> <ide> import org.hibernate.search.analyzer.Discriminator; <add> <add>//import com.sun.xml.internal.bind.v2.runtime.Location; <ide> <ide> import battlecode.common.*; <ide> <ide> static int husbandTurretID = -1; <ide> static boolean broadcastNextTurn = false; <ide> static int[] toBroadcastNextTurn = new int[3]; <add> static int MESSAGE_MARRIAGE = 0; <add> static int MESSAGE_ENEMY = 1; <ide> public static void run(RobotController rcIn){ <ide> <ide> rc = rcIn; <ide> Clock.yield(); <ide> } <ide> } <del> <add> private static MapLocation getTurretEnemy(Signal s){ <add> int[] message = s.getMessage(); <add> if(s.getTeam().equals(rc.getTeam()) && message != null && s.getLocation().distanceSquaredTo(rc.getLocation()) <= 2){ <add> if(message[0] == MESSAGE_ENEMY){ <add> return decodeLocation(message[1]); <add> } <add> } <add> return null; <add> } <ide> private static void turretCode() throws GameActionException { <ide> RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); <ide> Signal[] incomingSignals = rc.emptySignalQueue(); <ide> MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); <del> <add> for(Signal s: incomingSignals){ <add> MapLocation enemyLocation = getTurretEnemy(s); <add> if(enemyLocation != null && rc.canAttackLocation(enemyLocation)){ <add> rc.attackLocation(enemyLocation); <add> } <add> } <ide> if(enemyArray.length>0){ <ide> if(rc.isWeaponReady()){ <ide> //look for adjacent enemies to attack <ide> //could not find any enemies adjacent to attack <ide> //try to move toward them <ide> if(rc.isCoreReady()){ <del> MapLocation goal = enemyArray[0]; <del> Direction toEnemy = rc.getLocation().directionTo(goal); <ide> rc.pack(); <ide> } <ide> }else{//there are no enemies nearby <ide> //check to see if we are in the way of friends <ide> //we are obstructing them <ide> if(rc.isCoreReady()){ <add> //TODO Fix logic here choose the condition for packing <add> //rc.pack(); <ide> RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); <ide> if(nearbyFriends.length>3){ <del> Direction away = randomDirection(); <ide> rc.pack(); <ide> } <ide> } <ide> } <ide> } <del> <add> private static int encodeLocation(MapLocation lc){ <add> final int maxOffset = 16000; <add> final int range = 2 * maxOffset; <add> int x = lc.x; <add> int y = lc.y; <add> x += maxOffset; <add> y += maxOffset; <add> return (range + 1) * x + y; <add> } <add> private static MapLocation decodeLocation(int code){ <add> final int maxOffset = 16000; <add> final int range = 2 * maxOffset; <add> int x = code/(range + 1); <add> int y = code%(range + 1); <add> return new MapLocation(x, y); <add> } <ide> private static void ttmCode() throws GameActionException { <ide> RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); <ide> Signal[] incomingSignals = rc.emptySignalQueue(); <ide> } <ide> } <ide> } <del> <add> private static RobotInfo findWeakestRobot(RobotInfo[] listOfRobots){ <add> double weakestSoFar = 0; <add> RobotInfo weakest = null; <add> for(RobotInfo r:listOfRobots){ <add> double weakness = r.maxHealth-r.health; <add> //double weakness = (r.maxHealth-r.health)*1.0/r.maxHealth; <add> if(weakness>weakestSoFar){ <add> weakest = r; <add> weakestSoFar=weakness; <add> } <add> } <add> return weakest; <add> } <ide> private static MapLocation findWeakest(RobotInfo[] listOfRobots){ <ide> double weakestSoFar = 0; <ide> MapLocation weakestLocation = null; <ide> } <ide> return -1; <ide> } <del> private static void scoutCode(){ <add> private static void scoutCode() throws GameActionException{ <ide> RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); <ide> Signal[] incomingSignals = rc.emptySignalQueue(); <del> MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); <add> //MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); <ide> for(Signal s: incomingSignals){ <ide> husbandTurretID = getHusbandTurretID(s); <ide> if(husbandTurretID != -1){ <ide> husband = visibleAlliesArray[i]; <ide> } <ide> } <del> <add> RobotInfo targetRobot = findWeakestRobot(visibleEnemyArray); <add> MapLocation target = null; <add> if(targetRobot != null){ <add> target = targetRobot.location; <add> rc.setIndicatorString(2, "Target is at location (" + target.x + "," + target.y + ")"); <add> rc.setIndicatorString(3, "Target is of type:" + targetRobot.type); <add> } <ide> if(husband != null){ <ide> Direction toHusband = rc.getLocation().directionTo(husband.location); <del> try { <del> if(rc.getLocation().distanceSquaredTo(husband.location)>= 2){ <del> tryToMove(toHusband); <del> } <del> <del> } catch (GameActionException e) { <del> // TODO Auto-generated catch block <del> e.printStackTrace(); <del> } <add> if(rc.getLocation().distanceSquaredTo(husband.location)<= 2){ <add> if(target != null){ <add> rc.broadcastMessageSignal(MESSAGE_ENEMY, encodeLocation(target),rc.getLocation().distanceSquaredTo(husband.location)); <add> } <add> }else{ <add> if(rc.isCoreReady()){ <add> tryToMove(toHusband); <add> } <add> } <add> <ide> } <ide> <ide> }
Java
mit
7072c869ba289310c488628893dd3306c42113b1
0
Akhier/Java-DijkstraAlgorithm
package com.dragonheart.test; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Before; import org.junit.Test; import com.dragonheart.dijkstra.DijkstraGraph; import com.dragonheart.dijkstra.DijkstraGraphFactory; import com.dragonheart.dijkstra.Point; public class testDijkstraGraphFrom2DBoolArray { private boolean[][] boolMap; @Before public void setUp() throws Exception { int width = 7, height = 7; boolMap = new boolean[width][height]; boolMap[0][0] = true; boolMap[1][0] = true; boolMap[2][0] = false; boolMap[3][0] = true; boolMap[4][0] = true; boolMap[5][0] = true; boolMap[6][0] = true; boolMap[0][1] = false; boolMap[1][1] = true; boolMap[2][1] = false; boolMap[3][1] = false; boolMap[4][1] = true; boolMap[5][1] = false; boolMap[6][1] = true; boolMap[0][2] = true; boolMap[1][2] = true; boolMap[2][2] = true; boolMap[3][2] = false; boolMap[4][2] = true; boolMap[5][2] = false; boolMap[6][2] = true; boolMap[0][3] = true; boolMap[1][3] = false; boolMap[2][3] = true; boolMap[3][3] = false; boolMap[4][3] = true; boolMap[5][3] = false; boolMap[6][3] = true; boolMap[0][4] = true; boolMap[1][4] = false; boolMap[2][4] = true; boolMap[3][4] = true; boolMap[4][4] = true; boolMap[5][4] = false; boolMap[6][4] = true; boolMap[0][5] = true; boolMap[1][5] = true; boolMap[2][5] = true; boolMap[3][5] = false; boolMap[4][5] = false; boolMap[5][5] = true; boolMap[6][5] = true; boolMap[0][6] = false; boolMap[1][6] = false; boolMap[2][6] = false; boolMap[3][6] = false; boolMap[4][6] = false; boolMap[5][6] = false; boolMap[6][6] = true; } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraphFactory#dijkstraGraphFrom2DBoolArray(boolean[][], Double)} */ @Test public final void testDijkstraMapFrom2DBoolArray_NoDiagonalMovement() { DijkstraGraph graph = new DijkstraGraph(); Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, false, graph); graph.setSource(pointmap[6][6], 0.0); assertTrue(graph.processGraph()); List<Point> path = graph.getPathFrom(pointmap[0][0]); Point temp = path.get(1); assertTrue(temp == pointmap[1][0]); temp = path.get(2); assertTrue(temp == pointmap[1][1]); temp = path.get(path.size() - 2); assertTrue(temp == pointmap[6][5]); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraphFactory#dijkstraGraphFrom2DBoolArray(boolean[][], Double, Double)} */ @Test public final void testDijkstraMapFrom2DBoolArray_DiagonalMovement() { DijkstraGraph graph = new DijkstraGraph(); Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, true, graph); graph.setSource(pointmap[6][6], 0.0); assertTrue(graph.processGraph()); List<Point> path = graph.getPathFrom(pointmap[0][0]); Point temp = path.get(1); assertTrue(temp == pointmap[1][1]); temp = path.get(3); assertTrue(temp == pointmap[2][3]); temp = path.get(path.size() - 2); assertTrue(temp == pointmap[5][5]); } }
src/test/java/com/dragonheart/test/testDijkstraGraphFrom2DBoolArray.java
package com.dragonheart.test; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Before; import org.junit.Test; import com.dragonheart.dijkstra.DijkstraGraph; import com.dragonheart.dijkstra.DijkstraGraphFactory; import com.dragonheart.dijkstra.Point; public class testDijkstraGraphFrom2DBoolArray { private boolean[][] boolMap; @Before public void setUp() throws Exception { int width = 7, height = 7; boolMap = new boolean[width][height]; boolMap[0][0] = true; boolMap[1][0] = true; boolMap[2][0] = false; boolMap[3][0] = true; boolMap[4][0] = true; boolMap[5][0] = true; boolMap[6][0] = true; boolMap[0][1] = false; boolMap[1][1] = true; boolMap[2][1] = false; boolMap[3][1] = false; boolMap[4][1] = true; boolMap[5][1] = false; boolMap[6][1] = true; boolMap[0][2] = true; boolMap[1][2] = true; boolMap[2][2] = true; boolMap[3][2] = false; boolMap[4][2] = true; boolMap[5][2] = false; boolMap[6][2] = true; boolMap[0][3] = true; boolMap[1][3] = false; boolMap[2][3] = true; boolMap[3][3] = false; boolMap[4][3] = true; boolMap[5][3] = false; boolMap[6][3] = true; boolMap[0][4] = true; boolMap[1][4] = false; boolMap[2][4] = true; boolMap[3][4] = true; boolMap[4][4] = true; boolMap[5][4] = false; boolMap[6][4] = true; boolMap[0][5] = true; boolMap[1][5] = true; boolMap[2][5] = true; boolMap[3][5] = false; boolMap[4][5] = false; boolMap[5][5] = true; boolMap[6][5] = true; boolMap[0][6] = false; boolMap[1][6] = false; boolMap[2][6] = false; boolMap[3][6] = false; boolMap[4][6] = false; boolMap[5][6] = false; boolMap[6][6] = true; } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraphFactory#dijkstraGraphFrom2DBoolArray(boolean[][], Double)} */ @Test public final void testDijkstraMapFrom2DBoolArray_NoDiagonalMovement() { DijkstraGraph graph = new DijkstraGraph(); Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, graph); graph.setSource(pointmap[6][6], 0.0); assertTrue(graph.processGraph()); List<Point> path = graph.getPathFrom(pointmap[0][0]); Point temp = path.get(1); assertTrue(temp == pointmap[1][0]); temp = path.get(2); assertTrue(temp == pointmap[1][1]); temp = path.get(path.size() - 2); assertTrue(temp == pointmap[6][5]); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraphFactory#dijkstraGraphFrom2DBoolArray(boolean[][], Double, Double)} */ @Test public final void testDijkstraMapFrom2DBoolArray_DiagonalMovement() { DijkstraGraph graph = new DijkstraGraph(); Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, 1.0, graph); graph.setSource(pointmap[6][6], 0.0); assertTrue(graph.processGraph()); List<Point> path = graph.getPathFrom(pointmap[0][0]); Point temp = path.get(1); assertTrue(temp == pointmap[1][1]); temp = path.get(3); assertTrue(temp == pointmap[2][3]); temp = path.get(path.size() - 2); assertTrue(temp == pointmap[5][5]); } }
missed one
src/test/java/com/dragonheart/test/testDijkstraGraphFrom2DBoolArray.java
missed one
<ide><path>rc/test/java/com/dragonheart/test/testDijkstraGraphFrom2DBoolArray.java <ide> @Test <ide> public final void testDijkstraMapFrom2DBoolArray_NoDiagonalMovement() { <ide> DijkstraGraph graph = new DijkstraGraph(); <del> Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, graph); <add> Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, false, graph); <ide> graph.setSource(pointmap[6][6], 0.0); <ide> assertTrue(graph.processGraph()); <ide> List<Point> path = graph.getPathFrom(pointmap[0][0]); <ide> @Test <ide> public final void testDijkstraMapFrom2DBoolArray_DiagonalMovement() { <ide> DijkstraGraph graph = new DijkstraGraph(); <del> Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, 1.0, graph); <add> Point[][] pointmap = DijkstraGraphFactory.dijkstraGraphFrom2DBoolArray(boolMap, 1.0, true, graph); <ide> graph.setSource(pointmap[6][6], 0.0); <ide> assertTrue(graph.processGraph()); <ide> List<Point> path = graph.getPathFrom(pointmap[0][0]);
Java
lgpl-2.1
fd7b3ae383deaefde97671058e04d31654254280
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2009 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.crowd.peer.server; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.internal.Lists; import com.samskivert.util.Comparators; import com.samskivert.util.Interval; import com.samskivert.util.Lifecycle; import com.samskivert.util.ResultListener; import com.threerings.util.Name; import com.threerings.presents.client.InvocationService; import com.threerings.presents.data.ClientObject; import com.threerings.presents.peer.data.ClientInfo; import com.threerings.presents.peer.data.NodeObject; import com.threerings.presents.peer.server.PeerManager; import com.threerings.presents.peer.server.PeerNode; import com.threerings.presents.server.InvocationException; import com.threerings.presents.server.InvocationManager; import com.threerings.presents.server.PresentsSession; import com.threerings.crowd.chat.client.ChatService; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.chat.server.ChatProvider; import com.threerings.crowd.chat.server.SpeakUtil; import com.threerings.crowd.chat.server.SpeakUtil.ChatHistoryEntry; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.peer.data.CrowdClientInfo; import com.threerings.crowd.peer.data.CrowdNodeObject; import static com.threerings.crowd.Log.log; /** * Extends the standard peer manager and bridges certain Crowd services. */ public abstract class CrowdPeerManager extends PeerManager implements CrowdPeerProvider, ChatProvider.ChatForwarder { /** * Value asynchronously returned by {@link #collectChatHistory} after polling all peer nodes. */ public static class ChatHistoryResult { /** The set of nodes that either did not reply within the timeout, or had a failure. */ public Set<String> failedNodes; /** The things in the user's chat history, aggregated from all nodes and sorted by * timestamp. */ public List<ChatHistoryEntry> history; } /** * Creates an uninitialized peer manager. */ @Inject public CrowdPeerManager (Lifecycle cycle) { super(cycle); } // from interface CrowdPeerProvider public void deliverTell (ClientObject caller, UserMessage message, Name target, ChatService.TellListener listener) throws InvocationException { // we just forward the message as if it originated on this server _chatprov.deliverTell(message, target, listener); } // from interface CrowdPeerProvider public void deliverBroadcast ( ClientObject caller, Name from, byte levelOrMode, String bundle, String msg) { // deliver the broadcast locally on this server _chatprov.broadcast(from, levelOrMode, bundle, msg, false); } // from interface CrowdPeerProvider public void getChatHistory ( ClientObject caller, Name user, InvocationService.ResultListener lner) throws InvocationException { lner.requestProcessed(Lists.newArrayList(Iterables.filter( SpeakUtil.getChatHistory(user), IS_USER_MESSAGE))); } // from interface ChatProvider.ChatForwarder public boolean forwardTell (UserMessage message, Name target, ChatService.TellListener listener) { // look up their auth username from their visible name Name username = authFromViz(target); if (username == null) { return false; // sorry kid, don't know ya } // look through our peers to see if the target user is online on one of them for (PeerNode peer : _peers.values()) { CrowdNodeObject cnobj = (CrowdNodeObject)peer.nodeobj; if (cnobj == null) { continue; } // we have to use auth username to look up their ClientInfo CrowdClientInfo cinfo = (CrowdClientInfo)cnobj.clients.get(username); if (cinfo != null) { cnobj.crowdPeerService.deliverTell(peer.getClient(), message, target, listener); return true; } } return false; } // from interface ChatProvider.ChatForwarder public void forwardBroadcast (Name from, byte levelOrMode, String bundle, String msg) { for (PeerNode peer : _peers.values()) { if (peer.nodeobj != null) { ((CrowdNodeObject)peer.nodeobj).crowdPeerService.deliverBroadcast( peer.getClient(), from, levelOrMode, bundle, msg); } } } /** * Collects all chat messages heard by the given user on all peers. Must be called on the * dobj event thread. */ public void collectChatHistory (Name user, ResultListener<ChatHistoryResult> lner) { _omgr.requireEventThread(); new ChatHistoryCollector(user, lner).collect(); } @Override // from PeerManager public void shutdown () { super.shutdown(); // unregister our invocation service if (_nodeobj != null) { _invmgr.clearDispatcher(((CrowdNodeObject)_nodeobj).crowdPeerService); } // clear our chat forwarder registration _chatprov.setChatForwarder(null); } @Override // from PeerManager protected NodeObject createNodeObject () { return new CrowdNodeObject(); } @Override // from PeerManager protected ClientInfo createClientInfo () { return new CrowdClientInfo(); } @Override // from PeerManager protected void initClientInfo (PresentsSession client, ClientInfo info) { super.initClientInfo(client, info); ((CrowdClientInfo)info).visibleName = ((BodyObject)client.getClientObject()).getVisibleName(); } @Override // from PeerManager protected void didInit () { super.didInit(); // register and initialize our invocation service CrowdNodeObject cnobj = (CrowdNodeObject)_nodeobj; cnobj.setCrowdPeerService(_invmgr.registerDispatcher(new CrowdPeerDispatcher(this))); // register ourselves as a chat forwarder _chatprov.setChatForwarder(this); } /** * Converts a visible name to an authentication name. If this method returns null, the chat * system will act as if the vizname in question is not online. */ protected abstract Name authFromViz (Name vizname); /** * Asynchronously collects the chat history from all nodes for a given user. * TODO: refactor node parts into base class similar to PeerManager.NodeAction */ protected class ChatHistoryCollector { public ChatHistoryCollector (Name user, ResultListener<ChatHistoryResult> listener) { _user = user; _listener = listener; _result = new ChatHistoryResult(); _result.failedNodes = Sets.newHashSet(); _waiting = Sets.newHashSet(); } public void collect () { _result.history = Lists.newArrayList( Iterables.filter(SpeakUtil.getChatHistory(_user), IS_USER_MESSAGE)); for (PeerNode peer : _peers.values()) { final PeerNode fpeer = peer; ((CrowdNodeObject)peer.nodeobj).crowdPeerService.getChatHistory( peer.getClient(), _user, new InvocationService.ResultListener() { @Override public void requestProcessed (Object result) { processed(fpeer, result); } @Override public void requestFailed (String cause) { failed(fpeer, cause); } }); _waiting.add(peer.getNodeName()); } // timeout in 5 seconds if we haven't heard back from all nodes final long TIMEOUT = 5 * 1000; if (!maybeComplete()) { new Interval(_omgr) { @Override public void expired () { checkTimeout(); } }.schedule(TIMEOUT); } } protected void processed (PeerNode node, Object result) { String name = node.getNodeName(); if (!_waiting.remove(name)) { log.warning("Double chat history response from node", "name", name); return; } @SuppressWarnings("unchecked") List<ChatHistoryEntry> nodeMessages = (List<ChatHistoryEntry>)result; _result.history.addAll(nodeMessages); maybeComplete(); } protected void failed (PeerNode node, String cause) { String name = node.getNodeName(); _result.failedNodes.add(name); if (_waiting.remove(name)) { maybeComplete(); } else { log.warning("Double chat history response from node", "name", name); } } protected boolean maybeComplete () { if (!_waiting.isEmpty()) { return false; } Collections.sort(_result.history, SORT_BY_TIMESTAMP); _listener.requestCompleted(_result); return true; } protected void checkTimeout () { if (!_waiting.isEmpty()) { _result.failedNodes.addAll(_waiting); _waiting.clear(); maybeComplete(); } } protected Name _user; protected ResultListener<ChatHistoryResult> _listener; protected ChatHistoryResult _result; protected Set<String> _waiting; } @Inject protected InvocationManager _invmgr; @Inject protected ChatProvider _chatprov; protected static final Predicate<ChatHistoryEntry> IS_USER_MESSAGE = new Predicate<ChatHistoryEntry>() { @Override public boolean apply (ChatHistoryEntry entry) { return entry.message instanceof UserMessage; } }; protected static final Comparator<ChatHistoryEntry> SORT_BY_TIMESTAMP = new Comparator<ChatHistoryEntry>() { @Override public int compare (ChatHistoryEntry e1, ChatHistoryEntry e2) { return Comparators.compare(e1.message.timestamp, e2.message.timestamp); } }; }
src/java/com/threerings/crowd/peer/server/CrowdPeerManager.java
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2009 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.crowd.peer.server; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.inject.Inject; import com.google.inject.internal.Lists; import com.samskivert.util.Lifecycle; import com.threerings.util.Name; import com.threerings.presents.client.InvocationService.ResultListener; import com.threerings.presents.data.ClientObject; import com.threerings.presents.peer.data.ClientInfo; import com.threerings.presents.peer.data.NodeObject; import com.threerings.presents.peer.server.PeerManager; import com.threerings.presents.peer.server.PeerNode; import com.threerings.presents.server.InvocationException; import com.threerings.presents.server.InvocationManager; import com.threerings.presents.server.PresentsSession; import com.threerings.crowd.chat.client.ChatService; import com.threerings.crowd.chat.data.UserMessage; import com.threerings.crowd.chat.server.ChatProvider; import com.threerings.crowd.chat.server.SpeakUtil; import com.threerings.crowd.chat.server.SpeakUtil.ChatHistoryEntry; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.peer.data.CrowdClientInfo; import com.threerings.crowd.peer.data.CrowdNodeObject; /** * Extends the standard peer manager and bridges certain Crowd services. */ public abstract class CrowdPeerManager extends PeerManager implements CrowdPeerProvider, ChatProvider.ChatForwarder { /** * Creates an uninitialized peer manager. */ @Inject public CrowdPeerManager (Lifecycle cycle) { super(cycle); } // from interface CrowdPeerProvider public void deliverTell (ClientObject caller, UserMessage message, Name target, ChatService.TellListener listener) throws InvocationException { // we just forward the message as if it originated on this server _chatprov.deliverTell(message, target, listener); } // from interface CrowdPeerProvider public void deliverBroadcast ( ClientObject caller, Name from, byte levelOrMode, String bundle, String msg) { // deliver the broadcast locally on this server _chatprov.broadcast(from, levelOrMode, bundle, msg, false); } // from interface CrowdPeerProvider public void getChatHistory (ClientObject caller, Name user, ResultListener lner) throws InvocationException { lner.requestProcessed(Lists.newArrayList(Iterables.filter( SpeakUtil.getChatHistory(user), IS_USER_MESSAGE))); } // from interface ChatProvider.ChatForwarder public boolean forwardTell (UserMessage message, Name target, ChatService.TellListener listener) { // look up their auth username from their visible name Name username = authFromViz(target); if (username == null) { return false; // sorry kid, don't know ya } // look through our peers to see if the target user is online on one of them for (PeerNode peer : _peers.values()) { CrowdNodeObject cnobj = (CrowdNodeObject)peer.nodeobj; if (cnobj == null) { continue; } // we have to use auth username to look up their ClientInfo CrowdClientInfo cinfo = (CrowdClientInfo)cnobj.clients.get(username); if (cinfo != null) { cnobj.crowdPeerService.deliverTell(peer.getClient(), message, target, listener); return true; } } return false; } // from interface ChatProvider.ChatForwarder public void forwardBroadcast (Name from, byte levelOrMode, String bundle, String msg) { for (PeerNode peer : _peers.values()) { if (peer.nodeobj != null) { ((CrowdNodeObject)peer.nodeobj).crowdPeerService.deliverBroadcast( peer.getClient(), from, levelOrMode, bundle, msg); } } } @Override // from PeerManager public void shutdown () { super.shutdown(); // unregister our invocation service if (_nodeobj != null) { _invmgr.clearDispatcher(((CrowdNodeObject)_nodeobj).crowdPeerService); } // clear our chat forwarder registration _chatprov.setChatForwarder(null); } @Override // from PeerManager protected NodeObject createNodeObject () { return new CrowdNodeObject(); } @Override // from PeerManager protected ClientInfo createClientInfo () { return new CrowdClientInfo(); } @Override // from PeerManager protected void initClientInfo (PresentsSession client, ClientInfo info) { super.initClientInfo(client, info); ((CrowdClientInfo)info).visibleName = ((BodyObject)client.getClientObject()).getVisibleName(); } @Override // from PeerManager protected void didInit () { super.didInit(); // register and initialize our invocation service CrowdNodeObject cnobj = (CrowdNodeObject)_nodeobj; cnobj.setCrowdPeerService(_invmgr.registerDispatcher(new CrowdPeerDispatcher(this))); // register ourselves as a chat forwarder _chatprov.setChatForwarder(this); } /** * Converts a visible name to an authentication name. If this method returns null, the chat * system will act as if the vizname in question is not online. */ protected abstract Name authFromViz (Name vizname); @Inject protected InvocationManager _invmgr; @Inject protected ChatProvider _chatprov; protected static final Predicate<ChatHistoryEntry> IS_USER_MESSAGE = new Predicate<ChatHistoryEntry>() { @Override public boolean apply (ChatHistoryEntry entry) { return entry.message instanceof UserMessage; } }; }
Method to poll all peers for chat history and asynchronously return the result. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5993 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/crowd/peer/server/CrowdPeerManager.java
Method to poll all peers for chat history and asynchronously return the result.
<ide><path>rc/java/com/threerings/crowd/peer/server/CrowdPeerManager.java <ide> <ide> package com.threerings.crowd.peer.server; <ide> <add>import java.util.Collections; <add>import java.util.Comparator; <add>import java.util.List; <add>import java.util.Set; <add> <ide> import com.google.common.base.Predicate; <ide> import com.google.common.collect.Iterables; <add>import com.google.common.collect.Sets; <ide> import com.google.inject.Inject; <ide> import com.google.inject.internal.Lists; <ide> <add>import com.samskivert.util.Comparators; <add>import com.samskivert.util.Interval; <ide> import com.samskivert.util.Lifecycle; <add>import com.samskivert.util.ResultListener; <ide> import com.threerings.util.Name; <ide> <del>import com.threerings.presents.client.InvocationService.ResultListener; <add>import com.threerings.presents.client.InvocationService; <ide> import com.threerings.presents.data.ClientObject; <ide> import com.threerings.presents.peer.data.ClientInfo; <ide> import com.threerings.presents.peer.data.NodeObject; <ide> import com.threerings.crowd.peer.data.CrowdClientInfo; <ide> import com.threerings.crowd.peer.data.CrowdNodeObject; <ide> <add>import static com.threerings.crowd.Log.log; <add> <ide> /** <ide> * Extends the standard peer manager and bridges certain Crowd services. <ide> */ <ide> implements CrowdPeerProvider, ChatProvider.ChatForwarder <ide> { <ide> /** <add> * Value asynchronously returned by {@link #collectChatHistory} after polling all peer nodes. <add> */ <add> public static class ChatHistoryResult <add> { <add> /** The set of nodes that either did not reply within the timeout, or had a failure. */ <add> public Set<String> failedNodes; <add> <add> /** The things in the user's chat history, aggregated from all nodes and sorted by <add> * timestamp. */ <add> public List<ChatHistoryEntry> history; <add> } <add> <add> /** <ide> * Creates an uninitialized peer manager. <ide> */ <ide> @Inject public CrowdPeerManager (Lifecycle cycle) <ide> } <ide> <ide> // from interface CrowdPeerProvider <del> public void getChatHistory (ClientObject caller, Name user, ResultListener lner) <add> public void getChatHistory ( <add> ClientObject caller, Name user, InvocationService.ResultListener lner) <ide> throws InvocationException <ide> { <ide> lner.requestProcessed(Lists.newArrayList(Iterables.filter( <ide> } <ide> } <ide> <add> /** <add> * Collects all chat messages heard by the given user on all peers. Must be called on the <add> * dobj event thread. <add> */ <add> public void collectChatHistory (Name user, ResultListener<ChatHistoryResult> lner) <add> { <add> _omgr.requireEventThread(); <add> new ChatHistoryCollector(user, lner).collect(); <add> } <add> <ide> @Override // from PeerManager <ide> public void shutdown () <ide> { <ide> * system will act as if the vizname in question is not online. <ide> */ <ide> protected abstract Name authFromViz (Name vizname); <add> <add> /** <add> * Asynchronously collects the chat history from all nodes for a given user. <add> * TODO: refactor node parts into base class similar to PeerManager.NodeAction <add> */ <add> protected class ChatHistoryCollector <add> { <add> public ChatHistoryCollector (Name user, ResultListener<ChatHistoryResult> listener) <add> { <add> _user = user; <add> _listener = listener; <add> <add> _result = new ChatHistoryResult(); <add> _result.failedNodes = Sets.newHashSet(); <add> _waiting = Sets.newHashSet(); <add> } <add> <add> public void collect () <add> { <add> _result.history = Lists.newArrayList( <add> Iterables.filter(SpeakUtil.getChatHistory(_user), IS_USER_MESSAGE)); <add> <add> for (PeerNode peer : _peers.values()) { <add> final PeerNode fpeer = peer; <add> ((CrowdNodeObject)peer.nodeobj).crowdPeerService.getChatHistory( <add> peer.getClient(), _user, new InvocationService.ResultListener() { <add> @Override public void requestProcessed (Object result) { <add> processed(fpeer, result); <add> } <add> @Override public void requestFailed (String cause) { <add> failed(fpeer, cause); <add> } <add> }); <add> _waiting.add(peer.getNodeName()); <add> } <add> <add> // timeout in 5 seconds if we haven't heard back from all nodes <add> final long TIMEOUT = 5 * 1000; <add> if (!maybeComplete()) { <add> new Interval(_omgr) { <add> @Override public void expired () { <add> checkTimeout(); <add> } <add> }.schedule(TIMEOUT); <add> } <add> } <add> <add> protected void processed (PeerNode node, Object result) <add> { <add> String name = node.getNodeName(); <add> if (!_waiting.remove(name)) { <add> log.warning("Double chat history response from node", "name", name); <add> return; <add> } <add> <add> @SuppressWarnings("unchecked") <add> List<ChatHistoryEntry> nodeMessages = (List<ChatHistoryEntry>)result; <add> _result.history.addAll(nodeMessages); <add> maybeComplete(); <add> } <add> <add> protected void failed (PeerNode node, String cause) <add> { <add> String name = node.getNodeName(); <add> _result.failedNodes.add(name); <add> <add> if (_waiting.remove(name)) { <add> maybeComplete(); <add> } else { <add> log.warning("Double chat history response from node", "name", name); <add> } <add> } <add> <add> protected boolean maybeComplete () <add> { <add> if (!_waiting.isEmpty()) { <add> return false; <add> } <add> <add> Collections.sort(_result.history, SORT_BY_TIMESTAMP); <add> _listener.requestCompleted(_result); <add> return true; <add> } <add> <add> protected void checkTimeout () <add> { <add> if (!_waiting.isEmpty()) { <add> _result.failedNodes.addAll(_waiting); <add> _waiting.clear(); <add> maybeComplete(); <add> } <add> } <add> <add> protected Name _user; <add> protected ResultListener<ChatHistoryResult> _listener; <add> protected ChatHistoryResult _result; <add> protected Set<String> _waiting; <add> } <ide> <ide> @Inject protected InvocationManager _invmgr; <ide> @Inject protected ChatProvider _chatprov; <ide> return entry.message instanceof UserMessage; <ide> } <ide> }; <add> <add> protected static final Comparator<ChatHistoryEntry> SORT_BY_TIMESTAMP = <add> new Comparator<ChatHistoryEntry>() { <add> @Override public int compare (ChatHistoryEntry e1, ChatHistoryEntry e2) { <add> return Comparators.compare(e1.message.timestamp, e2.message.timestamp); <add> } <add> }; <ide> }
Java
agpl-3.0
4480fd611f06f58c59381e0535ae9720d0913e4b
0
PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1
package nl.mpi.kinnate.ui.relationsettings; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import javax.swing.JButton; import javax.swing.table.AbstractTableModel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.kindata.RelationTypeDefinition; import nl.mpi.kinnate.svg.DataStoreSvg; /** * Document : RelationTypesTableModel * Created on : Jan 2, 2012, 2:05:08 PM * Author : Peter Withers */ public class RelationTypesTableModel extends AbstractTableModel implements ActionListener { SavePanel savePanel; DataStoreSvg dataStoreSvg; HashSet<RelationTypeDefinition> checkBoxSet = new HashSet<RelationTypeDefinition>(); JButton deleteSelectedButton; public RelationTypesTableModel(SavePanel savePanel, DataStoreSvg dataStoreSvg, JButton deleteSelectedButton) { this.savePanel = savePanel; this.dataStoreSvg = dataStoreSvg; this.deleteSelectedButton = deleteSelectedButton; deleteSelectedButton.setEnabled(false); deleteSelectedButton.addActionListener(this); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex != 3; // prevent non colour data being entered into the colour field } public int getColumnCount() { return 7; } @Override public String getColumnName(int column) { switch (column) { case 0: return "Display Name"; case 1: return "Data Category"; case 2: return "Relation Type"; case 3: return "Line Colour"; case 4: return "Line Width"; case 5: return "Line Stye"; case 6: return ""; default: throw new UnsupportedOperationException("Too many columns"); } } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 6: return Boolean.class; default: return super.getColumnClass(columnIndex); } } public int getRowCount() { return dataStoreSvg.getRelationTypeDefinitions().length + 1; } public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex < dataStoreSvg.getRelationTypeDefinitions().length) { RelationTypeDefinition kinType = dataStoreSvg.getRelationTypeDefinitions()[rowIndex]; switch (columnIndex) { case 0: return kinType.getDisplayName(); case 1: return kinType.getDataCategory(); case 2: return kinType.getRelationType(); case 3: return kinType.getLineColour(); case 4: return kinType.getLineWidth(); case 5: return kinType.getLineStye(); case 6: return checkBoxSet.contains(kinType); default: throw new UnsupportedOperationException("Too many columns"); } } else { switch (columnIndex) { case 6: return false; default: return ""; // add a blank row at the end } } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { String stringValue = aValue.toString(); final RelationTypeDefinition[] kinTypeDefinitions = dataStoreSvg.getRelationTypeDefinitions(); if (rowIndex >= dataStoreSvg.getRelationTypeDefinitions().length && columnIndex == 6) { if (checkBoxSet.isEmpty()) { checkBoxSet.addAll(Arrays.asList(kinTypeDefinitions)); } else { checkBoxSet.clear(); } deleteSelectedButton.setEnabled(!checkBoxSet.isEmpty()); fireTableDataChanged(); return; } String displayName = "undefined"; RelationType relationType = DataTypes.RelationType.ancestor; String dataCategory = ""; String lineColour = "#999999"; int lineWidth = 2; String lineStye = null; RelationTypeDefinition kinType = null; if (rowIndex < dataStoreSvg.getRelationTypeDefinitions().length) { kinType = kinTypeDefinitions[rowIndex]; displayName = kinType.getDisplayName(); relationType = kinType.getRelationType(); dataCategory = kinType.getDataCategory(); lineColour = kinType.getLineColour(); lineWidth = kinType.getLineWidth(); lineStye = kinType.getLineStye(); } switch (columnIndex) { case 0: displayName = stringValue; break; case 1: dataCategory = stringValue; break; case 2: relationType = DataTypes.RelationType.valueOf(stringValue); break; case 3: lineColour = stringValue; fireTableCellUpdated(rowIndex, columnIndex); // update the colour in the modified table cell break; case 4: lineWidth = Integer.parseInt(stringValue.replaceAll("[^0-9]", "")); break; case 5: lineStye = stringValue; break; case 6: if ((Boolean) aValue) { checkBoxSet.add(kinType); } else { checkBoxSet.remove(kinType); } deleteSelectedButton.setEnabled(!checkBoxSet.isEmpty()); fireTableDataChanged(); return; default: throw new UnsupportedOperationException("Too many columns"); } if (rowIndex < dataStoreSvg.getRelationTypeDefinitions().length) { kinTypeDefinitions[rowIndex] = new RelationTypeDefinition(displayName, dataCategory, relationType, lineColour, lineWidth, lineStye); dataStoreSvg.setRelationTypeDefinitions(kinTypeDefinitions); } else { if ("".equals(aValue)) { // ignore if no text has been entered return; } ArrayList<RelationTypeDefinition> kinTypesList = new ArrayList<RelationTypeDefinition>(Arrays.asList(kinTypeDefinitions)); kinTypesList.add(new RelationTypeDefinition(displayName, dataCategory, relationType, lineColour, lineWidth, lineStye)); dataStoreSvg.setRelationTypeDefinitions(kinTypesList.toArray(new RelationTypeDefinition[]{})); } savePanel.updateGraph(); savePanel.requiresSave(); super.setValueAt(aValue, rowIndex, columnIndex); } public void actionPerformed(ActionEvent e) { ArrayList<RelationTypeDefinition> kinTypesList = new ArrayList<RelationTypeDefinition>(Arrays.asList(dataStoreSvg.getRelationTypeDefinitions())); for (RelationTypeDefinition kinType : checkBoxSet) { kinTypesList.remove(kinType); } dataStoreSvg.setRelationTypeDefinitions(kinTypesList.toArray(new RelationTypeDefinition[]{})); checkBoxSet.clear(); fireTableDataChanged(); savePanel.updateGraph(); } }
desktop/src/main/java/nl/mpi/kinnate/ui/relationsettings/RelationTypesTableModel.java
package nl.mpi.kinnate.ui.relationsettings; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import javax.swing.JButton; import javax.swing.table.AbstractTableModel; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import nl.mpi.kinnate.kindata.RelationTypeDefinition; import nl.mpi.kinnate.svg.DataStoreSvg; /** * Document : RelationTypesTableModel * Created on : Jan 2, 2012, 2:05:08 PM * Author : Peter Withers */ public class RelationTypesTableModel extends AbstractTableModel implements ActionListener { SavePanel savePanel; DataStoreSvg dataStoreSvg; HashSet<RelationTypeDefinition> checkBoxSet = new HashSet<RelationTypeDefinition>(); JButton deleteSelectedButton; public RelationTypesTableModel(SavePanel savePanel, DataStoreSvg dataStoreSvg, JButton deleteSelectedButton) { this.savePanel = savePanel; this.dataStoreSvg = dataStoreSvg; this.deleteSelectedButton = deleteSelectedButton; deleteSelectedButton.setEnabled(false); deleteSelectedButton.addActionListener(this); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex != 3; // prevent non colour data being entered into the colour field } public int getColumnCount() { return 7; } @Override public String getColumnName(int column) { switch (column) { case 0: return "Display Name"; case 1: return "Data Category"; case 2: return "Relation Type"; case 3: return "Line Colour"; case 4: return "Line Width"; case 5: return "Line Stye"; case 6: return ""; default: throw new UnsupportedOperationException("Too many columns"); } } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 6: return Boolean.class; default: return super.getColumnClass(columnIndex); } } public int getRowCount() { return dataStoreSvg.getRelationTypeDefinitions().length + 1; } public Object getValueAt(int rowIndex, int columnIndex) { if (rowIndex < dataStoreSvg.getRelationTypeDefinitions().length) { RelationTypeDefinition kinType = dataStoreSvg.getRelationTypeDefinitions()[rowIndex]; switch (columnIndex) { case 0: return kinType.getDisplayName(); case 1: return kinType.getDataCategory(); case 2: return kinType.getRelationType(); case 3: return kinType.getLineColour(); case 4: return kinType.getLineWidth(); case 5: return kinType.getLineStye(); case 6: return checkBoxSet.contains(kinType); default: throw new UnsupportedOperationException("Too many columns"); } } else { switch (columnIndex) { case 6: return false; default: return ""; // add a blank row at the end } } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { String stringValue = aValue.toString(); final RelationTypeDefinition[] kinTypeDefinitions = dataStoreSvg.getRelationTypeDefinitions(); if (rowIndex >= dataStoreSvg.getRelationTypeDefinitions().length && columnIndex == 6) { if (checkBoxSet.isEmpty()) { checkBoxSet.addAll(Arrays.asList(kinTypeDefinitions)); } else { checkBoxSet.clear(); } deleteSelectedButton.setEnabled(!checkBoxSet.isEmpty()); fireTableDataChanged(); return; } String displayName = "undefined"; RelationType relationType = DataTypes.RelationType.ancestor; String dataCategory = ""; String lineColour = "#999999"; int lineWidth = 2; String lineStye = null; RelationTypeDefinition kinType = null; if (rowIndex < dataStoreSvg.getRelationTypeDefinitions().length) { kinType = kinTypeDefinitions[rowIndex]; displayName = kinType.getDisplayName(); relationType = kinType.getRelationType(); dataCategory = kinType.getDataCategory(); lineColour = kinType.getLineColour(); lineWidth = kinType.getLineWidth(); lineStye = kinType.getLineStye(); } switch (columnIndex) { case 0: displayName = stringValue; break; case 1: dataCategory = stringValue; break; case 2: relationType = DataTypes.RelationType.valueOf(stringValue); break; case 3: lineColour = stringValue; fireTableCellUpdated(rowIndex, columnIndex); // update the colour in the modified table cell break; case 4: lineWidth = Integer.parseInt(stringValue); break; case 5: lineStye = stringValue; break; case 6: if ((Boolean) aValue) { checkBoxSet.add(kinType); } else { checkBoxSet.remove(kinType); } deleteSelectedButton.setEnabled(!checkBoxSet.isEmpty()); fireTableDataChanged(); return; default: throw new UnsupportedOperationException("Too many columns"); } if (rowIndex < dataStoreSvg.getRelationTypeDefinitions().length) { kinTypeDefinitions[rowIndex] = new RelationTypeDefinition(displayName, dataCategory, relationType, lineColour, lineWidth, lineStye); dataStoreSvg.setRelationTypeDefinitions(kinTypeDefinitions); } else { if ("".equals(aValue)) { // ignore if no text has been entered return; } ArrayList<RelationTypeDefinition> kinTypesList = new ArrayList<RelationTypeDefinition>(Arrays.asList(kinTypeDefinitions)); kinTypesList.add(new RelationTypeDefinition(displayName, dataCategory, relationType, lineColour, lineWidth, lineStye)); dataStoreSvg.setRelationTypeDefinitions(kinTypesList.toArray(new RelationTypeDefinition[]{})); } savePanel.updateGraph(); savePanel.requiresSave(); super.setValueAt(aValue, rowIndex, columnIndex); } public void actionPerformed(ActionEvent e) { ArrayList<RelationTypeDefinition> kinTypesList = new ArrayList<RelationTypeDefinition>(Arrays.asList(dataStoreSvg.getRelationTypeDefinitions())); for (RelationTypeDefinition kinType : checkBoxSet) { kinTypesList.remove(kinType); } dataStoreSvg.setRelationTypeDefinitions(kinTypesList.toArray(new RelationTypeDefinition[]{})); checkBoxSet.clear(); fireTableDataChanged(); savePanel.updateGraph(); } }
Added a settings panel for the relation type definitions. Added the relation type definitions to the data stored in the svg. Added the DCR to the relation types and its settings UI. Restructured the relation type data structure to suit the recent changes. Added drag handles for each custom relation type. Enabled line colour and width to be displayed based in the relation settings for the diagram. Modified the kin type query to compare all relations for an individual rather than just the first relation. Modified the entity merger and duplicator to consider all relations for an individual rather than just the first relation for each pair.
desktop/src/main/java/nl/mpi/kinnate/ui/relationsettings/RelationTypesTableModel.java
Added a settings panel for the relation type definitions. Added the relation type definitions to the data stored in the svg. Added the DCR to the relation types and its settings UI. Restructured the relation type data structure to suit the recent changes. Added drag handles for each custom relation type. Enabled line colour and width to be displayed based in the relation settings for the diagram. Modified the kin type query to compare all relations for an individual rather than just the first relation. Modified the entity merger and duplicator to consider all relations for an individual rather than just the first relation for each pair.
<ide><path>esktop/src/main/java/nl/mpi/kinnate/ui/relationsettings/RelationTypesTableModel.java <ide> fireTableCellUpdated(rowIndex, columnIndex); // update the colour in the modified table cell <ide> break; <ide> case 4: <del> lineWidth = Integer.parseInt(stringValue); <add> lineWidth = Integer.parseInt(stringValue.replaceAll("[^0-9]", "")); <ide> break; <ide> case 5: <ide> lineStye = stringValue;
Java
apache-2.0
c1e47ec47ca2ec4d5bd3e60cd1e51c91e8cef2eb
0
apache/camel,gnodet/camel,cunningt/camel,tdiesler/camel,tdiesler/camel,cunningt/camel,tadayosi/camel,apache/camel,adessaigne/camel,apache/camel,tadayosi/camel,tdiesler/camel,pax95/camel,adessaigne/camel,gnodet/camel,cunningt/camel,nikhilvibhav/camel,tdiesler/camel,gnodet/camel,apache/camel,pmoerenhout/camel,adessaigne/camel,pmoerenhout/camel,pmoerenhout/camel,gnodet/camel,christophd/camel,apache/camel,christophd/camel,pax95/camel,pax95/camel,christophd/camel,adessaigne/camel,pmoerenhout/camel,pax95/camel,tdiesler/camel,pax95/camel,cunningt/camel,tadayosi/camel,tadayosi/camel,gnodet/camel,tadayosi/camel,pmoerenhout/camel,apache/camel,christophd/camel,nikhilvibhav/camel,cunningt/camel,tdiesler/camel,cunningt/camel,adessaigne/camel,pmoerenhout/camel,tadayosi/camel,pax95/camel,nikhilvibhav/camel,christophd/camel,adessaigne/camel,christophd/camel,nikhilvibhav/camel
/* * 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.camel.processor.loadbalancer; import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.apache.camel.AsyncProcessor; import org.apache.camel.Navigate; import org.apache.camel.Processor; import org.apache.camel.spi.IdAware; import org.apache.camel.spi.RouteIdAware; import org.apache.camel.support.AsyncProcessorSupport; import org.apache.camel.support.service.ServiceHelper; /** * A default base class for a {@link LoadBalancer} implementation. */ public abstract class LoadBalancerSupport extends AsyncProcessorSupport implements LoadBalancer, Navigate<Processor>, IdAware, RouteIdAware { private final AtomicReference<AsyncProcessor[]> processors = new AtomicReference<>(new AsyncProcessor[0]); private String id; private String routeId; @Override public void addProcessor(AsyncProcessor processor) { processors.updateAndGet(op -> doAdd(processor, op)); } @Override public void removeProcessor(AsyncProcessor processor) { processors.updateAndGet(op -> doRemove(processor, op)); } private AsyncProcessor[] doAdd(AsyncProcessor processor, AsyncProcessor[] op) { int len = op.length; AsyncProcessor[] np = Arrays.copyOf(op, len + 1, op.getClass()); np[len] = processor; return np; } private AsyncProcessor[] doRemove(AsyncProcessor processor, AsyncProcessor[] op) { int len = op.length; for (int index = 0; index < len; index++) { if (op[index].equals(processor)) { AsyncProcessor[] np = (AsyncProcessor[]) Array.newInstance(AsyncProcessor.class, len - 1); System.arraycopy(op, 0, np, 0, index); System.arraycopy(op, index + 1, np, index, len - index - 1); return np; } } return op; } @Override public List<AsyncProcessor> getProcessors() { return Arrays.asList(processors.get()); } protected AsyncProcessor[] doGetProcessors() { return processors.get(); } @Override @SuppressWarnings("unchecked") public List<Processor> next() { if (!hasNext()) { return null; } return (List) getProcessors(); } @Override public boolean hasNext() { return doGetProcessors().length > 0; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getRouteId() { return routeId; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } @Override protected void doInit() throws Exception { ServiceHelper.initService((Object[]) processors.get()); } @Override protected void doStart() throws Exception { ServiceHelper.startService((Object[]) processors.get()); } @Override protected void doStop() throws Exception { ServiceHelper.stopService((Object[]) processors.get()); } @Override protected void doShutdown() throws Exception { AsyncProcessor[] p = processors.get(); ServiceHelper.stopAndShutdownServices((Object[]) p); for (AsyncProcessor processor : p) { removeProcessor(processor); } } @Override public String toString() { return getClass().getSimpleName(); } }
core/camel-core-processor/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.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.camel.processor.loadbalancer; import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.apache.camel.AsyncProcessor; import org.apache.camel.Navigate; import org.apache.camel.Processor; import org.apache.camel.spi.IdAware; import org.apache.camel.spi.RouteIdAware; import org.apache.camel.support.AsyncProcessorSupport; import org.apache.camel.support.service.ServiceHelper; /** * A default base class for a {@link LoadBalancer} implementation. */ public abstract class LoadBalancerSupport extends AsyncProcessorSupport implements LoadBalancer, Navigate<Processor>, IdAware, RouteIdAware { private final AtomicReference<AsyncProcessor[]> processors = new AtomicReference<>(new AsyncProcessor[0]); private String id; private String routeId; @Override public void addProcessor(AsyncProcessor processor) { processors.updateAndGet(op -> doAdd(processor, op)); } @Override public void removeProcessor(AsyncProcessor processor) { processors.updateAndGet(op -> doRemove(processor, op)); } private AsyncProcessor[] doAdd(AsyncProcessor processor, AsyncProcessor[] op) { int len = op.length; AsyncProcessor[] np = Arrays.copyOf(op, len + 1, op.getClass()); np[len] = processor; return np; } private AsyncProcessor[] doRemove(AsyncProcessor processor, AsyncProcessor[] op) { int len = op.length; for (int index = 0; index < len; index++) { if (op[index].equals(processor)) { AsyncProcessor[] np = (AsyncProcessor[]) Array.newInstance(AsyncProcessor.class, len - 1); System.arraycopy(op, 0, np, 0, index); System.arraycopy(op, index + 1, np, index, len - index - 1); return np; } } return op; } @Override public List<AsyncProcessor> getProcessors() { return Arrays.asList(processors.get()); } protected AsyncProcessor[] doGetProcessors() { return processors.get(); } @Override @SuppressWarnings("unchecked") public List<Processor> next() { if (!hasNext()) { return null; } return (List) getProcessors(); } @Override public boolean hasNext() { return doGetProcessors().length > 0; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getRouteId() { return routeId; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } @Override protected void doInit() throws Exception { ServiceHelper.initService((Object[]) processors.get()); } @Override protected void doStart() throws Exception { ServiceHelper.startService((Object[]) processors.get()); } @Override protected void doStop() throws Exception { ServiceHelper.stopService((Object[]) processors.get()); } @Override protected void doShutdown() throws Exception { AsyncProcessor[] p = processors.get(); ServiceHelper.stopAndShutdownServices((Object[]) p); for (AsyncProcessor processor : p) { removeProcessor(processor); } } @Override public String toString() { return getClass().getSimpleName() + Arrays.toString(doGetProcessors()); } }
Polished
core/camel-core-processor/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java
Polished
<ide><path>ore/camel-core-processor/src/main/java/org/apache/camel/processor/loadbalancer/LoadBalancerSupport.java <ide> <ide> @Override <ide> public String toString() { <del> return getClass().getSimpleName() + Arrays.toString(doGetProcessors()); <add> return getClass().getSimpleName(); <ide> } <ide> <ide> }
Java
mit
0fbdd78ce1f65d874b513d1f65019bada32522ba
0
sauliusg/jabref,bartsch-dev/jabref,Braunch/jabref,sauliusg/jabref,mredaelli/jabref,mairdl/jabref,motokito/jabref,Mr-DLib/jabref,bartsch-dev/jabref,ayanai1/jabref,zellerdev/jabref,JabRef/jabref,Siedlerchr/jabref,grimes2/jabref,tschechlovdev/jabref,bartsch-dev/jabref,obraliar/jabref,Mr-DLib/jabref,ayanai1/jabref,jhshinn/jabref,Siedlerchr/jabref,oscargus/jabref,tschechlovdev/jabref,ayanai1/jabref,Siedlerchr/jabref,shitikanth/jabref,tobiasdiez/jabref,motokito/jabref,motokito/jabref,Siedlerchr/jabref,shitikanth/jabref,obraliar/jabref,jhshinn/jabref,motokito/jabref,Braunch/jabref,JabRef/jabref,zellerdev/jabref,motokito/jabref,shitikanth/jabref,grimes2/jabref,Mr-DLib/jabref,tobiasdiez/jabref,oscargus/jabref,jhshinn/jabref,mairdl/jabref,mredaelli/jabref,zellerdev/jabref,mredaelli/jabref,Braunch/jabref,jhshinn/jabref,Mr-DLib/jabref,zellerdev/jabref,tschechlovdev/jabref,bartsch-dev/jabref,JabRef/jabref,zellerdev/jabref,mairdl/jabref,sauliusg/jabref,grimes2/jabref,mairdl/jabref,Braunch/jabref,mredaelli/jabref,ayanai1/jabref,shitikanth/jabref,oscargus/jabref,tobiasdiez/jabref,Mr-DLib/jabref,sauliusg/jabref,tschechlovdev/jabref,jhshinn/jabref,oscargus/jabref,obraliar/jabref,shitikanth/jabref,Braunch/jabref,tobiasdiez/jabref,obraliar/jabref,oscargus/jabref,mairdl/jabref,tschechlovdev/jabref,JabRef/jabref,mredaelli/jabref,ayanai1/jabref,obraliar/jabref,grimes2/jabref,bartsch-dev/jabref,grimes2/jabref
package net.sf.jabref.export.layout.format; import net.sf.jabref.export.layout.*; import net.sf.jabref.Globals; public class RTFChars implements LayoutFormatter { public String format(String field) { int i; field = firstFormat(field); StringBuffer sb = new StringBuffer(""); StringBuffer currentCommand = null; char c; boolean escaped = false, incommand = false; for (i = 0; i < field.length(); i++) { c = field.charAt(i); if (escaped && (c == '\\')) { sb.append('\\'); escaped = false; } else if (c == '\\') { escaped = true; incommand = true; currentCommand = new StringBuffer(); } else if (!incommand && (c == '{' || c == '}')) { // Swallow the brace. } else if (Character.isLetter((char) c) || (Globals.SPECIAL_COMMAND_CHARS.indexOf("" + (char) c) >= 0)) { escaped = false; if (!incommand) sb.append((char) c); // Else we are in a command, and should not keep the letter. else { currentCommand.append((char) c); testCharCom: if ((currentCommand.length() == 1) && (Globals.SPECIAL_COMMAND_CHARS.indexOf(currentCommand.toString()) >= 0)) { // This indicates that we are in a command of the type // \^o or \~{n} if (i >= field.length() - 1) break testCharCom; String command = currentCommand.toString(); i++; c = field.charAt(i); // System.out.println("next: "+(char)c); String combody; if (c == '{') { IntAndString part = getPart(field, i); i += part.i; combody = part.s; } else { combody = field.substring(i, i + 1); // System.out.println("... "+combody); } // System.out.println(command+combody); Object result = Globals.RTFCHARS.get(command + combody); if (result != null) sb.append((String) result); incommand = false; escaped = false; } } } else { // if (!incommand || ((c!='{') && !Character.isWhitespace(c))) testContent: if (!incommand || (!Character.isWhitespace(c) && (c != '{'))) sb.append((char) c); else { // First test if we are already at the end of the string. if (i >= field.length() - 1) break testContent; if (c == '{') { String command = currentCommand.toString(); // Then test if we are dealing with a italics or bold // command. If so, handle. if (command.equals("emph") || command.equals("textit")) { IntAndString part = getPart(field, i); i += part.i; sb.append("}{\\i ").append(part.s).append("}{"); } else if (command.equals("textbf")) { IntAndString part = getPart(field, i); i += part.i; sb.append("}{\\b ").append(part.s).append("}{"); } } else sb.append((char) c); } incommand = false; escaped = false; } } return sb.toString(); // field.replaceAll("\\\\emph", "").replaceAll("\\\\em", // "").replaceAll("\\\\textbf", ""); } private String firstFormat(String s) { return s;// s.replaceAll("&|\\\\&","&amp;");//.replaceAll("--", // "&mdash;"); } private IntAndString getPart(String text, int i) { char c; int count = 0;// , i=index; StringBuffer part = new StringBuffer(); while ((count >= 0) && (i < text.length())) { i++; c = text.charAt(i); if (c == '}') count--; else if (c == '{') count++; part.append((char) c); } // System.out.println("part: "+part.toString()+"\nformatted: // "+format(part.toString())); return new IntAndString(part.length(), format(part.toString())); } private class IntAndString { public int i; String s; public IntAndString(int i, String s) { this.i = i; this.s = s; } } }
src/java/net/sf/jabref/export/layout/format/RTFChars.java
package net.sf.jabref.export.layout.format; import net.sf.jabref.export.layout.*; import net.sf.jabref.Globals; public class RTFChars implements LayoutFormatter { public String format(String field) { int i; field = firstFormat(field); StringBuffer sb = new StringBuffer(""); StringBuffer currentCommand = null; char c; boolean escaped = false, incommand = false; for (i=0; i<field.length(); i++) { c = field.charAt(i); if (escaped && (c == '\\')) { sb.append('\\'); escaped = false; } else if (c == '\\') { escaped = true; incommand = true; currentCommand = new StringBuffer(); } else if (!incommand && (c=='{' || c=='}')) { // Swallow the brace. } else if (Character.isLetter((char)c) || (Globals.SPECIAL_COMMAND_CHARS.indexOf(""+(char)c) >= 0)) { escaped = false; if (!incommand) sb.append((char)c); // Else we are in a command, and should not keep the letter. else { currentCommand.append( (char) c); testCharCom: if ((currentCommand.length() == 1) && (Globals.SPECIAL_COMMAND_CHARS.indexOf(currentCommand.toString()) >= 0)) { // This indicates that we are in a command of the type \^o or \~{n} if (i >= field.length()-1) break testCharCom; String command = currentCommand.toString(); i++; c = field.charAt(i); //System.out.println("next: "+(char)c); String combody; if (c == '{') { IntAndString part = getPart(field, i); i += part.i; combody = part.s; } else { combody = field.substring(i,i+1); //System.out.println("... "+combody); } //System.out.println(command+combody); Object result = Globals.RTFCHARS.get(command+combody); if (result != null) sb.append((String)result); incommand = false; escaped = false; } } } else { //if (!incommand || ((c!='{') && !Character.isWhitespace(c))) testContent: if (!incommand || (!Character.isWhitespace(c) && (c != '{'))) sb.append((char)c); else { // First test if we are already at the end of the string. if (i >= field.length()-1) break testContent; if (c == '{') { String command = currentCommand.toString(); // Then test if we are dealing with a italics or bold command. If so, handle. if (command.equals("emph") || command.equals("textit")) { IntAndString part = getPart(field, i); i += part.i; sb.append("}{\\i ").append(part.s).append("}{"); } else if (command.equals("textbf")) { IntAndString part = getPart(field, i); i += part.i; sb.append("}{\\b ").append(part.s).append("}{"); } } else sb.append((char)c); } incommand = false; escaped = false; } } return sb.toString(); //field.replaceAll("\\\\emph", "").replaceAll("\\\\em", "").replaceAll("\\\\textbf", ""); } private String firstFormat(String s) { return s;//s.replaceAll("&|\\\\&","&amp;");//.replaceAll("--", "&mdash;"); } private IntAndString getPart(String text, int i) { char c; int count = 0;//, i=index; StringBuffer part = new StringBuffer(); while ((count >= 0) && (i < text.length())) { i++; c = text.charAt(i); if (c == '}') count--; else if (c == '{') count++; part.append((char)c); } //System.out.println("part: "+part.toString()+"\nformatted: "+format(part.toString())); return new IntAndString(part.length(), format(part.toString())); } private class IntAndString{ public int i; String s; public IntAndString(int i, String s) { this.i = i; this.s = s; } } }
Format.
src/java/net/sf/jabref/export/layout/format/RTFChars.java
Format.
<ide><path>rc/java/net/sf/jabref/export/layout/format/RTFChars.java <ide> <ide> public class RTFChars implements LayoutFormatter { <ide> <add> public String format(String field) { <ide> <del> public String format(String field) { <del> <del> int i; <del> field = firstFormat(field); <del> StringBuffer sb = new StringBuffer(""); <del> StringBuffer currentCommand = null; <del> char c; <del> boolean escaped = false, incommand = false; <del> for (i=0; i<field.length(); i++) { <del> c = field.charAt(i); <del> if (escaped && (c == '\\')) { <del> sb.append('\\'); <del> escaped = false; <del> } <add> int i; <add> field = firstFormat(field); <add> StringBuffer sb = new StringBuffer(""); <add> StringBuffer currentCommand = null; <add> char c; <add> boolean escaped = false, incommand = false; <add> for (i = 0; i < field.length(); i++) { <add> c = field.charAt(i); <add> if (escaped && (c == '\\')) { <add> sb.append('\\'); <add> escaped = false; <add> } <ide> <del> else if (c == '\\') { <del> escaped = true; <del> incommand = true; <del> currentCommand = new StringBuffer(); <del> } <del> else if (!incommand && (c=='{' || c=='}')) { <del> // Swallow the brace. <del> } <del> else if (Character.isLetter((char)c) || <del> (Globals.SPECIAL_COMMAND_CHARS.indexOf(""+(char)c) >= 0)) { <del> escaped = false; <del> if (!incommand) <del> sb.append((char)c); <del> // Else we are in a command, and should not keep the letter. <del> else { <del> currentCommand.append( (char) c); <add> else if (c == '\\') { <add> escaped = true; <add> incommand = true; <add> currentCommand = new StringBuffer(); <add> } else if (!incommand && (c == '{' || c == '}')) { <add> // Swallow the brace. <add> } else if (Character.isLetter((char) c) <add> || (Globals.SPECIAL_COMMAND_CHARS.indexOf("" + (char) c) >= 0)) { <add> escaped = false; <add> if (!incommand) <add> sb.append((char) c); <add> // Else we are in a command, and should not keep the letter. <add> else { <add> currentCommand.append((char) c); <ide> <del> testCharCom: if ((currentCommand.length() == 1) <del> && (Globals.SPECIAL_COMMAND_CHARS.indexOf(currentCommand.toString()) >= 0)) { <del> // This indicates that we are in a command of the type \^o or \~{n} <del> if (i >= field.length()-1) <del> break testCharCom; <add> testCharCom: if ((currentCommand.length() == 1) <add> && (Globals.SPECIAL_COMMAND_CHARS.indexOf(currentCommand.toString()) >= 0)) { <add> // This indicates that we are in a command of the type <add> // \^o or \~{n} <add> if (i >= field.length() - 1) <add> break testCharCom; <ide> <del> String command = currentCommand.toString(); <del> i++; <del> c = field.charAt(i); <del> //System.out.println("next: "+(char)c); <del> String combody; <del> if (c == '{') { <del> IntAndString part = getPart(field, i); <del> i += part.i; <del> combody = part.s; <del> } <del> else { <del> combody = field.substring(i,i+1); <del> //System.out.println("... "+combody); <del> } <del> //System.out.println(command+combody); <del> Object result = Globals.RTFCHARS.get(command+combody); <del> <del> if (result != null) <del> sb.append((String)result); <add> String command = currentCommand.toString(); <add> i++; <add> c = field.charAt(i); <add> // System.out.println("next: "+(char)c); <add> String combody; <add> if (c == '{') { <add> IntAndString part = getPart(field, i); <add> i += part.i; <add> combody = part.s; <add> } else { <add> combody = field.substring(i, i + 1); <add> // System.out.println("... "+combody); <add> } <add> // System.out.println(command+combody); <add> Object result = Globals.RTFCHARS.get(command + combody); <ide> <del> incommand = false; <del> escaped = false; <add> if (result != null) <add> sb.append((String) result); <ide> <del> } <add> incommand = false; <add> escaped = false; <ide> <del> } <add> } <ide> <del> } <del> else { <del> //if (!incommand || ((c!='{') && !Character.isWhitespace(c))) <del> testContent: if (!incommand || (!Character.isWhitespace(c) && (c != '{'))) <del> sb.append((char)c); <del> else { <del> // First test if we are already at the end of the string. <del> if (i >= field.length()-1) <del> break testContent; <add> } <ide> <del> if (c == '{') { <add> } else { <add> // if (!incommand || ((c!='{') && !Character.isWhitespace(c))) <add> testContent: if (!incommand || (!Character.isWhitespace(c) && (c != '{'))) <add> sb.append((char) c); <add> else { <add> // First test if we are already at the end of the string. <add> if (i >= field.length() - 1) <add> break testContent; <ide> <del> String command = currentCommand.toString(); <del> // Then test if we are dealing with a italics or bold command. If so, handle. <del> if (command.equals("emph") || command.equals("textit")) { <del> IntAndString part = getPart(field, i); <del> i += part.i; <del> sb.append("}{\\i ").append(part.s).append("}{"); <del> } <del> else if (command.equals("textbf")) { <del> IntAndString part = getPart(field, i); <del> i += part.i; <del> sb.append("}{\\b ").append(part.s).append("}{"); <del> } <del> } else <del> sb.append((char)c); <add> if (c == '{') { <ide> <del> } <del> incommand = false; <del> escaped = false; <del> } <del> } <add> String command = currentCommand.toString(); <add> // Then test if we are dealing with a italics or bold <add> // command. If so, handle. <add> if (command.equals("emph") || command.equals("textit")) { <add> IntAndString part = getPart(field, i); <add> i += part.i; <add> sb.append("}{\\i ").append(part.s).append("}{"); <add> } else if (command.equals("textbf")) { <add> IntAndString part = getPart(field, i); <add> i += part.i; <add> sb.append("}{\\b ").append(part.s).append("}{"); <add> } <add> } else <add> sb.append((char) c); <ide> <del> return sb.toString(); <del> //field.replaceAll("\\\\emph", "").replaceAll("\\\\em", "").replaceAll("\\\\textbf", ""); <del> } <add> } <add> incommand = false; <add> escaped = false; <add> } <add> } <ide> <del> private String firstFormat(String s) { <del> return s;//s.replaceAll("&|\\\\&","&amp;");//.replaceAll("--", "&mdash;"); <del> } <add> return sb.toString(); <add> // field.replaceAll("\\\\emph", "").replaceAll("\\\\em", <add> // "").replaceAll("\\\\textbf", ""); <add> } <ide> <del> private IntAndString getPart(String text, int i) { <del> char c; <del> int count = 0;//, i=index; <del> StringBuffer part = new StringBuffer(); <del> while ((count >= 0) && (i < text.length())) { <del> i++; <del> c = text.charAt(i); <del> if (c == '}') <del> count--; <del> else if (c == '{') <del> count++; <add> private String firstFormat(String s) { <add> return s;// s.replaceAll("&|\\\\&","&amp;");//.replaceAll("--", <add> // "&mdash;"); <add> } <ide> <del> part.append((char)c); <del> } <del> //System.out.println("part: "+part.toString()+"\nformatted: "+format(part.toString())); <del> return new IntAndString(part.length(), format(part.toString())); <del> } <add> private IntAndString getPart(String text, int i) { <add> char c; <add> int count = 0;// , i=index; <add> StringBuffer part = new StringBuffer(); <add> while ((count >= 0) && (i < text.length())) { <add> i++; <add> c = text.charAt(i); <add> if (c == '}') <add> count--; <add> else if (c == '{') <add> count++; <ide> <del> private class IntAndString{ <del> public int i; <del> String s; <del> public IntAndString(int i, String s) { <del> this.i = i; <del> this.s = s; <del> } <del> } <add> part.append((char) c); <add> } <add> // System.out.println("part: "+part.toString()+"\nformatted: <add> // "+format(part.toString())); <add> return new IntAndString(part.length(), format(part.toString())); <add> } <add> <add> private class IntAndString { <add> public int i; <add> <add> String s; <add> <add> public IntAndString(int i, String s) { <add> this.i = i; <add> this.s = s; <add> } <add> } <ide> }
Java
bsd-3-clause
e00099985f379d5d3bf3003f86883f3ce0f76dbd
0
Caleydo/org.caleydo.view.contour
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *******************************************************************************/ package org.caleydo.view.relationshipexplorer.ui.dialog; import java.util.HashSet; import java.util.Set; import org.caleydo.core.data.collection.column.container.CategoricalClassDescription; import org.caleydo.core.data.collection.column.container.CategoryProperty; import org.caleydo.core.data.collection.table.NumericalTable; import org.caleydo.core.data.collection.table.Table; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.gui.util.AHelpButtonDialog; import org.caleydo.core.io.DataDescription; import org.caleydo.core.io.NumericalProperties; import org.caleydo.view.relationshipexplorer.ui.column.TabularDataCollection; import org.caleydo.view.relationshipexplorer.ui.column.TabularDataColumn; import org.caleydo.view.relationshipexplorer.ui.util.CompositePredicate; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import com.google.common.base.Predicate; /** * @author Christian * */ public class TabularAttributesFilterDialog extends AHelpButtonDialog { protected final TabularDataColumn column; protected final TabularDataCollection collection; protected Set<IAttributeFilterFactory> filterFactories = new HashSet<>(); protected CompositePredicate<Object> filter; protected interface IAttributeFilterFactory { public Predicate<Object> createFilter(); public boolean use(); } protected class NumericalAttributeFilterFactory implements IAttributeFilterFactory { protected final int dimensionID; protected final Text upperLimitText; protected final Text lowerLimitText; protected boolean use = false; public NumericalAttributeFilterFactory(int dimensionID, Text upperLimitText, Text lowerLimitText) { this.dimensionID = dimensionID; this.upperLimitText = upperLimitText; this.lowerLimitText = lowerLimitText; } @Override public Predicate<Object> createFilter() { final float upperLimit = Float.parseFloat(upperLimitText.getText()); final float lowerLimit = Float.parseFloat(lowerLimitText.getText()); return new Predicate<Object>() { @Override public boolean apply(Object elementID) { float value = (float) collection.getDataDomain().getRaw(collection.getItemIDType(), (int) elementID, collection.getDimensionPerspective().getIdType(), dimensionID); return value >= lowerLimit && value <= upperLimit; } }; } @Override public boolean use() { return use; } } protected class CategoricalAttributeFilterFactory implements IAttributeFilterFactory { protected final int dimensionID; protected final org.eclipse.swt.widgets.Table table; protected boolean use = false; public CategoricalAttributeFilterFactory(int dimensionID, org.eclipse.swt.widgets.Table table) { this.dimensionID = dimensionID; this.table = table; } @Override public Predicate<Object> createFilter() { final Set<String> validCategories = new HashSet<>(table.getSelection().length); for (TableItem item : table.getItems()) { if (item.getChecked()) { validCategories.add(item.getText()); } } return new Predicate<Object>() { @Override public boolean apply(Object elementID) { String value = (String) collection.getDataDomain().getRaw(collection.getItemIDType(), (int) elementID, collection.getDimensionPerspective().getIdType(), dimensionID); return validCategories.contains(value); } }; } @Override public boolean use() { return use; } } /** * @param parentShell */ public TabularAttributesFilterDialog(Shell parentShell, TabularDataColumn column) { super(parentShell); this.column = column; this.collection = (TabularDataCollection) column.getCollection(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Attribute Filter for " + collection.getLabel()); } @Override protected Control createDialogArea(Composite parent) { ATableBasedDataDomain dataDomain = collection.getDataDomain(); Table table = dataDomain.getTable(); ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.H_SCROLL); scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); scrolledComposite.setExpandVertical(true); scrolledComposite.setExpandHorizontal(true); Composite parentComposite = new Composite(scrolledComposite, SWT.NONE); parentComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); parentComposite.setLayout(new GridLayout(collection.getDimensionPerspective().getVirtualArray().size(), true)); scrolledComposite.setContent(parentComposite); scrolledComposite.setMinSize(collection.getDimensionPerspective().getVirtualArray().size() * 200, 100); if (table.isDataHomogeneous()) { DataDescription desc = dataDomain.getDataSetDescription().getDataDescription(); CategoricalClassDescription<?> categoricalClassDesc = desc.getCategoricalClassDescription(); for (int dimensionID : collection.getDimensionPerspective().getVirtualArray()) { String label = dataDomain.getDimensionLabel(dimensionID); if (categoricalClassDesc == null) { NumericalTable numericalTable = (NumericalTable) table; // float dataCenter = numericalTable.getDataCenter().floatValue(); float min = (float) numericalTable.getMin(); float max = (float) numericalTable.getMax(); addNumericalAttributeGroup(parentComposite, dimensionID, label, min, max); } else { addCategoricalAttributeGroup(parentComposite, dimensionID, label, categoricalClassDesc); } } } else { for (int dimensionID : collection.getDimensionPerspective().getVirtualArray()) { Object dataClassDesc = table.getDataClassSpecificDescription(dimensionID); String label = dataDomain.getDimensionLabel(dimensionID); if (dataClassDesc == null || dataClassDesc instanceof NumericalProperties) { float min = Float.POSITIVE_INFINITY; float max = Float.NEGATIVE_INFINITY; for (Object elementID : collection.getAllElementIDs()) { float value = (float) collection.getDataDomain().getRaw(collection.getItemIDType(), (int) elementID, collection.getDimensionPerspective().getIdType(), dimensionID); if (value < min) { min = value; } if (value > max) { max = value; } } addNumericalAttributeGroup(parentComposite, dimensionID, label, min, max); } else { addCategoricalAttributeGroup(parentComposite, dimensionID, label, (CategoricalClassDescription<?>) dataClassDesc); } } } return super.createDialogArea(parent); } protected void addNumericalAttributeGroup(Composite parent, int dimensionID, String label, float min, float max) { Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = 200; group.setLayoutData(gd); group.setText(label); group.setLayout(new GridLayout(2, false)); final Label maxLabel = new Label(group, SWT.NONE); maxLabel.setText("Upper Limit"); maxLabel.setEnabled(false); final Text maxText = new Text(group, SWT.BORDER); maxText.setText(Float.toString(max)); maxText.setEnabled(false); maxText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); final Label minLabel = new Label(group, SWT.NONE); minLabel.setText("Lower Limit"); minLabel.setEnabled(false); final Text minText = new Text(group, SWT.BORDER); minText.setText(Float.toString(min)); minText.setEnabled(false); minText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); final Button useAttributeButton = new Button(group, SWT.CHECK); useAttributeButton.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true, 2, 1)); useAttributeButton.setText("Enabled"); final NumericalAttributeFilterFactory factory = new NumericalAttributeFilterFactory(dimensionID, maxText, minText); filterFactories.add(factory); useAttributeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean enabled = useAttributeButton.getSelection(); maxLabel.setEnabled(enabled); maxText.setEnabled(enabled); minLabel.setEnabled(enabled); minText.setEnabled(enabled); factory.use = enabled; } }); } protected void addCategoricalAttributeGroup(Composite parent, int dimensionID, String label, CategoricalClassDescription<?> categoricalClassDesc) { Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = 200; group.setLayoutData(gd); group.setText(label); group.setLayout(new GridLayout()); final org.eclipse.swt.widgets.Table table = new org.eclipse.swt.widgets.Table(group, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); for (CategoryProperty<?> cp : categoricalClassDesc.getCategoryProperties()) { TableItem item = new TableItem(table, SWT.NONE); item.setText(cp.getCategoryName()); item.setChecked(true); } table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); table.setEnabled(false); final CategoricalAttributeFilterFactory factory = new CategoricalAttributeFilterFactory(dimensionID, table); filterFactories.add(factory); final Button useAttributeButton = new Button(group, SWT.CHECK); useAttributeButton.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true)); useAttributeButton.setText("Enabled"); useAttributeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean enabled = useAttributeButton.getSelection(); table.setEnabled(enabled); factory.use = enabled; } }); } @Override protected void helpPressed() { // TODO Auto-generated method stub } @Override protected void okPressed() { filter = new CompositePredicate<>(); for(IAttributeFilterFactory f : filterFactories) { if (f.use()) { filter.add(f.createFilter()); } } super.okPressed(); } public Predicate<Object> getFilter() { return filter; } }
src/main/java/org/caleydo/view/relationshipexplorer/ui/dialog/TabularAttributesFilterDialog.java
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *******************************************************************************/ package org.caleydo.view.relationshipexplorer.ui.dialog; import java.util.HashSet; import java.util.Set; import org.caleydo.core.data.collection.column.container.CategoricalClassDescription; import org.caleydo.core.data.collection.column.container.CategoryProperty; import org.caleydo.core.data.collection.table.NumericalTable; import org.caleydo.core.data.collection.table.Table; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.gui.util.AHelpButtonDialog; import org.caleydo.core.io.DataDescription; import org.caleydo.core.io.NumericalProperties; import org.caleydo.view.relationshipexplorer.ui.column.TabularDataCollection; import org.caleydo.view.relationshipexplorer.ui.column.TabularDataColumn; import org.caleydo.view.relationshipexplorer.ui.util.CompositePredicate; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import com.google.common.base.Predicate; /** * @author Christian * */ public class TabularAttributesFilterDialog extends AHelpButtonDialog { protected final TabularDataColumn column; protected final TabularDataCollection collection; protected Set<IAttributeFilterFactory> filterFactories = new HashSet<>(); protected CompositePredicate<Object> filter; protected interface IAttributeFilterFactory { public Predicate<Object> createFilter(); public boolean use(); } protected class NumericalAttributeFilterFactory implements IAttributeFilterFactory { protected final int dimensionID; protected final Text upperLimitText; protected final Text lowerLimitText; protected boolean use = false; public NumericalAttributeFilterFactory(int dimensionID, Text upperLimitText, Text lowerLimitText) { this.dimensionID = dimensionID; this.upperLimitText = upperLimitText; this.lowerLimitText = lowerLimitText; } @Override public Predicate<Object> createFilter() { final float upperLimit = Float.parseFloat(upperLimitText.getText()); final float lowerLimit = Float.parseFloat(lowerLimitText.getText()); return new Predicate<Object>() { @Override public boolean apply(Object elementID) { float value = (float) collection.getDataDomain().getRaw(collection.getItemIDType(), (int) elementID, collection.getDimensionPerspective().getIdType(), dimensionID); return value >= lowerLimit && value <= upperLimit; } }; } @Override public boolean use() { return use; } } protected class CategoricalAttributeFilterFactory implements IAttributeFilterFactory { protected final int dimensionID; protected final org.eclipse.swt.widgets.Table table; protected boolean use = false; public CategoricalAttributeFilterFactory(int dimensionID, org.eclipse.swt.widgets.Table table) { this.dimensionID = dimensionID; this.table = table; } @Override public Predicate<Object> createFilter() { final Set<String> validCategories = new HashSet<>(table.getSelection().length); for (TableItem item : table.getItems()) { if (item.getChecked()) { validCategories.add(item.getText()); } } return new Predicate<Object>() { @Override public boolean apply(Object elementID) { String value = (String) collection.getDataDomain().getRaw(collection.getItemIDType(), (int) elementID, collection.getDimensionPerspective().getIdType(), dimensionID); return validCategories.contains(value); } }; } @Override public boolean use() { return use; } } /** * @param parentShell */ public TabularAttributesFilterDialog(Shell parentShell, TabularDataColumn column) { super(parentShell); this.column = column; this.collection = (TabularDataCollection) column.getCollection(); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Attribute Filter for " + collection.getLabel()); } @Override protected Control createDialogArea(Composite parent) { ATableBasedDataDomain dataDomain = collection.getDataDomain(); Table table = dataDomain.getTable(); ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.H_SCROLL); scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); scrolledComposite.setExpandVertical(true); scrolledComposite.setExpandHorizontal(true); Composite parentComposite = new Composite(scrolledComposite, SWT.NONE); parentComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); parentComposite.setLayout(new GridLayout(collection.getDimensionPerspective().getVirtualArray().size(), true)); scrolledComposite.setContent(parentComposite); scrolledComposite.setMinSize(collection.getDimensionPerspective().getVirtualArray().size() * 200, 100); if (table.isDataHomogeneous()) { DataDescription desc = dataDomain.getDataSetDescription().getDataDescription(); CategoricalClassDescription<?> categoricalClassDesc = desc.getCategoricalClassDescription(); for (int dimensionID : collection.getDimensionPerspective().getVirtualArray()) { String label = dataDomain.getDimensionLabel(dimensionID); if (categoricalClassDesc == null) { NumericalTable numericalTable = (NumericalTable) table; // float dataCenter = numericalTable.getDataCenter().floatValue(); float min = (float) numericalTable.getMin(); float max = (float) numericalTable.getMax(); addNumericalAttributeGroup(parentComposite, dimensionID, label, min, max); } else { addCategoricalAttributeGroup(parentComposite, dimensionID, label, categoricalClassDesc); } } } else { for (int dimensionID : collection.getDimensionPerspective().getVirtualArray()) { Object dataClassDesc = table.getDataClassSpecificDescription(dimensionID); String label = dataDomain.getDimensionLabel(dimensionID); if (dataClassDesc == null || dataClassDesc instanceof NumericalProperties) { // TODO: use correct data center addNumericalAttributeGroup(parentComposite, dimensionID, label, 0, 0); } else { addCategoricalAttributeGroup(parentComposite, dimensionID, label, (CategoricalClassDescription<?>) dataClassDesc); } } } return super.createDialogArea(parent); } protected void addNumericalAttributeGroup(Composite parent, int dimensionID, String label, float min, float max) { Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = 200; group.setLayoutData(gd); group.setText(label); group.setLayout(new GridLayout(2, false)); final Label maxLabel = new Label(group, SWT.NONE); maxLabel.setText("Upper Limit"); maxLabel.setEnabled(false); final Text maxText = new Text(group, SWT.BORDER); maxText.setText(Float.toString(max)); maxText.setEnabled(false); maxText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); final Label minLabel = new Label(group, SWT.NONE); minLabel.setText("Lower Limit"); minLabel.setEnabled(false); final Text minText = new Text(group, SWT.BORDER); minText.setText(Float.toString(min)); minText.setEnabled(false); minText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); final Button useAttributeButton = new Button(group, SWT.CHECK); useAttributeButton.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true, 2, 1)); useAttributeButton.setText("Enabled"); final NumericalAttributeFilterFactory factory = new NumericalAttributeFilterFactory(dimensionID, maxText, minText); filterFactories.add(factory); useAttributeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean enabled = useAttributeButton.getSelection(); maxLabel.setEnabled(enabled); maxText.setEnabled(enabled); minLabel.setEnabled(enabled); minText.setEnabled(enabled); factory.use = enabled; } }); } protected void addCategoricalAttributeGroup(Composite parent, int dimensionID, String label, CategoricalClassDescription<?> categoricalClassDesc) { Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = 200; group.setLayoutData(gd); group.setText(label); group.setLayout(new GridLayout()); final org.eclipse.swt.widgets.Table table = new org.eclipse.swt.widgets.Table(group, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); for (CategoryProperty<?> cp : categoricalClassDesc.getCategoryProperties()) { TableItem item = new TableItem(table, SWT.NONE); item.setText(cp.getCategoryName()); item.setChecked(true); } table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); table.setEnabled(false); final CategoricalAttributeFilterFactory factory = new CategoricalAttributeFilterFactory(dimensionID, table); filterFactories.add(factory); final Button useAttributeButton = new Button(group, SWT.CHECK); useAttributeButton.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true)); useAttributeButton.setText("Enabled"); useAttributeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { boolean enabled = useAttributeButton.getSelection(); table.setEnabled(enabled); factory.use = enabled; } }); } @Override protected void helpPressed() { // TODO Auto-generated method stub } @Override protected void okPressed() { filter = new CompositePredicate<>(); for(IAttributeFilterFactory f : filterFactories) { if (f.use()) { filter.add(f.createFilter()); } } super.okPressed(); } public Predicate<Object> getFilter() { return filter; } }
added correct min and max values for inhomogeneous dataset attribute filters
src/main/java/org/caleydo/view/relationshipexplorer/ui/dialog/TabularAttributesFilterDialog.java
added correct min and max values for inhomogeneous dataset attribute filters
<ide><path>rc/main/java/org/caleydo/view/relationshipexplorer/ui/dialog/TabularAttributesFilterDialog.java <ide> Object dataClassDesc = table.getDataClassSpecificDescription(dimensionID); <ide> String label = dataDomain.getDimensionLabel(dimensionID); <ide> if (dataClassDesc == null || dataClassDesc instanceof NumericalProperties) { <del> // TODO: use correct data center <del> addNumericalAttributeGroup(parentComposite, dimensionID, label, 0, 0); <add> <add> float min = Float.POSITIVE_INFINITY; <add> float max = Float.NEGATIVE_INFINITY; <add> <add> for (Object elementID : collection.getAllElementIDs()) { <add> float value = (float) collection.getDataDomain().getRaw(collection.getItemIDType(), <add> (int) elementID, collection.getDimensionPerspective().getIdType(), dimensionID); <add> if (value < min) { <add> min = value; <add> } <add> if (value > max) { <add> max = value; <add> } <add> <add> } <add> <add> addNumericalAttributeGroup(parentComposite, dimensionID, label, min, max); <ide> } else { <ide> <ide> addCategoricalAttributeGroup(parentComposite, dimensionID, label,
Java
mit
3a950c5a027fe1d836cc35e73729889de813e1f6
0
sideshowcecil/myx-monitor,sideshowcecil/myx-monitor
package at.ac.tuwien.dsg.myx.monitor.model; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import edu.uci.isr.xarch.IXArch; import edu.uci.isr.xarch.IXArchImplementation; import edu.uci.isr.xarch.XArchParseException; import edu.uci.isr.xarch.XArchSerializeException; import edu.uci.isr.xarch.XArchUtils; public class ModelRootImpl implements ModelRoot { protected IXArchImplementation xArchImpl; protected IXArch xArchRoot; public ModelRootImpl() { xArchImpl = XArchUtils.getDefaultXArchImplementation(); } public ModelRootImpl(String xadlFile) { this(); parse(xadlFile); } @Override public void parse(String xadlFile) { try { FileReader documentSource = new FileReader(new File(xadlFile)); xArchRoot = xArchImpl.parse(documentSource); } catch (XArchParseException | FileNotFoundException e) { throw new IllegalArgumentException("There was an error while parsing the given xadl file", e); } } @Override public void save(String xadlFile) { FileWriter fr = null; try { fr = new FileWriter(new File(xadlFile)); fr.write(xArchImpl.serialize(xArchRoot, null)); fr.close(); } catch (IOException | XArchSerializeException e) { throw new IllegalArgumentException("There was an error while saving the architecture", e); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { } } } } @Override public IXArch getArchitectureRoot() { return xArchRoot; } }
myx-monitor/src/main/java/at/ac/tuwien/dsg/myx/monitor/model/ModelRootImpl.java
package at.ac.tuwien.dsg.myx.monitor.model; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import edu.uci.isr.xarch.IXArch; import edu.uci.isr.xarch.IXArchImplementation; import edu.uci.isr.xarch.XArchParseException; import edu.uci.isr.xarch.XArchSerializeException; import edu.uci.isr.xarch.XArchUtils; public class ModelRootImpl implements ModelRoot { protected IXArchImplementation xArchImpl; protected IXArch xArchRoot; public ModelRootImpl() { xArchImpl = XArchUtils.getDefaultXArchImplementation(); } public ModelRootImpl(String xadlFile) { super(); parse(xadlFile); } @Override public void parse(String xadlFile) { try { FileReader documentSource = new FileReader(new File(xadlFile)); xArchRoot = xArchImpl.parse(documentSource); } catch (XArchParseException | FileNotFoundException e) { throw new IllegalArgumentException("There was an error while parsing the given xadl file", e); } } @Override public void save(String xadlFile) { FileWriter fr = null; try { fr = new FileWriter(new File(xadlFile)); fr.write(xArchImpl.serialize(xArchRoot, null)); fr.close(); } catch (IOException | XArchSerializeException e) { throw new IllegalArgumentException("There was an error while saving the architecture", e); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { } } } } @Override public IXArch getArchitectureRoot() { return xArchRoot; } }
small bugfix in constructor: super() -> this()
myx-monitor/src/main/java/at/ac/tuwien/dsg/myx/monitor/model/ModelRootImpl.java
small bugfix in constructor: super() -> this()
<ide><path>yx-monitor/src/main/java/at/ac/tuwien/dsg/myx/monitor/model/ModelRootImpl.java <ide> } <ide> <ide> public ModelRootImpl(String xadlFile) { <del> super(); <add> this(); <ide> parse(xadlFile); <ide> } <ide>
Java
bsd-3-clause
1e2b1a7ed99073a1b092c65ec46fe64192d35bd8
0
lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon
// ======================================================================== // $Id: DaemonStatus.java,v 1.12 2003-04-03 11:34:53 tal Exp $ // ======================================================================== /* Copyright (c) 2000-2002 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.servlet; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; import java.util.*; import java.net.*; import java.text.*; // import com.mortbay.servlet.*; // import org.mortbay.util.*; import org.mortbay.html.*; import org.mortbay.tools.*; import org.lockss.util.*; import org.lockss.daemon.*; import org.lockss.daemon.status.*; /** DaemonStatus servlet */ public class DaemonStatus extends LockssServlet { private static final String cellContrastColor = "#DDDDDD"; private static final String bAddRem = "Add/Remove Cluster Clients"; private static final String bDelete = "Delete"; private static final String bAdd = "Add"; // public static final DateFormat df = // DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); public static final DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); private String tableName; private String key; private boolean isForm = false; private boolean html = false; private String errorMsg = null; private StatusService statSvc; public void init(ServletConfig config) throws ServletException { super.init(config); statSvc = getLockssDaemon().getStatusService(); } public void lockssHandle() throws IOException { PrintWriter wrtr = resp.getWriter(); Page page = null; Date now = new Date(); html = req.getParameter("text") == null; resp.setContentType(html ? "text/html" : "text/plain"); tableName = req.getParameter("table"); key = req.getParameter("key"); if (StringUtil.isNullString(tableName)) { tableName = StatusService.ALL_TABLES_TABLE; } if (StringUtil.isNullString(key)) { key = null; } if (html) { page = newPage(); page.add("<center>" + getMachineName() + " at " + df.format(now) + "</center>"); page.add("<br>"); // page.add("<center>"); // page.add(srvLink(SERVLET_DAEMON_STATUS, ".", // concatParams("text=1", req.getQueryString()))); // page.add("</center><br><br>"); } else { wrtr.println("host=" + getLcapIPAddr() + ",time=" + now.getTime() + ",version=" + "0.0"); } doStatusTable(page, wrtr, tableName, key); if (html) { page.add(getFooter()); page.write(wrtr); } } // Build the table private void doStatusTable(Page page, PrintWriter wrtr, String tableName, String tableKey) throws IOException { StatusTable statTable; try { statTable = statSvc.getTable(tableName, tableKey); } catch (StatusService.NoSuchTableException e) { if (html) { page.add("Can't get table: "); page.add(e.toString()); } else { wrtr.println("Error getting table: " + e.toString()); } return; } java.util.List colList = statTable.getColumnDescriptors(); java.util.List rowList = statTable.getSortedRows(); String title0 = statTable.getTitle(); String titleFoot = statTable.getTitleFootnote(); Table table = null; ColumnDescriptor cds[] = (ColumnDescriptor [])colList.toArray(new ColumnDescriptor[0]); int cols = cds.length; Iterator rowIter = rowList.iterator(); if (true || rowIter.hasNext()) { // if table not empty, output column headings // table = new Table(0, "CELLSPACING=2 CELLPADDING=0 WIDTH=\"100%\""); table = new Table(0, "ALIGN=CENTER CELLSPACING=2 CELLPADDING=0"); if (html) { // ensure title footnote numbered before ColDesc.HEADs String title = title0 + addFootnote(titleFoot); table.newRow(); table.addHeading(title, "ALIGN=CENTER COLSPAN=" + (cols * 2 - 1)); table.newRow(); java.util.List summary = statTable.getSummaryInfo(); if (summary != null && !summary.isEmpty()) { for (Iterator iter = summary.iterator(); iter.hasNext(); ) { StatusTable.SummaryInfo sInfo = (StatusTable.SummaryInfo)iter.next(); table.newRow(); StringBuffer sb = new StringBuffer(); sb.append("<b>"); sb.append(sInfo.getTitle()); sb.append("</b>: "); sb.append(dispString(sInfo.getValue(), sInfo.getType())); table.newCell("COLSPAN=" + (cols * 2 - 1)); table.add(sb.toString()); } table.newRow(); } for (int ix = 0; ix < cols; ix++) { ColumnDescriptor cd = cds[ix]; String head = cd.getTitle() + addFootnote(cd.getFootNote()); table.addHeading(head, "align=" + ((cols != 1) ? getColAlignment(cd) : "center" )); if (ix < (cols - 1)) { table.newCell("width = 8"); } } } else { wrtr.println(); wrtr.println("table=" + title0); if (tableKey != null) { wrtr.println("key=" + tableKey); } } } while (rowIter.hasNext()) { Map rowMap = (Map)rowIter.next(); if (html) { table.newRow(); for (int ix = 0; ix < cols; ix++) { ColumnDescriptor cd = cds[ix]; Object val = rowMap.get(cd.getColumnName()); String disp; table.newCell("align=" + getColAlignment(cd)); table.add(dispString(rowMap.get(cd.getColumnName()), cd.getType())); if (ix < (cols - 1)) { table.newCell(); // empty column for spacing } } } else { Iterator iter = rowMap.keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); wrtr.print(key + "=" + rowMap.get(key).toString()); if (iter.hasNext()) { wrtr.print(","); } else { wrtr.println(); } } } } if (html && table != null) { page.add(table); page.add("<br>"); String heading = getHeading(); page.title("LOCKSS: " + title0 + " - " + heading); } } private String getColAlignment(ColumnDescriptor cd) { switch (cd.getType()) { case ColumnDescriptor.TYPE_STRING: case ColumnDescriptor.TYPE_FLOAT: // tk - should align decimal points? case ColumnDescriptor.TYPE_DATE: case ColumnDescriptor.TYPE_IP_ADDRESS: case ColumnDescriptor.TYPE_TIME_INTERVAL: default: return "LEFT"; case ColumnDescriptor.TYPE_INT: case ColumnDescriptor.TYPE_PERCENT: return "RIGHT"; } } private String dispString(Object val, int type) { if (val instanceof StatusTable.Reference) { StatusTable.Reference ref = (StatusTable.Reference)val; StringBuffer sb = new StringBuffer(); sb.append("table="); sb.append(ref.getTableName()); String key = ref.getKey(); if (!StringUtil.isNullString(key)) { sb.append("&key="); sb.append(urlEncode(key)); } return srvLink(myServletDescr(), dispString1(ref.getValue(), type), sb.toString()); } else { return dispString1(val, type); } } private String dispString1(Object val, int type) { if (val instanceof StatusTable.DisplayedValue) { StatusTable.DisplayedValue aval = (StatusTable.DisplayedValue)val; String str = dispString2(aval.getValue(), type); String color = aval.getColor(); if (color != null) { str = "<font color=" + color + ">" + str + "</font>"; } return str; } else { return dispString2(val, type); } } private String dispString2(Object val, int type) { if (val == null) { return ""; } try { switch (type) { case ColumnDescriptor.TYPE_STRING: case ColumnDescriptor.TYPE_FLOAT: case ColumnDescriptor.TYPE_INT: default: return val.toString(); case ColumnDescriptor.TYPE_PERCENT: float fv = ((Number)val).floatValue(); return Integer.toString(Math.round(fv * 100)) + "%"; case ColumnDescriptor.TYPE_DATE: Date d; if (val instanceof Number) { d = new Date(((Number)val).longValue()); } else if (val instanceof Date) { d = (Date)val; } else { return val.toString(); } if (d.getTime() == 0) { return "never"; } else { return df.format(d); } case ColumnDescriptor.TYPE_IP_ADDRESS: return ((InetAddress)val).getHostAddress(); case ColumnDescriptor.TYPE_TIME_INTERVAL: long millis = ((Number)val).longValue(); return StringUtil.timeIntervalToString(millis); } } catch (NumberFormatException e) { log.warning("Bad number: " + val.toString() + ": " + e.toString()); return val.toString(); } catch (ClassCastException e) { log.warning("Wrong type value: " + val.toString() + ": " + e.toString()); return val.toString(); } catch (Exception e) { log.warning("Error formatting value: " + val.toString() + ": " + e.toString()); return val.toString(); } } // don't make me a link in nav table if I'm displaying table of all tables protected boolean includeMeInNav() { return !StatusService.ALL_TABLES_TABLE.equals(tableName); } }
src/org/lockss/servlet/DaemonStatus.java
// ======================================================================== // $Id: DaemonStatus.java,v 1.11 2003-04-02 10:52:03 tal Exp $ // ======================================================================== /* Copyright (c) 2000-2002 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.servlet; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; import java.util.*; import java.net.*; import java.text.*; // import com.mortbay.servlet.*; // import org.mortbay.util.*; import org.mortbay.html.*; import org.mortbay.tools.*; import org.lockss.util.*; import org.lockss.daemon.*; import org.lockss.daemon.status.*; /** DaemonStatus servlet */ public class DaemonStatus extends LockssServlet { private static final String cellContrastColor = "#DDDDDD"; private static final String bAddRem = "Add/Remove Cluster Clients"; private static final String bDelete = "Delete"; private static final String bAdd = "Add"; // public static final DateFormat df = // DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); public static final DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); private String tableName; private String key; private boolean isForm = false; private boolean html = false; private String errorMsg = null; private StatusService statSvc; public void init(ServletConfig config) throws ServletException { super.init(config); statSvc = getLockssDaemon().getStatusService(); } public void lockssHandle() throws IOException { PrintWriter wrtr = resp.getWriter(); Page page = null; Date now = new Date(); html = req.getParameter("text") == null; resp.setContentType(html ? "text/html" : "text/plain"); tableName = req.getParameter("table"); key = req.getParameter("key"); if (StringUtil.isNullString(tableName)) { tableName = StatusService.ALL_TABLES_TABLE; } if (StringUtil.isNullString(key)) { key = null; } if (html) { page = newPage(); page.add("<center>" + getMachineName() + " at " + df.format(now) + "</center>"); page.add("<br>"); // page.add("<center>"); // page.add(srvLink(SERVLET_DAEMON_STATUS, ".", // concatParams("text=1", req.getQueryString()))); // page.add("</center><br><br>"); } else { wrtr.println("host=" + getLcapIPAddr() + ",time=" + now.getTime() + ",version=" + "0.0"); } doStatusTable(page, wrtr, tableName, key); if (html) { page.add(getFooter()); page.write(wrtr); } } // Build the table private void doStatusTable(Page page, PrintWriter wrtr, String tableName, String tableKey) throws IOException { StatusTable statTable; try { statTable = statSvc.getTable(tableName, tableKey); } catch (StatusService.NoSuchTableException e) { if (html) { page.add("Can't get table: "); page.add(e.toString()); } else { wrtr.println("Error getting table: " + e.toString()); } return; } java.util.List colList = statTable.getColumnDescriptors(); java.util.List rowList = statTable.getSortedRows(); String title = statTable.getTitle(); String titleFoot = statTable.getTitleFootnote(); Table table = null; ColumnDescriptor cds[] = (ColumnDescriptor [])colList.toArray(new ColumnDescriptor[0]); int cols = cds.length; Iterator rowIter = rowList.iterator(); if (true || rowIter.hasNext()) { // if table not empty, output column headings // table = new Table(0, "CELLSPACING=2 CELLPADDING=0 WIDTH=\"100%\""); table = new Table(0, "ALIGN=CENTER CELLSPACING=2 CELLPADDING=0"); if (html) { // ensure title footnote numbered before ColDesc.HEADs title = title + addFootnote(titleFoot); table.newRow(); table.addHeading(title, "ALIGN=CENTER COLSPAN=" + (cols * 2 - 1)); table.newRow(); java.util.List summary = statTable.getSummaryInfo(); if (summary != null && !summary.isEmpty()) { for (Iterator iter = summary.iterator(); iter.hasNext(); ) { StatusTable.SummaryInfo sInfo = (StatusTable.SummaryInfo)iter.next(); table.newRow(); StringBuffer sb = new StringBuffer(); sb.append("<b>"); sb.append(sInfo.getTitle()); sb.append("</b>: "); sb.append(dispString(sInfo.getValue(), sInfo.getType())); table.newCell("COLSPAN=" + (cols * 2 - 1)); table.add(sb.toString()); } table.newRow(); } for (int ix = 0; ix < cols; ix++) { ColumnDescriptor cd = cds[ix]; String head = cd.getTitle() + addFootnote(cd.getFootNote()); table.addHeading(head, "align=" + ((cols != 1) ? getColAlignment(cd) : "center" )); if (ix < (cols - 1)) { table.newCell("width = 8"); } } } else { wrtr.println(); wrtr.println("table=" + title); if (tableKey != null) { wrtr.println("key=" + tableKey); } } } while (rowIter.hasNext()) { Map rowMap = (Map)rowIter.next(); if (html) { table.newRow(); for (int ix = 0; ix < cols; ix++) { ColumnDescriptor cd = cds[ix]; Object val = rowMap.get(cd.getColumnName()); String disp; table.newCell("align=" + getColAlignment(cd)); table.add(dispString(rowMap.get(cd.getColumnName()), cd.getType())); if (ix < (cols - 1)) { table.newCell(); // empty column for spacing } } } else { Iterator iter = rowMap.keySet().iterator(); while (iter.hasNext()) { String key = (String)iter.next(); wrtr.print(key + "=" + rowMap.get(key).toString()); if (iter.hasNext()) { wrtr.print(","); } else { wrtr.println(); } } } } if (html && table != null) { page.add(table); page.add("<br>"); } } private String getColAlignment(ColumnDescriptor cd) { switch (cd.getType()) { case ColumnDescriptor.TYPE_STRING: case ColumnDescriptor.TYPE_FLOAT: // tk - should align decimal points? case ColumnDescriptor.TYPE_DATE: case ColumnDescriptor.TYPE_IP_ADDRESS: case ColumnDescriptor.TYPE_TIME_INTERVAL: default: return "LEFT"; case ColumnDescriptor.TYPE_INT: case ColumnDescriptor.TYPE_PERCENT: return "RIGHT"; } } private String dispString(Object val, int type) { if (val instanceof StatusTable.Reference) { StatusTable.Reference ref = (StatusTable.Reference)val; StringBuffer sb = new StringBuffer(); sb.append("table="); sb.append(ref.getTableName()); String key = ref.getKey(); if (!StringUtil.isNullString(key)) { sb.append("&key="); sb.append(urlEncode(key)); } return srvLink(myServletDescr(), dispString1(ref.getValue(), type), sb.toString()); } else { return dispString1(val, type); } } private String dispString1(Object val, int type) { if (val instanceof StatusTable.DisplayedValue) { StatusTable.DisplayedValue aval = (StatusTable.DisplayedValue)val; String str = dispString2(aval.getValue(), type); String color = aval.getColor(); if (color != null) { str = "<font color=" + color + ">" + str + "</font>"; } return str; } else { return dispString2(val, type); } } private String dispString2(Object val, int type) { if (val == null) { return ""; } try { switch (type) { case ColumnDescriptor.TYPE_STRING: case ColumnDescriptor.TYPE_FLOAT: case ColumnDescriptor.TYPE_INT: default: return val.toString(); case ColumnDescriptor.TYPE_PERCENT: float fv = ((Number)val).floatValue(); return Integer.toString(Math.round(fv * 100)) + "%"; case ColumnDescriptor.TYPE_DATE: Date d; if (val instanceof Number) { d = new Date(((Number)val).longValue()); } else if (val instanceof Date) { d = (Date)val; } else { return val.toString(); } if (d.getTime() == 0) { return "never"; } else { return df.format(d); } case ColumnDescriptor.TYPE_IP_ADDRESS: return ((InetAddress)val).getHostAddress(); case ColumnDescriptor.TYPE_TIME_INTERVAL: long millis = ((Number)val).longValue(); return StringUtil.timeIntervalToString(millis); } } catch (NumberFormatException e) { log.warning("Bad number: " + val.toString() + ": " + e.toString()); return val.toString(); } catch (ClassCastException e) { log.warning("Wrong type value: " + val.toString() + ": " + e.toString()); return val.toString(); } catch (Exception e) { log.warning("Error formatting value: " + val.toString() + ": " + e.toString()); return val.toString(); } } // don't make me a link in nav table if I'm displaying table of all tables protected boolean includeMeInNav() { return !StatusService.ALL_TABLES_TABLE.equals(tableName); } }
Put table title in page title. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@1136 4f837ed2-42f5-46e7-a7a5-fa17313484d4
src/org/lockss/servlet/DaemonStatus.java
Put table title in page title.
<ide><path>rc/org/lockss/servlet/DaemonStatus.java <ide> // ======================================================================== <del>// $Id: DaemonStatus.java,v 1.11 2003-04-02 10:52:03 tal Exp $ <add>// $Id: DaemonStatus.java,v 1.12 2003-04-03 11:34:53 tal Exp $ <ide> // ======================================================================== <ide> <ide> /* <ide> } <ide> java.util.List colList = statTable.getColumnDescriptors(); <ide> java.util.List rowList = statTable.getSortedRows(); <del> String title = statTable.getTitle(); <add> String title0 = statTable.getTitle(); <ide> String titleFoot = statTable.getTitleFootnote(); <ide> <ide> Table table = null; <ide> table = new Table(0, "ALIGN=CENTER CELLSPACING=2 CELLPADDING=0"); <ide> if (html) { <ide> // ensure title footnote numbered before ColDesc.HEADs <del> title = title + addFootnote(titleFoot); <add> String title = title0 + addFootnote(titleFoot); <ide> <ide> table.newRow(); <ide> table.addHeading(title, "ALIGN=CENTER COLSPAN=" + <ide> } <ide> } else { <ide> wrtr.println(); <del> wrtr.println("table=" + title); <add> wrtr.println("table=" + title0); <ide> if (tableKey != null) { <ide> wrtr.println("key=" + tableKey); <ide> } <ide> if (html && table != null) { <ide> page.add(table); <ide> page.add("<br>"); <add> String heading = getHeading(); <add> page.title("LOCKSS: " + title0 + " - " + heading); <ide> } <ide> } <ide>
Java
apache-2.0
b6ebafc731252342a7d28a00632800bd85793ba4
0
SylvesterAbreu/jackrabbit,Kast0rTr0y/jackrabbit,bartosz-grabski/jackrabbit,bartosz-grabski/jackrabbit,tripodsan/jackrabbit,kigsmtua/jackrabbit,SylvesterAbreu/jackrabbit,Kast0rTr0y/jackrabbit,Kast0rTr0y/jackrabbit,tripodsan/jackrabbit,sdmcraft/jackrabbit,bartosz-grabski/jackrabbit,Overseas-Student-Living/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,tripodsan/jackrabbit,afilimonov/jackrabbit,sdmcraft/jackrabbit,afilimonov/jackrabbit,afilimonov/jackrabbit,kigsmtua/jackrabbit,SylvesterAbreu/jackrabbit,kigsmtua/jackrabbit,Overseas-Student-Living/jackrabbit
/* * 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.jackrabbit.spi.commons.query.sql2; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.UnsupportedEncodingException; import java.util.Random; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.NamespaceException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.ValueFormatException; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.QueryResult; import javax.jcr.query.qom.Column; import javax.jcr.query.qom.Constraint; import javax.jcr.query.qom.Ordering; import javax.jcr.query.qom.QueryObjectModel; import javax.jcr.query.qom.Source; import javax.jcr.version.VersionException; import junit.framework.TestCase; import org.apache.jackrabbit.commons.query.sql2.Parser; import org.apache.jackrabbit.commons.query.sql2.QOMFormatter; import org.apache.jackrabbit.spi.commons.conversion.DefaultNamePathResolver; import org.apache.jackrabbit.spi.commons.conversion.DummyNamespaceResolver; import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver; import org.apache.jackrabbit.spi.commons.query.qom.QueryObjectModelFactoryImpl; import org.apache.jackrabbit.spi.commons.query.qom.QueryObjectModelTree; import org.apache.jackrabbit.spi.commons.value.ValueFactoryQImpl; import org.apache.jackrabbit.spi.commons.value.QValueFactoryImpl; /** * This class runs function tests on the JCR-SQL2 parser. */ public class ParserTest extends TestCase { protected org.apache.jackrabbit.commons.query.sql2.Parser parser; protected Random random = new Random(); public static class QOM implements QueryObjectModel { protected QueryObjectModelTree qomTree; QOM(QueryObjectModelTree qomTree) { this.qomTree = qomTree; } public Source getSource() { return qomTree.getSource(); } public Constraint getConstraint() { return qomTree.getConstraint(); } public Ordering[] getOrderings() { return qomTree.getOrderings(); } public Column[] getColumns() { return qomTree.getColumns(); } public void bindValue(String varName, Value value) throws IllegalArgumentException, RepositoryException { // ignore } public QueryResult execute() throws InvalidQueryException, RepositoryException { return null; } public String[] getBindVariableNames() throws RepositoryException { return null; } public String getLanguage() { return null; } public String getStatement() { return null; } public String getStoredQueryPath() throws ItemNotFoundException, RepositoryException { return null; } public void setLimit(long limit) { // ignore } public void setOffset(long offset) { // ignore } public Node storeAsNode(String absPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, UnsupportedRepositoryOperationException, RepositoryException { return null; } } static class QOMF extends QueryObjectModelFactoryImpl { public QOMF(NamePathResolver resolver) { super(resolver); } protected QueryObjectModel createQuery(QueryObjectModelTree qomTree) throws InvalidQueryException, RepositoryException { return new QOM(qomTree); } } protected void setUp() throws Exception { super.setUp(); NamePathResolver resolver = new DefaultNamePathResolver(new DummyNamespaceResolver()); QueryObjectModelFactoryImpl factory = new QOMF(resolver); ValueFactory vf = new ValueFactoryQImpl(QValueFactoryImpl.getInstance(), resolver); parser = new Parser(factory, vf); } private LineNumberReader openScript(String name) { try { return new LineNumberReader(new InputStreamReader( getClass().getResourceAsStream(name), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 not supported", e); } } public void testFormatLiterals() throws Exception { formatLiteral("true", "true"); formatLiteral("false", "false"); formatLiteral("CAST('2000-01-01T12:00:00.000Z' AS DATE)", "CAST('2000-01-01T12:00:00.000Z' AS DATE)"); formatLiteral("CAST(0 AS DATE)", "CAST('1970-01-01T00:00:00.000Z' AS DATE)"); formatLiteral("1", "CAST('1' AS LONG)"); formatLiteral("-1", "CAST('-1' AS LONG)"); formatLiteral("CAST(" + Long.MAX_VALUE + " AS LONG)", "CAST('" + Long.MAX_VALUE + "' AS LONG)"); formatLiteral("CAST(" + Long.MIN_VALUE + " AS LONG)", "CAST('" + Long.MIN_VALUE + "' AS LONG)"); formatLiteral("1.0", "CAST('1.0' AS DECIMAL)"); formatLiteral("-1.0", "CAST('-1.0' AS DECIMAL)"); formatLiteral("100000000000000000000", "CAST('100000000000000000000' AS DECIMAL)"); formatLiteral("-100000000000000000000", "CAST('-100000000000000000000' AS DECIMAL)"); formatLiteral("CAST(1.0 AS DOUBLE)", "CAST('1.0' AS DOUBLE)"); formatLiteral("CAST(-1.0 AS DOUBLE)", "CAST('-1.0' AS DOUBLE)"); formatLiteral("CAST('X' AS NAME)", "CAST('X' AS NAME)"); formatLiteral("CAST('X' AS PATH)", "CAST('X' AS PATH)"); formatLiteral("CAST('X' AS REFERENCE)", "CAST('X' AS REFERENCE)"); formatLiteral("CAST('X' AS WEAKREFERENCE)", "CAST('X' AS WEAKREFERENCE)"); formatLiteral("CAST('X' AS URI)", "CAST('X' AS URI)"); formatLiteral("''", "''"); formatLiteral("' '", "' '"); formatLiteral("CAST(0 AS STRING)", "'0'"); formatLiteral("CAST(-1000000000000 AS STRING)", "'-1000000000000'"); formatLiteral("CAST(false AS STRING)", "'false'"); formatLiteral("CAST(true AS STRING)", "'true'"); } private void formatLiteral(String literal, String cast) throws Exception { String s = "SELECT TEST.* FROM TEST WHERE ID=" + literal; QueryObjectModel qom = parser.createQueryObjectModel(s); String s2 = QOMFormatter.format(qom); String cast2 = s2.substring(s2.indexOf('=') + 1).trim(); assertEquals(cast, cast2); qom = parser.createQueryObjectModel(s); s2 = QOMFormatter.format(qom); cast2 = s2.substring(s2.indexOf('=') + 1).trim(); assertEquals(cast, cast2); } public void testParseScript() throws Exception { LineNumberReader reader = openScript("test.sql2.txt"); while (true) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.length() == 0 || line.startsWith("#")) { continue; } // System.out.println(line); String query = line; try { QueryObjectModel qom = parser.createQueryObjectModel(line); String s = QOMFormatter.format(qom); qom = parser.createQueryObjectModel(s); String s2 = QOMFormatter.format(qom); assertEquals(s, s2); fuzz(line); } catch (Exception e) { line = reader.readLine(); String message = e.getMessage(); message = message.replace('\n', ' '); if (line == null || !line.startsWith("> exception")) { e.printStackTrace(); assertTrue("Unexpected exception for query " + query + ": " + e, false); } assertEquals("Expected exception message: " + message, "> exception: " + message, line); } } reader.close(); } public void fuzz(String query) throws Exception { for (int i = 0; i < 100; i++) { StringBuffer buff = new StringBuffer(query); int changes = 1 + (int) Math.abs(random.nextGaussian() * 2); for (int j = 0; j < changes; j++) { char newChar; if (random.nextBoolean()) { String s = "<>_.+\"*%&/()=?[]{}_:;,.-1234567890.qersdf"; newChar = s.charAt(random.nextInt(s.length())); } else { newChar = (char) random.nextInt(255); } int pos = random.nextInt(buff.length()); if (random.nextBoolean()) { // 50%: change one character buff.setCharAt(pos, newChar); } else { if (random.nextBoolean()) { // 25%: delete one character buff.deleteCharAt(pos); } else { // 25%: insert one character buff.insert(pos, newChar); } } } String q = buff.toString(); try { parser.createQueryObjectModel(q); } catch (ValueFormatException e) { // OK } catch (InvalidQueryException e) { // OK } catch (NamespaceException e) { // OK? } catch (Throwable t) { t.printStackTrace(); assertTrue("Unexpected exception for query " + q + ": " + t, false); } } } }
jackrabbit-spi-commons/src/test/java/org/apache/jackrabbit/spi/commons/query/sql2/ParserTest.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.jackrabbit.spi.commons.query.sql2; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.UnsupportedEncodingException; import java.util.Random; import javax.jcr.ItemExistsException; import javax.jcr.ItemNotFoundException; import javax.jcr.NamespaceException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.ValueFormatException; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.query.InvalidQueryException; import javax.jcr.query.QueryResult; import javax.jcr.query.qom.Column; import javax.jcr.query.qom.Constraint; import javax.jcr.query.qom.Ordering; import javax.jcr.query.qom.QueryObjectModel; import javax.jcr.query.qom.Source; import javax.jcr.version.VersionException; import junit.framework.TestCase; import org.apache.jackrabbit.commons.query.sql2.Parser; import org.apache.jackrabbit.commons.query.sql2.QOMFormatter; import org.apache.jackrabbit.spi.commons.conversion.DefaultNamePathResolver; import org.apache.jackrabbit.spi.commons.conversion.DummyNamespaceResolver; import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver; import org.apache.jackrabbit.spi.commons.query.qom.QueryObjectModelFactoryImpl; import org.apache.jackrabbit.spi.commons.query.qom.QueryObjectModelTree; import org.apache.jackrabbit.spi.commons.value.ValueFactoryQImpl; import org.apache.jackrabbit.spi.commons.value.QValueFactoryImpl; /** * This class runs function tests on the JCR-SQL2 parser. */ public class ParserTest extends TestCase { protected org.apache.jackrabbit.commons.query.sql2.Parser parser; protected Random random = new Random(); public static class QOM implements QueryObjectModel { protected QueryObjectModelTree qomTree; QOM(QueryObjectModelTree qomTree) { this.qomTree = qomTree; } public Source getSource() { return qomTree.getSource(); } public Constraint getConstraint() { return qomTree.getConstraint(); } public Ordering[] getOrderings() { return qomTree.getOrderings(); } public Column[] getColumns() { return qomTree.getColumns(); } public void bindValue(String varName, Value value) throws IllegalArgumentException, RepositoryException { // ignore } public QueryResult execute() throws InvalidQueryException, RepositoryException { return null; } public String[] getBindVariableNames() throws RepositoryException { return null; } public String getLanguage() { return null; } public String getStatement() { return null; } public String getStoredQueryPath() throws ItemNotFoundException, RepositoryException { return null; } public void setLimit(long limit) { // ignore } public void setOffset(long offset) { // ignore } public Node storeAsNode(String absPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, UnsupportedRepositoryOperationException, RepositoryException { return null; } } static class QOMF extends QueryObjectModelFactoryImpl { public QOMF(NamePathResolver resolver) { super(resolver); } protected QueryObjectModel createQuery(QueryObjectModelTree qomTree) throws InvalidQueryException, RepositoryException { return new QOM(qomTree); } } protected void setUp() throws Exception { super.setUp(); NamePathResolver resolver = new DefaultNamePathResolver(new DummyNamespaceResolver()); QueryObjectModelFactoryImpl factory = new QOMF(resolver); ValueFactory vf = new ValueFactoryQImpl(QValueFactoryImpl.getInstance(), resolver); parser = new Parser(factory, vf); } private LineNumberReader openScript(String name) { try { return new LineNumberReader(new InputStreamReader( getClass().getResourceAsStream(name), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 not supported", e); } } public void testParseScript() throws Exception { LineNumberReader reader = openScript("test.sql2.txt"); while (true) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.length() == 0 || line.startsWith("#")) { continue; } // System.out.println(line); String query = line; try { QueryObjectModel qom = parser.createQueryObjectModel(line); String s = QOMFormatter.format(qom); qom = parser.createQueryObjectModel(s); String s2 = QOMFormatter.format(qom); assertEquals(s, s2); fuzz(line); } catch (Exception e) { line = reader.readLine(); String message = e.getMessage(); message = message.replace('\n', ' '); if (line == null || !line.startsWith("> exception")) { e.printStackTrace(); assertTrue("Unexpected exception for query " + query + ": " + e, false); } assertEquals("Expected exception message: " + message, "> exception: " + message, line); } } reader.close(); } public void fuzz(String query) throws Exception { for (int i = 0; i < 100; i++) { StringBuffer buff = new StringBuffer(query); int changes = 1 + (int) Math.abs(random.nextGaussian() * 2); for (int j = 0; j < changes; j++) { char newChar; if (random.nextBoolean()) { String s = "<>_.+\"*%&/()=?[]{}_:;,.-1234567890.qersdf"; newChar = s.charAt(random.nextInt(s.length())); } else { newChar = (char) random.nextInt(255); } int pos = random.nextInt(buff.length()); if (random.nextBoolean()) { // 50%: change one character buff.setCharAt(pos, newChar); } else { if (random.nextBoolean()) { // 25%: delete one character buff.deleteCharAt(pos); } else { // 25%: insert one character buff.insert(pos, newChar); } } } String q = buff.toString(); try { parser.createQueryObjectModel(q); } catch (ValueFormatException e) { // OK } catch (InvalidQueryException e) { // OK } catch (NamespaceException e) { // OK? } catch (Throwable t) { t.printStackTrace(); assertTrue("Unexpected exception for query " + q + ": " + t, false); } } } }
JCR-2996: QOM to SQL2 doesn't cast numeric literals git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1137572 13f79535-47bb-0310-9956-ffa450edef68
jackrabbit-spi-commons/src/test/java/org/apache/jackrabbit/spi/commons/query/sql2/ParserTest.java
JCR-2996: QOM to SQL2 doesn't cast numeric literals
<ide><path>ackrabbit-spi-commons/src/test/java/org/apache/jackrabbit/spi/commons/query/sql2/ParserTest.java <ide> } <ide> } <ide> <add> public void testFormatLiterals() throws Exception { <add> formatLiteral("true", "true"); <add> formatLiteral("false", "false"); <add> <add> formatLiteral("CAST('2000-01-01T12:00:00.000Z' AS DATE)", <add> "CAST('2000-01-01T12:00:00.000Z' AS DATE)"); <add> formatLiteral("CAST(0 AS DATE)", <add> "CAST('1970-01-01T00:00:00.000Z' AS DATE)"); <add> <add> formatLiteral("1", "CAST('1' AS LONG)"); <add> formatLiteral("-1", "CAST('-1' AS LONG)"); <add> formatLiteral("CAST(" + Long.MAX_VALUE + " AS LONG)", <add> "CAST('" + Long.MAX_VALUE + "' AS LONG)"); <add> formatLiteral("CAST(" + Long.MIN_VALUE + " AS LONG)", <add> "CAST('" + Long.MIN_VALUE + "' AS LONG)"); <add> <add> formatLiteral("1.0", "CAST('1.0' AS DECIMAL)"); <add> formatLiteral("-1.0", "CAST('-1.0' AS DECIMAL)"); <add> formatLiteral("100000000000000000000", <add> "CAST('100000000000000000000' AS DECIMAL)"); <add> formatLiteral("-100000000000000000000", <add> "CAST('-100000000000000000000' AS DECIMAL)"); <add> <add> formatLiteral("CAST(1.0 AS DOUBLE)", "CAST('1.0' AS DOUBLE)"); <add> formatLiteral("CAST(-1.0 AS DOUBLE)", "CAST('-1.0' AS DOUBLE)"); <add> <add> formatLiteral("CAST('X' AS NAME)", "CAST('X' AS NAME)"); <add> formatLiteral("CAST('X' AS PATH)", "CAST('X' AS PATH)"); <add> formatLiteral("CAST('X' AS REFERENCE)", "CAST('X' AS REFERENCE)"); <add> formatLiteral("CAST('X' AS WEAKREFERENCE)", "CAST('X' AS WEAKREFERENCE)"); <add> formatLiteral("CAST('X' AS URI)", "CAST('X' AS URI)"); <add> <add> formatLiteral("''", "''"); <add> formatLiteral("' '", "' '"); <add> formatLiteral("CAST(0 AS STRING)", "'0'"); <add> formatLiteral("CAST(-1000000000000 AS STRING)", "'-1000000000000'"); <add> formatLiteral("CAST(false AS STRING)", "'false'"); <add> formatLiteral("CAST(true AS STRING)", "'true'"); <add> } <add> <add> private void formatLiteral(String literal, String cast) throws Exception { <add> String s = "SELECT TEST.* FROM TEST WHERE ID=" + literal; <add> QueryObjectModel qom = parser.createQueryObjectModel(s); <add> String s2 = QOMFormatter.format(qom); <add> String cast2 = s2.substring(s2.indexOf('=') + 1).trim(); <add> assertEquals(cast, cast2); <add> qom = parser.createQueryObjectModel(s); <add> s2 = QOMFormatter.format(qom); <add> cast2 = s2.substring(s2.indexOf('=') + 1).trim(); <add> assertEquals(cast, cast2); <add> } <add> <ide> public void testParseScript() throws Exception { <ide> LineNumberReader reader = openScript("test.sql2.txt"); <ide> while (true) {
Java
apache-2.0
83e03c898c45e1cafd9d10b6fe1f52f39b3ea43e
0
rouazana/james,rouazana/james,aduprat/james,chibenwa/james,aduprat/james,aduprat/james,chibenwa/james,aduprat/james,rouazana/james,chibenwa/james,rouazana/james,chibenwa/james
/**************************************************************** * 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.james.remotemanager.core; import java.io.UnsupportedEncodingException; import org.apache.james.protocols.api.ConnectHandler; import org.apache.james.protocols.api.LineHandler; import org.apache.james.remotemanager.RemoteManagerResponse; import org.apache.james.remotemanager.RemoteManagerSession; public class AuthorizationHandler implements ConnectHandler<RemoteManagerSession> { private final static String AUTHORIZATION_STATE = "AUTHORIZATION_STATE"; private final static int LOGIN_SUPPLIED = 1; private final static int PASSWORD_SUPPLIED = 2; private final static String USERNAME = "USERNAME"; private final LineHandler<RemoteManagerSession> lineHandler = new AuthorizationLineHandler(); /* * (non-Javadoc) * * @see * org.apache.james.remotemanager.ConnectHandler#onConnect(org.apache.james * .remotemanager.RemoteManagerSession) */ public void onConnect(RemoteManagerSession session) { RemoteManagerResponse response = new RemoteManagerResponse("JAMES Remote Administration Tool ");// + // Constants.SOFTWARE_VERSION) response.appendLine("Please enter your login and password"); response.appendLine("Login id:"); session.writeResponse(response); session.pushLineHandler(lineHandler); session.getState().put(AUTHORIZATION_STATE, LOGIN_SUPPLIED); } private final class AuthorizationLineHandler implements LineHandler<RemoteManagerSession> { public void onLine(RemoteManagerSession session, byte[] byteLine) { try { String line = new String(byteLine, "ISO-8859-1").trim(); int state = (Integer) session.getState().get(AUTHORIZATION_STATE); if (state == LOGIN_SUPPLIED) { session.getState().put(USERNAME, line); session.getState().put(AUTHORIZATION_STATE, PASSWORD_SUPPLIED); session.writeResponse(new RemoteManagerResponse("Password:")); } else if (state == PASSWORD_SUPPLIED) { String password = line; String username = (String) session.getState().get(USERNAME); if (!password.equals(session.getAdministrativeAccountData().get(username)) || password.length() == 0) { final String message = "Login failed for " + username; session.writeResponse(new RemoteManagerResponse(message)); session.writeResponse(new RemoteManagerResponse("Login id:")); // we need to handle the next line as login again session.getState().put(AUTHORIZATION_STATE, LOGIN_SUPPLIED); } else { StringBuilder messageBuffer = new StringBuilder(64).append("Welcome ").append(username).append(". HELP for a list of commands"); session.writeResponse(new RemoteManagerResponse(messageBuffer.toString())); if (session.getLogger().isInfoEnabled()) { StringBuilder infoBuffer = new StringBuilder(128).append("Login for ").append(username).append(" successful"); session.getLogger().info(infoBuffer.toString()); } session.popLineHandler(); } session.getState().remove(USERNAME); } } catch (UnsupportedEncodingException e) { // Should never happen e.printStackTrace(); } } } }
remotemanager/src/main/java/org/apache/james/remotemanager/core/AuthorizationHandler.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.james.remotemanager.core; import java.io.UnsupportedEncodingException; import org.apache.james.protocols.api.ConnectHandler; import org.apache.james.protocols.api.LineHandler; import org.apache.james.remotemanager.RemoteManagerResponse; import org.apache.james.remotemanager.RemoteManagerSession; public class AuthorizationHandler implements ConnectHandler<RemoteManagerSession> { private final static String AUTHORIZATION_STATE = "AUTHORIZATION_STATE"; private final static int LOGIN_SUPPLIED = 1; private final static int PASSWORD_SUPPLIED = 2; private final static String USERNAME = "USERNAME"; private final LineHandler<RemoteManagerSession> lineHandler = new AuthorizationLineHandler(); /* * (non-Javadoc) * * @see * org.apache.james.remotemanager.ConnectHandler#onConnect(org.apache.james * .remotemanager.RemoteManagerSession) */ public void onConnect(RemoteManagerSession session) { RemoteManagerResponse response = new RemoteManagerResponse("JAMES Remote Administration Tool ");// + // Constants.SOFTWARE_VERSION) response.appendLine("Please enter your login and password"); response.appendLine("Login id:"); session.writeResponse(response); session.pushLineHandler(lineHandler); session.getState().put(AUTHORIZATION_STATE, LOGIN_SUPPLIED); } private final class AuthorizationLineHandler implements LineHandler<RemoteManagerSession> { public void onLine(RemoteManagerSession session, byte[] byteLine) { try { String line = new String(byteLine, "ISO-8859-1").trim(); int state = (Integer) session.getState().get(AUTHORIZATION_STATE); if (state == LOGIN_SUPPLIED) { session.getState().put(USERNAME, line); session.getState().put(AUTHORIZATION_STATE, PASSWORD_SUPPLIED); session.writeResponse(new RemoteManagerResponse("Password:")); } else if (state == PASSWORD_SUPPLIED) { String password = line; String username = (String) session.getState().get(USERNAME); if (!password.equals(session.getAdministrativeAccountData().get(username)) || password.length() == 0) { final String message = "Login failed for " + username; session.writeResponse(new RemoteManagerResponse(message)); session.writeResponse(new RemoteManagerResponse("Login id:")); } else { StringBuilder messageBuffer = new StringBuilder(64).append("Welcome ").append(username).append(". HELP for a list of commands"); session.writeResponse(new RemoteManagerResponse(messageBuffer.toString())); if (session.getLogger().isInfoEnabled()) { StringBuilder infoBuffer = new StringBuilder(128).append("Login for ").append(username).append(" successful"); session.getLogger().info(infoBuffer.toString()); } session.popLineHandler(); } session.getState().remove(USERNAME); } } catch (UnsupportedEncodingException e) { // Should never happen e.printStackTrace(); } } } }
Fix login on second attempt (JAMES-974) git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@915221 13f79535-47bb-0310-9956-ffa450edef68
remotemanager/src/main/java/org/apache/james/remotemanager/core/AuthorizationHandler.java
Fix login on second attempt (JAMES-974)
<ide><path>emotemanager/src/main/java/org/apache/james/remotemanager/core/AuthorizationHandler.java <ide> final String message = "Login failed for " + username; <ide> session.writeResponse(new RemoteManagerResponse(message)); <ide> session.writeResponse(new RemoteManagerResponse("Login id:")); <add> <add> // we need to handle the next line as login again <add> session.getState().put(AUTHORIZATION_STATE, LOGIN_SUPPLIED); <add> <ide> } else { <ide> StringBuilder messageBuffer = new StringBuilder(64).append("Welcome ").append(username).append(". HELP for a list of commands"); <ide> session.writeResponse(new RemoteManagerResponse(messageBuffer.toString()));
Java
apache-2.0
8e7d8baf8c4a9d0779d85b23c0466d53cc18aebd
0
jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
package de.fernunihagen.dna.jkn.scalephant; import java.io.File; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import de.fernunihagen.dna.jkn.scalephant.storage.BoundingBox; import de.fernunihagen.dna.jkn.scalephant.storage.StorageConfiguration; import de.fernunihagen.dna.jkn.scalephant.storage.StorageInterface; import de.fernunihagen.dna.jkn.scalephant.storage.StorageManager; import de.fernunihagen.dna.jkn.scalephant.storage.StorageManagerException; import de.fernunihagen.dna.jkn.scalephant.storage.Tuple; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableCompactor; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableIndexReader; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableReader; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableWriter; public class TestTableCompactor { protected final static String TEST_RELATION = "testrelation"; protected final StorageConfiguration storageConfiguration = new StorageConfiguration(); @Before public void clearData() { final StorageManager storageManager = StorageInterface.getStorageManager(TEST_RELATION); storageManager.clear(); storageManager.shutdown(); } @Test public void testCompactTestFileCreation() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("2", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); boolean compactResult = compactor.executeCompactation(); Assert.assertTrue(compactResult); Assert.assertTrue(writer.getSstableFile().exists()); Assert.assertTrue(writer.getSstableIndexFile().exists()); writer.close(); } @Test public void testCompactTestFileCreation2() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("2", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(tuple); } Assert.assertEquals(tupleList1.size() + tupleList2.size(), counter); } @Test public void testCompactTestFileCreation3() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(tuple); } Assert.assertEquals(tupleList1.size() + tupleList2.size(), counter); } @Test public void testCompactTestFileCreation4() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("2", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(tuple); } Assert.assertEquals(tupleList1.size() + tupleList2.size(), counter); } @Test public void testCompactTestFileCreation5() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("1", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(new String(tuple.getDataBytes())); Assert.assertEquals("def", new String(tuple.getDataBytes())); } Assert.assertEquals(1, counter); } protected SSTableIndexReader addTuplesToFile(final List<Tuple> tupleList, int number) throws StorageManagerException { final SSTableWriter ssTableWriter = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, number); ssTableWriter.open(); ssTableWriter.addData(tupleList); final File sstableFile = ssTableWriter.getSstableFile(); ssTableWriter.close(); final SSTableReader sstableReader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), sstableFile); sstableReader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(sstableReader); ssTableIndexReader.init(); return ssTableIndexReader; } }
src/test/java/de/fernunihagen/dna/jkn/scalephant/TestTableCompactor.java
package de.fernunihagen.dna.jkn.scalephant; import java.io.File; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import de.fernunihagen.dna.jkn.scalephant.storage.BoundingBox; import de.fernunihagen.dna.jkn.scalephant.storage.StorageConfiguration; import de.fernunihagen.dna.jkn.scalephant.storage.StorageInterface; import de.fernunihagen.dna.jkn.scalephant.storage.StorageManager; import de.fernunihagen.dna.jkn.scalephant.storage.StorageManagerException; import de.fernunihagen.dna.jkn.scalephant.storage.Tuple; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableCompactor; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableIndexReader; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableReader; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableWriter; public class TestTableCompactor { protected final static String TEST_RELATION = "testrelation"; protected final StorageConfiguration storageConfiguration = new StorageConfiguration(); @Before public void clearData() { final StorageManager storageManager = StorageInterface.getStorageManager(TEST_RELATION); storageManager.clear(); storageManager.shutdown(); } @Test public void testCompactTestFileCreation() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("2", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); boolean compactResult = compactor.executeCompactation(); Assert.assertTrue(compactResult); Assert.assertTrue(writer.getSstableFile().exists()); Assert.assertTrue(writer.getSstableIndexFile().exists()); writer.close(); } @Test public void testCompactTestFileCreation2() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("2", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(tuple); } Assert.assertEquals(tupleList1.size() + tupleList2.size(), counter); } @Test public void testCompactTestFileCreation3() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(tuple); } Assert.assertEquals(tupleList1.size() + tupleList2.size(), counter); } @Test public void testCompactTestFileCreation4() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("2", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); int counter = 0; for(final Tuple tuple : ssTableIndexReader) { counter++; System.out.println(tuple); } Assert.assertEquals(tupleList1.size() + tupleList2.size(), counter); } @Test public void testCompactTestFileCreation5() throws StorageManagerException { final List<Tuple> tupleList1 = new ArrayList<Tuple>(); tupleList1.add(new Tuple("1", BoundingBox.EMPTY_BOX, "abc".getBytes())); final SSTableIndexReader reader1 = addTuplesToFile(tupleList1, 1); final List<Tuple> tupleList2 = new ArrayList<Tuple>(); tupleList2.add(new Tuple("1", BoundingBox.EMPTY_BOX, "def".getBytes())); final SSTableIndexReader reader2 = addTuplesToFile(tupleList2, 2); final SSTableWriter writer = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, 3); final SSTableCompactor compactor = new SSTableCompactor(reader1, reader2, writer); compactor.executeCompactation(); writer.close(); final SSTableReader reader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), writer.getSstableFile()); reader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); ssTableIndexReader.init(); for(final Tuple tuple : ssTableIndexReader) { System.out.println(new String(tuple.getDataBytes())); Assert.assertEquals("def", new String(tuple.getDataBytes())); } } protected SSTableIndexReader addTuplesToFile(final List<Tuple> tupleList, int number) throws StorageManagerException { final SSTableWriter ssTableWriter = new SSTableWriter(storageConfiguration.getDataDir(), TEST_RELATION, number); ssTableWriter.open(); ssTableWriter.addData(tupleList); final File sstableFile = ssTableWriter.getSstableFile(); ssTableWriter.close(); final SSTableReader sstableReader = new SSTableReader(TEST_RELATION, storageConfiguration.getDataDir(), sstableFile); sstableReader.init(); final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(sstableReader); ssTableIndexReader.init(); return ssTableIndexReader; } }
Check number of tuples
src/test/java/de/fernunihagen/dna/jkn/scalephant/TestTableCompactor.java
Check number of tuples
<ide><path>rc/test/java/de/fernunihagen/dna/jkn/scalephant/TestTableCompactor.java <ide> final SSTableIndexReader ssTableIndexReader = new SSTableIndexReader(reader); <ide> ssTableIndexReader.init(); <ide> <del> for(final Tuple tuple : ssTableIndexReader) { <add> int counter = 0; <add> for(final Tuple tuple : ssTableIndexReader) { <add> counter++; <ide> System.out.println(new String(tuple.getDataBytes())); <ide> Assert.assertEquals("def", new String(tuple.getDataBytes())); <ide> } <ide> <add> Assert.assertEquals(1, counter); <ide> } <ide> <ide>
Java
mit
d0cf712c037c60aad73b96133c43bf0ec23f783a
0
zalando/nakadi,zalando/nakadi
package de.zalando.aruha.nakadi.controller; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import de.zalando.aruha.nakadi.NakadiException; import de.zalando.aruha.nakadi.domain.Cursor; import de.zalando.aruha.nakadi.repository.EventConsumer; import de.zalando.aruha.nakadi.repository.TopicRepository; import de.zalando.aruha.nakadi.service.EventStream; import de.zalando.aruha.nakadi.service.EventStreamConfig; import de.zalando.aruha.nakadi.utils.FlushableGZIPOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.zalando.problem.Problem; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.PRECONDITION_FAILED; import static javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE; import static org.zalando.problem.MoreStatus.UNPROCESSABLE_ENTITY; @RestController public class EventStreamController { private static final Logger LOG = LoggerFactory.getLogger(EventStreamController.class); private final TopicRepository topicRepository; private final ObjectMapper jsonMapper; public EventStreamController(final TopicRepository topicRepository, final ObjectMapper jsonMapper) { this.topicRepository = topicRepository; this.jsonMapper = jsonMapper; } @Timed(name = "stream_events_for_event_type", absolute = true) @RequestMapping(value = "/event-types/{name}/events", method = RequestMethod.GET) public StreamingResponseBody streamEventsFromPartition( @PathVariable("name") final String eventTypeName, @RequestParam(value = "batch_limit", required = false, defaultValue = "1") final int batchLimit, @RequestParam(value = "stream_limit", required = false, defaultValue = "0") final int streamLimit, @RequestParam(value = "batch_flush_timeout", required = false, defaultValue = "30") final int batchTimeout, @RequestParam(value = "stream_timeout", required = false, defaultValue = "0") final int streamTimeout, @RequestParam(value = "stream_keep_alive_limit", required = false, defaultValue = "0") final int streamKeepAliveLimit, @Nullable @RequestHeader(name = "X-nakadi-cursors", required = false) final String cursorsStr, final NativeWebRequest request, final HttpServletResponse response) throws IOException { return outputStream -> { try { // todo: we should get topic from EventType after persistence of EventType is implemented @SuppressWarnings("UnnecessaryLocalVariable") final String topic = eventTypeName; // validate parameters if (!topicRepository.topicExists(topic)) { writeProblemResponse(response, outputStream, NOT_FOUND, "topic not found"); return; } if (streamLimit != 0 && streamLimit < batchLimit) { writeProblemResponse(response, outputStream, UNPROCESSABLE_ENTITY, "stream_limit can't be lower than batch_limit"); return; } if (streamTimeout != 0 && streamTimeout < batchTimeout) { writeProblemResponse(response, outputStream, UNPROCESSABLE_ENTITY, "stream_timeout can't be lower than batch_flush_timeout"); return; } // deserialize cursors List<Cursor> cursors = null; if (cursorsStr != null) { try { cursors = jsonMapper.<List<Cursor>>readValue(cursorsStr, new TypeReference<ArrayList<Cursor>>() { }); } catch (IOException e) { writeProblemResponse(response, outputStream, BAD_REQUEST, "incorrect syntax of X-nakadi-cursors header"); return; } } // check that offsets are not out of bounds and partitions exist if (cursors != null && !topicRepository.areCursorsValid(topic, cursors)) { writeProblemResponse(response, outputStream, PRECONDITION_FAILED, "cursors are not valid"); return; } // if no cursors provided - read from the newest available events if (cursors == null) { cursors = topicRepository .listPartitions(topic) .stream() .map(pInfo -> new Cursor(pInfo.getPartitionId(), pInfo.getNewestAvailableOffset())) .collect(Collectors.toList()); } final Map<String, String> streamCursors = cursors .stream() .collect(Collectors.toMap( Cursor::getPartition, Cursor::getOffset)); final EventStreamConfig streamConfig = new EventStreamConfig(topic, streamCursors, batchLimit, streamLimit, batchTimeout, streamTimeout, streamKeepAliveLimit); response.setStatus(HttpStatus.OK.value()); final String acceptEncoding = request.getHeader("Accept-Encoding"); final boolean gzipEnabled = acceptEncoding != null && acceptEncoding.contains("gzip"); final OutputStream output = gzipEnabled ? new FlushableGZIPOutputStream(outputStream) : outputStream; if (gzipEnabled) { response.addHeader("Content-Encoding", "gzip"); } final EventConsumer eventConsumer = topicRepository.createEventConsumer(topic, streamConfig.getCursors()); final EventStream eventStream = new EventStream(eventConsumer, output, streamConfig); eventStream.streamEvents(); if (gzipEnabled) { output.close(); } } catch (final NakadiException e) { writeProblemResponse(response, outputStream, SERVICE_UNAVAILABLE, e.getProblemMessage()); } catch (final Exception e) { writeProblemResponse(response, outputStream, INTERNAL_SERVER_ERROR, e.getMessage()); } finally { outputStream.flush(); outputStream.close(); } }; } private void writeProblemResponse(final HttpServletResponse response, final OutputStream outputStream, final Response.StatusType statusCode, final String message) throws IOException { response.setStatus(statusCode.getStatusCode()); jsonMapper.writer().writeValue(outputStream, Problem.valueOf(statusCode, message)); } }
src/main/java/de/zalando/aruha/nakadi/controller/EventStreamController.java
package de.zalando.aruha.nakadi.controller; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import de.zalando.aruha.nakadi.NakadiException; import de.zalando.aruha.nakadi.domain.Cursor; import de.zalando.aruha.nakadi.repository.EventConsumer; import de.zalando.aruha.nakadi.repository.TopicRepository; import de.zalando.aruha.nakadi.service.EventStream; import de.zalando.aruha.nakadi.service.EventStreamConfig; import de.zalando.aruha.nakadi.utils.FlushableGZIPOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import org.zalando.problem.Problem; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.PRECONDITION_FAILED; import static javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE; import static org.zalando.problem.MoreStatus.UNPROCESSABLE_ENTITY; @RestController public class EventStreamController { private static final Logger LOG = LoggerFactory.getLogger(EventStreamController.class); private final TopicRepository topicRepository; private final ObjectMapper jsonMapper; public EventStreamController(final TopicRepository topicRepository, final ObjectMapper jsonMapper) { this.topicRepository = topicRepository; this.jsonMapper = jsonMapper; } @Timed(name = "stream_events_for_event_type", absolute = true) @RequestMapping(value = "/event-types/{name}/events", method = RequestMethod.GET) public StreamingResponseBody streamEventsFromPartition( @PathVariable("name") final String eventTypeName, @RequestParam(value = "batch_limit", required = false, defaultValue = "1") final int batchLimit, @RequestParam(value = "stream_limit", required = false, defaultValue = "0") final int streamLimit, @RequestParam(value = "batch_flush_timeout", required = false, defaultValue = "30") final int batchTimeout, @RequestParam(value = "stream_timeout", required = false, defaultValue = "0") final int streamTimeout, @RequestParam(value = "stream_keep_alive_limit", required = false, defaultValue = "0") final int streamKeepAliveLimit, @Nullable @RequestHeader(name = "X-Flow-Id", required = false) final String flowId, @Nullable @RequestHeader(name = "X-nakadi-cursors", required = false) final String cursorsStr, final NativeWebRequest request, final HttpServletResponse response) throws IOException { LOG.trace("starting event stream for flow id: {}", flowId); return outputStream -> { try { // todo: we should get topic from EventType after persistence of EventType is implemented @SuppressWarnings("UnnecessaryLocalVariable") final String topic = eventTypeName; // validate parameters if (!topicRepository.topicExists(topic)) { writeProblemResponse(response, outputStream, NOT_FOUND, "topic not found"); return; } if (streamLimit != 0 && streamLimit < batchLimit) { writeProblemResponse(response, outputStream, UNPROCESSABLE_ENTITY, "stream_limit can't be lower than batch_limit"); return; } if (streamTimeout != 0 && streamTimeout < batchTimeout) { writeProblemResponse(response, outputStream, UNPROCESSABLE_ENTITY, "stream_timeout can't be lower than batch_flush_timeout"); return; } // deserialize cursors List<Cursor> cursors = null; if (cursorsStr != null) { try { cursors = jsonMapper.<List<Cursor>>readValue(cursorsStr, new TypeReference<ArrayList<Cursor>>() { }); } catch (IOException e) { writeProblemResponse(response, outputStream, BAD_REQUEST, "incorrect syntax of X-nakadi-cursors header"); return; } } // check that offsets are not out of bounds and partitions exist if (cursors != null && !topicRepository.areCursorsValid(topic, cursors)) { writeProblemResponse(response, outputStream, PRECONDITION_FAILED, "cursors are not valid"); return; } // if no cursors provided - read from the newest available events if (cursors == null) { cursors = topicRepository .listPartitions(topic) .stream() .map(pInfo -> new Cursor(pInfo.getPartitionId(), pInfo.getNewestAvailableOffset())) .collect(Collectors.toList()); } final Map<String, String> streamCursors = cursors .stream() .collect(Collectors.toMap( Cursor::getPartition, Cursor::getOffset)); final EventStreamConfig streamConfig = new EventStreamConfig(topic, streamCursors, batchLimit, streamLimit, batchTimeout, streamTimeout, streamKeepAliveLimit); response.setStatus(HttpStatus.OK.value()); final String acceptEncoding = request.getHeader("Accept-Encoding"); final boolean gzipEnabled = acceptEncoding != null && acceptEncoding.contains("gzip"); final OutputStream output = gzipEnabled ? new FlushableGZIPOutputStream(outputStream) : outputStream; if (gzipEnabled) { response.addHeader("Content-Encoding", "gzip"); } final EventConsumer eventConsumer = topicRepository.createEventConsumer(topic, streamConfig.getCursors()); final EventStream eventStream = new EventStream(eventConsumer, output, streamConfig); eventStream.streamEvents(); if (gzipEnabled) { output.close(); } } catch (final NakadiException e) { writeProblemResponse(response, outputStream, SERVICE_UNAVAILABLE, e.getProblemMessage()); } catch (final Exception e) { writeProblemResponse(response, outputStream, INTERNAL_SERVER_ERROR, e.getMessage()); } finally { outputStream.flush(); outputStream.close(); } }; } private void writeProblemResponse(final HttpServletResponse response, final OutputStream outputStream, final Response.StatusType statusCode, final String message) throws IOException { response.setStatus(statusCode.getStatusCode()); jsonMapper.writer().writeValue(outputStream, Problem.valueOf(statusCode, message)); } }
ARUHA-78: removed flow id;
src/main/java/de/zalando/aruha/nakadi/controller/EventStreamController.java
ARUHA-78: removed flow id;
<ide><path>rc/main/java/de/zalando/aruha/nakadi/controller/EventStreamController.java <ide> @RequestParam(value = "batch_flush_timeout", required = false, defaultValue = "30") final int batchTimeout, <ide> @RequestParam(value = "stream_timeout", required = false, defaultValue = "0") final int streamTimeout, <ide> @RequestParam(value = "stream_keep_alive_limit", required = false, defaultValue = "0") final int streamKeepAliveLimit, <del> @Nullable @RequestHeader(name = "X-Flow-Id", required = false) final String flowId, <ide> @Nullable @RequestHeader(name = "X-nakadi-cursors", required = false) final String cursorsStr, <ide> final NativeWebRequest request, final HttpServletResponse response) throws IOException { <del> <del> LOG.trace("starting event stream for flow id: {}", flowId); <ide> <ide> return outputStream -> { <ide> try {
Java
apache-2.0
6597d8a77f38c24565d4120e971dcab28d46cea4
0
apache/commons-io,apache/commons-io,apache/commons-io
/* * 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.commons.io; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; /** * This is used to test FileUtils.waitFor() method for correctness. * * @see FileUtils */ public class FileUtilsWaitForTestCase { // This class has been broken out from FileUtilsTestCase // to solve issues as per BZ 38927 @Test public void testWaitFor() { FileUtils.waitFor(FileUtils.current(), -1); } @Test public void testWaitForInterrupted() throws InterruptedException { final AtomicBoolean wasInterrupted = new AtomicBoolean(); final CountDownLatch started = new CountDownLatch(1); final Thread thread1 = new Thread(() -> { started.countDown(); assertTrue(FileUtils.waitFor(FileUtils.current(), 4)); wasInterrupted.set(Thread.currentThread().isInterrupted()); }); thread1.start(); thread1.interrupt(); started.await(); thread1.join(); assertTrue(wasInterrupted.get()); } @Test public void testWaitForNegativeDuration() { FileUtils.waitFor(FileUtils.current(), -1); } }
src/test/java/org/apache/commons/io/FileUtilsWaitForTestCase.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.commons.io; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; /** * This is used to test FileUtils.waitFor() method for correctness. * * @see FileUtils */ public class FileUtilsWaitForTestCase { // This class has been broken out from FileUtilsTestCase // to solve issues as per BZ 38927 @Test public void testWaitFor() { FileUtils.waitFor(FileUtils.current(), -1); } @Test public void testWaitForInterrupted() throws InterruptedException { final AtomicBoolean wasInterrupted = new AtomicBoolean(false); final CountDownLatch started = new CountDownLatch(1); final Thread thread1 = new Thread(() -> { started.countDown(); assertTrue(FileUtils.waitFor(FileUtils.current(), 4)); wasInterrupted.set(Thread.currentThread().isInterrupted()); }); thread1.start(); started.await(); thread1.interrupt(); thread1.join(); assertTrue(wasInterrupted.get()); } @Test public void testWaitForNegativeDuration() { FileUtils.waitFor(FileUtils.current(), -1); } }
No need to specify value equal to the default. Trying to fix random failures on GitHub builds.
src/test/java/org/apache/commons/io/FileUtilsWaitForTestCase.java
No need to specify value equal to the default.
<ide><path>rc/test/java/org/apache/commons/io/FileUtilsWaitForTestCase.java <ide> <ide> @Test <ide> public void testWaitForInterrupted() throws InterruptedException { <del> final AtomicBoolean wasInterrupted = new AtomicBoolean(false); <add> final AtomicBoolean wasInterrupted = new AtomicBoolean(); <ide> final CountDownLatch started = new CountDownLatch(1); <ide> final Thread thread1 = new Thread(() -> { <ide> started.countDown(); <ide> wasInterrupted.set(Thread.currentThread().isInterrupted()); <ide> }); <ide> thread1.start(); <add> thread1.interrupt(); <ide> started.await(); <del> thread1.interrupt(); <ide> thread1.join(); <ide> assertTrue(wasInterrupted.get()); <ide> }
Java
apache-2.0
8f399a7a5b9c6b477615c7f05d0d8d58fba65093
0
EvilMcJerkface/Aeron,mikeb01/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,galderz/Aeron,real-logic/Aeron,real-logic/Aeron,mikeb01/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,mikeb01/Aeron,galderz/Aeron,galderz/Aeron,EvilMcJerkface/Aeron
/* * Copyright 2014-2018 Real Logic 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 io.aeron; import io.aeron.driver.*; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.Header; import io.aeron.protocol.DataHeaderFlyweight; import org.agrona.DirectBuffer; import org.agrona.IoUtil; import org.agrona.collections.MutableInteger; import org.agrona.concurrent.UnsafeBuffer; import org.junit.After; import org.junit.Test; import java.io.File; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; /** * Tests requiring multiple embedded drivers for FlowControl strategies */ public class FlowControlStrategiesTest { private static final String MULTICAST_URI = "aeron:udp?endpoint=224.20.30.39:54326|interface=localhost"; private static final int STREAM_ID = 1; private static final int TERM_BUFFER_LENGTH = 64 * 1024; private static final int NUM_MESSAGES_PER_TERM = 64; private static final int MESSAGE_LENGTH = (TERM_BUFFER_LENGTH / NUM_MESSAGES_PER_TERM) - DataHeaderFlyweight.HEADER_LENGTH; private static final String ROOT_DIR = IoUtil.tmpDirName() + "aeron-system-tests-" + UUID.randomUUID().toString() + File.separator; private final MediaDriver.Context driverAContext = new MediaDriver.Context(); private final MediaDriver.Context driverBContext = new MediaDriver.Context(); private Aeron clientA; private Aeron clientB; private MediaDriver driverA; private MediaDriver driverB; private Publication publication; private Subscription subscriptionA; private Subscription subscriptionB; private UnsafeBuffer buffer = new UnsafeBuffer(new byte[MESSAGE_LENGTH]); private FragmentHandler fragmentHandlerA = mock(FragmentHandler.class); private FragmentHandler fragmentHandlerB = mock(FragmentHandler.class); private void launch() { final String baseDirA = ROOT_DIR + "A"; final String baseDirB = ROOT_DIR + "B"; buffer.putInt(0, 1); driverAContext.publicationTermBufferLength(TERM_BUFFER_LENGTH) .aeronDirectoryName(baseDirA) .errorHandler(Throwable::printStackTrace) .threadingMode(ThreadingMode.SHARED); driverBContext.publicationTermBufferLength(TERM_BUFFER_LENGTH) .aeronDirectoryName(baseDirB) .errorHandler(Throwable::printStackTrace) .threadingMode(ThreadingMode.SHARED); driverA = MediaDriver.launch(driverAContext); driverB = MediaDriver.launch(driverBContext); clientA = Aeron.connect(new Aeron.Context().aeronDirectoryName(driverAContext.aeronDirectoryName())); clientB = Aeron.connect(new Aeron.Context().aeronDirectoryName(driverBContext.aeronDirectoryName())); } @After public void after() { clientB.close(); clientA.close(); driverB.close(); driverA.close(); IoUtil.delete(new File(ROOT_DIR), true); } @Test(timeout = 10_000) public void shouldSpinUpAndShutdown() { launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } } @Test(timeout = 10_000) public void shouldTimeoutImageWhenBehindForTooLongWithMaxMulticastFlowControlStrategy() throws Exception { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; final CountDownLatch unavailableCountDownLatch = new CountDownLatch(1); final CountDownLatch availableCountDownLatch = new CountDownLatch(2); driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new MaxMulticastFlowControl()); launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription( MULTICAST_URI, STREAM_ID, (image) -> availableCountDownLatch.countDown(), (image) -> unavailableCountDownLatch.countDown()); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (int i = 0; i < numMessagesToSend; i++) { while (publication.offer(buffer, 0, buffer.capacity()) < 0L) { SystemTest.checkInterruptedStatus(); Thread.yield(); } // A keeps up final MutableInteger fragmentsRead = new MutableInteger(); SystemTest.executeUntil( () -> fragmentsRead.get() > 0, (j) -> { fragmentsRead.value += subscriptionA.poll(fragmentHandlerA, 10); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(500)); fragmentsRead.set(0); // B receives slowly and eventually can't keep up if (i % 10 == 0) { SystemTest.executeUntil( () -> fragmentsRead.get() > 0, (j) -> { fragmentsRead.value += subscriptionB.poll(fragmentHandlerB, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(500)); } } unavailableCountDownLatch.await(); availableCountDownLatch.await(); verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, atMost(numMessagesToSend - 1)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldSlowDownWhenBehindWithMinMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; int numFragmentsFromB = 0; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new MinMulticastFlowControl()); launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (long i = 0; numFragmentsFromA < numMessagesToSend || numFragmentsFromB < numMessagesToSend; i++) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } SystemTest.checkInterruptedStatus(); Thread.yield(); // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives slowly if ((i % 2) == 0) { numFragmentsFromB += subscriptionB.poll(fragmentHandlerB, 1); } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldRemoveDeadReceiverWithMinMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; int numFragmentsFromB = 0; boolean isClosedB = false; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new MinMulticastFlowControl()); launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } while (numFragmentsFromA < numMessagesToSend) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives up to 1/8 of the messages, then stops if (numFragmentsFromB < (numMessagesToSend / 8)) { numFragmentsFromB += subscriptionB.poll(fragmentHandlerB, 10); } else if (!isClosedB) { subscriptionB.close(); isClosedB = true; } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldSlowDownToSlowPreferredWithPreferredMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; int numFragmentsFromB = 0; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new PreferredMulticastFlowControl()); driverBContext.applicationSpecificFeedback(PreferredMulticastFlowControl.PREFERRED_ASF_BYTES); launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (long i = 0; numFragmentsFromB < numMessagesToSend || numFragmentsFromA < numMessagesToSend; i++) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } SystemTest.checkInterruptedStatus(); Thread.yield(); // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives slowly if ((i % 2) == 0) { numFragmentsFromB += subscriptionB.poll(fragmentHandlerB, 1); } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldKeepUpToFastPreferredWithPreferredMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new PreferredMulticastFlowControl()); driverAContext.applicationSpecificFeedback(PreferredMulticastFlowControl.PREFERRED_ASF_BYTES); launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (long i = 0; numFragmentsFromA < numMessagesToSend; i++) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } SystemTest.checkInterruptedStatus(); Thread.yield(); // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives slowly if ((i % 2) == 0) { subscriptionB.poll(fragmentHandlerB, 1); } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, atMost(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldRemoveDeadPreferredReceiverWithPreferredMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsReadFromA = 0, numFragmentsReadFromB = 0; boolean isBClosed = false; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new PreferredMulticastFlowControl()); driverBContext.applicationSpecificFeedback(PreferredMulticastFlowControl.PREFERRED_ASF_BYTES); launch(); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } while (numFragmentsReadFromA < numMessagesToSend) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } // A keeps up numFragmentsReadFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives up to 1/8 of the messages, then stops if (numFragmentsReadFromB < (numMessagesToSend / 8)) { numFragmentsReadFromB += subscriptionB.poll(fragmentHandlerB, 10); } else if (!isBClosed) { subscriptionB.close(); isBClosed = true; } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } }
aeron-system-tests/src/test/java/io/aeron/FlowControlStrategiesTest.java
/* * Copyright 2014-2018 Real Logic 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 io.aeron; import io.aeron.driver.*; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.Header; import io.aeron.protocol.DataHeaderFlyweight; import org.agrona.DirectBuffer; import org.agrona.IoUtil; import org.agrona.collections.MutableInteger; import org.agrona.concurrent.UnsafeBuffer; import org.junit.After; import org.junit.Test; import java.io.File; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; /** * Tests requiring multiple embedded drivers for FlowControl strategies */ public class FlowControlStrategiesTest { private static final String MULTICAST_URI = "aeron:udp?endpoint=224.20.30.39:54326|interface=localhost"; private static final int STREAM_ID = 1; private static final int TERM_BUFFER_LENGTH = 64 * 1024; private static final int NUM_MESSAGES_PER_TERM = 64; private static final int MESSAGE_LENGTH = (TERM_BUFFER_LENGTH / NUM_MESSAGES_PER_TERM) - DataHeaderFlyweight.HEADER_LENGTH; private static final String ROOT_DIR = IoUtil.tmpDirName() + "aeron-system-tests-" + UUID.randomUUID().toString() + File.separator; private final MediaDriver.Context driverAContext = new MediaDriver.Context(); private final MediaDriver.Context driverBContext = new MediaDriver.Context(); private Aeron clientA; private Aeron clientB; private MediaDriver driverA; private MediaDriver driverB; private Publication publication; private Subscription subscriptionA; private Subscription subscriptionB; private UnsafeBuffer buffer = new UnsafeBuffer(new byte[MESSAGE_LENGTH]); private FragmentHandler fragmentHandlerA = mock(FragmentHandler.class); private FragmentHandler fragmentHandlerB = mock(FragmentHandler.class); private void launch() { final String baseDirA = ROOT_DIR + "A"; final String baseDirB = ROOT_DIR + "B"; buffer.putInt(0, 1); driverAContext.publicationTermBufferLength(TERM_BUFFER_LENGTH) .aeronDirectoryName(baseDirA) .errorHandler(Throwable::printStackTrace) .threadingMode(ThreadingMode.SHARED); driverBContext.publicationTermBufferLength(TERM_BUFFER_LENGTH) .aeronDirectoryName(baseDirB) .errorHandler(Throwable::printStackTrace) .threadingMode(ThreadingMode.SHARED); driverA = MediaDriver.launch(driverAContext); driverB = MediaDriver.launch(driverBContext); clientA = Aeron.connect(new Aeron.Context().aeronDirectoryName(driverAContext.aeronDirectoryName())); clientB = Aeron.connect(new Aeron.Context().aeronDirectoryName(driverBContext.aeronDirectoryName())); } @After public void after() { clientB.close(); clientA.close(); driverB.close(); driverA.close(); IoUtil.delete(new File(ROOT_DIR), true); } @Test(timeout = 10_000) public void shouldSpinUpAndShutdown() { launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } } @Test(timeout = 10_000) public void shouldTimeoutImageWhenBehindForTooLongWithMaxMulticastFlowControlStrategy() throws Exception { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; final CountDownLatch unavailableCountDownLatch = new CountDownLatch(1); final CountDownLatch availableCountDownLatch = new CountDownLatch(2); driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new MaxMulticastFlowControl()); launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription( MULTICAST_URI, STREAM_ID, (image) -> availableCountDownLatch.countDown(), (image) -> unavailableCountDownLatch.countDown()); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (int i = 0; i < numMessagesToSend; i++) { while (publication.offer(buffer, 0, buffer.capacity()) < 0L) { Thread.yield(); } // A keeps up final MutableInteger fragmentsRead = new MutableInteger(); SystemTest.executeUntil( () -> fragmentsRead.get() > 0, (j) -> { fragmentsRead.value += subscriptionA.poll(fragmentHandlerA, 10); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(500)); fragmentsRead.set(0); // B receives slowly and eventually can't keep up if (i % 10 == 0) { SystemTest.executeUntil( () -> fragmentsRead.get() > 0, (j) -> { fragmentsRead.value += subscriptionB.poll(fragmentHandlerB, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(500)); } } unavailableCountDownLatch.await(); availableCountDownLatch.await(); verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, atMost(numMessagesToSend - 1)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldSlowDownWhenBehindWithMinMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; int numFragmentsFromB = 0; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new MinMulticastFlowControl()); launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { Thread.yield(); } for (long i = 0; numFragmentsFromA < numMessagesToSend || numFragmentsFromB < numMessagesToSend; i++) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } SystemTest.checkInterruptedStatus(); Thread.yield(); // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives slowly if ((i % 2) == 0) { numFragmentsFromB += subscriptionB.poll(fragmentHandlerB, 1); } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldRemoveDeadReceiverWithMinMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; int numFragmentsFromB = 0; boolean isClosedB = false; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new MinMulticastFlowControl()); launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } while (numFragmentsFromA < numMessagesToSend) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives up to 1/8 of the messages, then stops if (numFragmentsFromB < (numMessagesToSend / 8)) { numFragmentsFromB += subscriptionB.poll(fragmentHandlerB, 10); } else if (!isClosedB) { subscriptionB.close(); isClosedB = true; } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldSlowDownToSlowPreferredWithPreferredMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; int numFragmentsFromB = 0; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new PreferredMulticastFlowControl()); driverBContext.applicationSpecificFeedback(PreferredMulticastFlowControl.PREFERRED_ASF_BYTES); launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (long i = 0; numFragmentsFromB < numMessagesToSend || numFragmentsFromA < numMessagesToSend; i++) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } SystemTest.checkInterruptedStatus(); Thread.yield(); // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives slowly if ((i % 2) == 0) { numFragmentsFromB += subscriptionB.poll(fragmentHandlerB, 1); } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldKeepUpToFastPreferredWithPreferredMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsFromA = 0; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new PreferredMulticastFlowControl()); driverAContext.applicationSpecificFeedback(PreferredMulticastFlowControl.PREFERRED_ASF_BYTES); launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } for (long i = 0; numFragmentsFromA < numMessagesToSend; i++) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } SystemTest.checkInterruptedStatus(); Thread.yield(); // A keeps up numFragmentsFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives slowly if ((i % 2) == 0) { subscriptionB.poll(fragmentHandlerB, 1); } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); verify(fragmentHandlerB, atMost(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } @Test(timeout = 10_000) public void shouldRemoveDeadPreferredReceiverWithPreferredMulticastFlowControlStrategy() { final int numMessagesToSend = NUM_MESSAGES_PER_TERM * 3; int numMessagesLeftToSend = numMessagesToSend; int numFragmentsReadFromA = 0, numFragmentsReadFromB = 0; boolean isBClosed = false; driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500)); driverAContext.multicastFlowControlSupplier( (udpChannel, streamId, registrationId) -> new PreferredMulticastFlowControl()); driverBContext.applicationSpecificFeedback(PreferredMulticastFlowControl.PREFERRED_ASF_BYTES); launch(); publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) { SystemTest.checkInterruptedStatus(); Thread.yield(); } while (numFragmentsReadFromA < numMessagesToSend) { if (numMessagesLeftToSend > 0) { if (publication.offer(buffer, 0, buffer.capacity()) >= 0L) { numMessagesLeftToSend--; } } // A keeps up numFragmentsReadFromA += subscriptionA.poll(fragmentHandlerA, 10); // B receives up to 1/8 of the messages, then stops if (numFragmentsReadFromB < (numMessagesToSend / 8)) { numFragmentsReadFromB += subscriptionB.poll(fragmentHandlerB, 10); } else if (!isBClosed) { subscriptionB.close(); isBClosed = true; } } verify(fragmentHandlerA, times(numMessagesToSend)).onFragment( any(DirectBuffer.class), anyInt(), eq(MESSAGE_LENGTH), any(Header.class)); } }
[Java] Create subscriptions before publications to speed up tests.
aeron-system-tests/src/test/java/io/aeron/FlowControlStrategiesTest.java
[Java] Create subscriptions before publications to speed up tests.
<ide><path>eron-system-tests/src/test/java/io/aeron/FlowControlStrategiesTest.java <ide> { <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <del> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <del> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> <ide> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <ide> { <ide> <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <ide> subscriptionB = clientB.addSubscription( <ide> MULTICAST_URI, <ide> STREAM_ID, <ide> (image) -> availableCountDownLatch.countDown(), <ide> (image) -> unavailableCountDownLatch.countDown()); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> <ide> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <ide> { <ide> { <ide> while (publication.offer(buffer, 0, buffer.capacity()) < 0L) <ide> { <add> SystemTest.checkInterruptedStatus(); <ide> Thread.yield(); <ide> } <ide> <ide> <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <del> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <del> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <del> <del> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <del> { <add> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <add> <add> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <add> { <add> SystemTest.checkInterruptedStatus(); <ide> Thread.yield(); <ide> } <ide> <ide> <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <del> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <del> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> <ide> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <ide> { <ide> <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <del> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <del> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> <ide> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <ide> { <ide> <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <del> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <del> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> <ide> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <ide> { <ide> <ide> launch(); <ide> <del> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <del> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <del> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionA = clientA.addSubscription(MULTICAST_URI, STREAM_ID); <add> subscriptionB = clientB.addSubscription(MULTICAST_URI, STREAM_ID); <add> publication = clientA.addPublication(MULTICAST_URI, STREAM_ID); <ide> <ide> while (!subscriptionA.isConnected() || !subscriptionB.isConnected()) <ide> {
Java
mit
c4a8eb3a27bd820ceea8ba835584a88530ea5fc9
0
binaryoverload/FlareBot,weeryan17/FlareBot,FlareBot/FlareBot
package com.bwfcwalshy.flarebot.commands.administrator; import com.bwfcwalshy.flarebot.FlareBot; import com.bwfcwalshy.flarebot.MessageUtils; import com.bwfcwalshy.flarebot.commands.Command; import com.bwfcwalshy.flarebot.commands.CommandType; import com.bwfcwalshy.flarebot.scheduler.FlarebotTask; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.RequestBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Purge implements Command { private Map<String, Long> cooldowns = new HashMap<>(); private static final long cooldown = 60000; @Override public void onCommand(IUser sender, IChannel channel, IMessage message, String[] args) { if (channel.isPrivate()) { MessageUtils.sendMessage(MessageUtils.getEmbed(sender).withDesc("Cannot purge in DMs!").build(), channel); return; } if (args.length == 1 && args[0].matches("\\d+")) { if(!FlareBot.getInstance().getPermissions(channel).hasPermission(sender, "flarebot.purge.bypass")) { long calmitdood = cooldowns.computeIfAbsent(channel.getGuild().getID(), n -> 0L); if (System.currentTimeMillis() - calmitdood < cooldown) { MessageUtils.sendMessage(MessageUtils.getEmbed(sender) .withDesc(String.format("You are on a cooldown! %s seconds left!", (cooldown - (System.currentTimeMillis() - calmitdood)) / 1000)).build(), channel); return; } } int count = Integer.parseInt(args[0]) + 1; if (count < 2 || count > 200) { MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Can't purge less than 2 messages or more than 200!").build(), channel); return; } if(!FlareBot.getInstance().getPermissions(channel).hasPermission(sender, "flarebot.purge.bypass")) cooldowns.put(channel.getGuild().getID(), System.currentTimeMillis()); RequestBuffer.request(() -> { channel.getMessages().setCacheCapacity(count); boolean loaded = true; while (loaded && channel.getMessages().size() < count) loaded = channel.getMessages().load(Math.min(count, 100)); if (loaded) { List<IMessage> list = new ArrayList<>(channel.getMessages()); List<IMessage> toDelete = new ArrayList<>(); for (IMessage msg : list) { if (toDelete.size() > 99) { bulk(toDelete, channel, sender); toDelete.clear(); } toDelete.add(msg); } bulk(toDelete, channel, sender); channel.getMessages().setCacheCapacity(0); IMessage msg = MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc(":+1: Deleted!") .appendField("Message Count: ", String.valueOf(count - 1), true).build(), channel); new FlarebotTask("Delete message " + msg.getChannel().toString() + msg.getID()) { @Override public void run() { RequestBuffer.request(() -> { try { msg.delete(); } catch (MissingPermissionsException | DiscordException ignored) { } }); } }.delay(10000); } else MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Could not load in messages!").build(), channel); }); } else { MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Bad arguments!\n" + getDescription()).build(), channel); } } private void bulk(List<IMessage> toDelete, IChannel channel, IUser sender) { RequestBuffer.request(() -> { try { channel.getMessages().bulkDelete(toDelete); } catch (DiscordException e) { FlareBot.LOGGER.error("Could not bulk delete!", e); MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Could not bulk delete! Error occured!").build(), channel); } catch (MissingPermissionsException e) { MessageUtils.sendMessage(MessageUtils.getEmbed(sender) .withDesc("I do not have the `Manage Messages` permission!").build(), channel); } }); } @Override public String getCommand() { return "purge"; } @Override public String getDescription() { return "Removes last X messages. Usage: `purge MESSAGES`"; } @Override public CommandType getType() { return CommandType.ADMINISTRATIVE; } @Override public String getPermission() { return "flarebot.purge"; } @Override public String[] getAliases() { return new String[]{"clean"}; } }
src/main/java/com/bwfcwalshy/flarebot/commands/administrator/Purge.java
package com.bwfcwalshy.flarebot.commands.administrator; import com.bwfcwalshy.flarebot.FlareBot; import com.bwfcwalshy.flarebot.MessageUtils; import com.bwfcwalshy.flarebot.commands.Command; import com.bwfcwalshy.flarebot.commands.CommandType; import com.bwfcwalshy.flarebot.scheduler.FlarebotTask; import sx.blah.discord.handle.obj.IChannel; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.handle.obj.IUser; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.MissingPermissionsException; import sx.blah.discord.util.RequestBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Purge implements Command { private Map<String, Long> cooldowns = new HashMap<>(); private static final long cooldown = 60000; @Override public void onCommand(IUser sender, IChannel channel, IMessage message, String[] args) { if (channel.isPrivate()) { MessageUtils.sendMessage(MessageUtils.getEmbed(sender).withDesc("Cannot purge in DMs!").build(), channel); return; } if (args.length == 1 && args[0].matches("\\d+")) { if(!FlareBot.getInstance().getPermissions(channel).hasPermission(sender, "flarebot.purge.bypass")) { long calmitdood = cooldowns.computeIfAbsent(channel.getGuild().getID(), n -> 0L); if (System.currentTimeMillis() - calmitdood < cooldown) { MessageUtils.sendMessage(MessageUtils.getEmbed(sender) .withDesc(String.format("You are on a cooldown! %s seconds left!", (cooldown - (System.currentTimeMillis() - calmitdood)) / 1000)).build(), channel); return; } } int count = Integer.parseInt(args[0]) + 1; if (count < 2 || count > 200) { MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Can't purge less than 2 messages or more than 200!").build(), channel); return; } cooldowns.put(channel.getGuild().getID(), System.currentTimeMillis()); RequestBuffer.request(() -> { channel.getMessages().setCacheCapacity(count); boolean loaded = true; while (loaded && channel.getMessages().size() < count) loaded = channel.getMessages().load(Math.min(count, 100)); if (loaded) { List<IMessage> list = new ArrayList<>(channel.getMessages()); List<IMessage> toDelete = new ArrayList<>(); for (IMessage msg : list) { if (toDelete.size() > 99) { bulk(toDelete, channel, sender); toDelete.clear(); } toDelete.add(msg); } bulk(toDelete, channel, sender); channel.getMessages().setCacheCapacity(0); IMessage msg = MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc(":+1: Deleted!") .appendField("Message Count: ", String.valueOf(count - 1), true).build(), channel); new FlarebotTask("Delete message " + msg.getChannel().toString() + msg.getID()) { @Override public void run() { RequestBuffer.request(() -> { try { msg.delete(); } catch (MissingPermissionsException | DiscordException ignored) { } }); } }.delay(10000); } else MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Could not load in messages!").build(), channel); }); } else { MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Bad arguments!\n" + getDescription()).build(), channel); } } private void bulk(List<IMessage> toDelete, IChannel channel, IUser sender) { RequestBuffer.request(() -> { try { channel.getMessages().bulkDelete(toDelete); } catch (DiscordException e) { FlareBot.LOGGER.error("Could not bulk delete!", e); MessageUtils.sendMessage(MessageUtils .getEmbed(sender).withDesc("Could not bulk delete! Error occured!").build(), channel); } catch (MissingPermissionsException e) { MessageUtils.sendMessage(MessageUtils.getEmbed(sender) .withDesc("I do not have the `Manage Messages` permission!").build(), channel); } }); } @Override public String getCommand() { return "purge"; } @Override public String getDescription() { return "Removes last X messages. Usage: `purge MESSAGES`"; } @Override public CommandType getType() { return CommandType.ADMINISTRATIVE; } @Override public String getPermission() { return "flarebot.purge"; } @Override public String[] getAliases() { return new String[]{"clean"}; } }
* Tiny improvement to cooldown bypass
src/main/java/com/bwfcwalshy/flarebot/commands/administrator/Purge.java
* Tiny improvement to cooldown bypass
<ide><path>rc/main/java/com/bwfcwalshy/flarebot/commands/administrator/Purge.java <ide> .getEmbed(sender).withDesc("Can't purge less than 2 messages or more than 200!").build(), channel); <ide> return; <ide> } <del> cooldowns.put(channel.getGuild().getID(), System.currentTimeMillis()); <add> if(!FlareBot.getInstance().getPermissions(channel).hasPermission(sender, "flarebot.purge.bypass")) <add> cooldowns.put(channel.getGuild().getID(), System.currentTimeMillis()); <ide> RequestBuffer.request(() -> { <ide> channel.getMessages().setCacheCapacity(count); <ide> boolean loaded = true;
Java
mit
b5dd04086929e90ec5397316223b5e577a85c703
0
RudiaMoon/objectify-appengine,google-code-export/objectify-appengine,naveen514/objectify-appengine,objectify/objectify,asolfre/objectify-appengine,qickrooms/objectify-appengine,zenmeso/objectify-appengine,gvaish/objectify-appengine,gvaish/attic-objectify-appengine
package com.googlecode.objectify; import java.util.HashMap; import java.util.Map; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Transaction; /** * <p>This is the underlying implementation of the ObjectifyFactory static methods, available * as a singleton. If you wish to override factory behavior, you can inject a subclass of * this object in your code. You can also make calls to these methods by calling * {@code ObjectifyFact.instance().begin()} etc if you think static methods are fugly.</p> * * <p>In general, however, you probably want to use the ObjectifyFactory methods.</p> * * <p>Note that all method documentation is on ObjectifyFactory.</p> * * @see ObjectifyFactory * * @author Jeff Schnitzer <[email protected]> */ public class Factory { /** */ protected static Factory instance = new Factory(); /** Obtain the singleton as an alternative to using the static methods */ public static Factory instance() { return instance; } /** */ protected Map<String, EntityMetadata> types = new HashMap<String, EntityMetadata>(); /** @see ObjectifyFactory#begin() */ public Objectify begin() { return new ObjectifyImpl(this, DatastoreServiceFactory.getDatastoreService(), null); } /** @see ObjectifyFactory#beginTransaction() */ public Objectify beginTransaction() { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); return new ObjectifyImpl(this, ds, ds.beginTransaction()); } /** @see ObjectifyFactory#withTransaction(Transaction) */ public Objectify withTransaction(Transaction txn) { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); return new ObjectifyImpl(this, ds, txn); } /** @see ObjectifyFactory#register(Class) */ public void register(Class<?> clazz) { String kind = getKind(clazz); this.types.put(kind, new EntityMetadata(clazz)); } // // Methods equivalent to those on KeyFactory, but which use typed Classes instead of kind. // /** @see ObjectifyFactory#createKey(Class, long) */ public Key createKey(Class<?> kind, long id) { return KeyFactory.createKey(getKind(kind), id); } /** @see ObjectifyFactory#createKey(Class, String) */ public Key createKey(Class<?> kind, String name) { return KeyFactory.createKey(getKind(kind), name); } /** @see ObjectifyFactory#createKey(Key, Class, long) */ public Key createKey(Key parent, Class<?> kind, long id) { return KeyFactory.createKey(parent, getKind(kind), id); } /** @see ObjectifyFactory#createKey(Key, Class, String) */ public Key createKey(Key parent, Class<?> kind, String name) { return KeyFactory.createKey(parent, getKind(kind), name); } /** @see ObjectifyFactory#createKey(Object) */ public Key createKey(Object entity) { return getMetadata(entity).getKey(entity); } // // Friendly query creation methods // /** @see ObjectifyFactory#createQuery() */ public Query createQuery() { return new Query(); } /** @see ObjectifyFactory#createQuery(Class) */ public Query createQuery(Class<?> entityClazz) { return new Query(getKind(entityClazz)); } // // Stuff which should only be necessary internally. // /** @see ObjectifyFactory#getKind(Class) */ public String getKind(Class<?> clazz) { javax.persistence.Entity entityAnn = clazz.getAnnotation(javax.persistence.Entity.class); if (entityAnn == null || entityAnn.name() == null) return clazz.getSimpleName(); else return entityAnn.name(); } /** @see ObjectifyFactory#getMetadata(Key) */ public EntityMetadata getMetadata(Key key) { EntityMetadata metadata = types.get(key.getKind()); if (metadata == null) throw new IllegalArgumentException("No registered type for kind " + key.getKind()); else return metadata; } /** @see ObjectifyFactory#getMetadata(Object) */ public EntityMetadata getMetadata(Object obj) { EntityMetadata metadata = types.get(getKind(obj.getClass())); if (metadata == null) throw new IllegalArgumentException("No registered type for kind " + getKind(obj.getClass())); else return metadata; } }
src/com/googlecode/objectify/Factory.java
package com.googlecode.objectify; import java.util.HashMap; import java.util.Map; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Transaction; /** * <p>This is the underlying implementation of the ObjectifyFactory static methods, available * as a singleton. If you wish to override factory behavior, you can inject a subclass of * this object in your code. You can also make calls to these methods by calling * {@code ObjectifyFact.instance().begin()} etc if you think static methods are fugly.</p> * * <p>In general, however, you probably want to use the ObjectifyFactory methods.</p> * * <p>Note that all method documentation is on ObjectifyFactory.</p> * * @see ObjectifyFactory * * @author Jeff Schnitzer <[email protected]> */ public class Factory { /** */ protected static Factory instance = new Factory(); /** Obtain the singleton as an alternative to using the static methods */ public static Factory instance() { return instance; } /** */ protected Map<String, EntityMetadata> types = new HashMap<String, EntityMetadata>(); /** @see ObjectifyFactory#begin() */ public Objectify begin() { return new ObjectifyImpl(this, DatastoreServiceFactory.getDatastoreService(), null); } /** @see ObjectifyFactory#beginTransaction() */ public Objectify beginTransaction() { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); return new ObjectifyImpl(this, ds, ds.beginTransaction()); } /** @see ObjectifyFactory#withTransaction(Transaction) */ public Objectify withTransaction(Transaction txn) { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); return new ObjectifyImpl(this, ds, txn); } /** @see ObjectifyFactory#register(Class) */ public void register(Class<?> clazz) { String kind = getKind(clazz); this.types.put(kind, new EntityMetadata(clazz)); } // // Methods equivalent to those on KeyFactory, but which use typed Classes instead of kind. // /** @see ObjectifyFactory#createKey(Class, long) */ public Key createKey(Class<?> kind, long id) { return KeyFactory.createKey(getKind(kind), id); } /** @see ObjectifyFactory#createKey(Class, String) */ public Key createKey(Class<?> kind, String name) { return KeyFactory.createKey(getKind(kind), name); } /** @see ObjectifyFactory#createKey(Key, Class, long) */ public Key createKey(Key parent, Class<?> kind, long id) { return KeyFactory.createKey(parent, getKind(kind), id); } /** @see ObjectifyFactory#createKey(Key, Class, String) */ public Key createKey(Key parent, Class<?> kind, String name) { return KeyFactory.createKey(parent, getKind(kind), name); } /** @see ObjectifyFactory#createKey(Object) */ public Key createKey(Object entity) { return getMetadata(entity).getKey(entity); } // // Friendly query creation methods // /** @see ObjectifyFactory#createQuery() */ public Query createQuery() { return new Query(); } /** @see ObjectifyFactory#createQuery(Class) */ public Query createQuery(Class<?> entityClazz) { return new Query(getKind(entityClazz)); } // // Stuff which should only be necessary internally. // /** @see ObjectifyFactory#getKind(Class) */ public String getKind(Class<?> clazz) { javax.persistence.Entity entityAnn = clazz.getAnnotation(javax.persistence.Entity.class); if (entityAnn == null) return clazz.getSimpleName(); else return entityAnn.name(); } /** @see ObjectifyFactory#getMetadata(Key) */ public EntityMetadata getMetadata(Key key) { EntityMetadata metadata = types.get(key.getKind()); if (metadata == null) throw new IllegalArgumentException("No registered type for kind " + key.getKind()); else return metadata; } /** @see ObjectifyFactory#getMetadata(Object) */ public EntityMetadata getMetadata(Object obj) { EntityMetadata metadata = types.get(getKind(obj.getClass())); if (metadata == null) throw new IllegalArgumentException("No registered type for kind " + getKind(obj.getClass())); else return metadata; } }
Fixed bug causing un-named @Entity objects to not have kinds. git-svn-id: 1ab7df0ed85a7513fd7b1f64d2838346d91c60ce@23 79e2b5ea-dad9-11de-b64b-7d26b27941e2
src/com/googlecode/objectify/Factory.java
Fixed bug causing un-named @Entity objects to not have kinds.
<ide><path>rc/com/googlecode/objectify/Factory.java <ide> public String getKind(Class<?> clazz) <ide> { <ide> javax.persistence.Entity entityAnn = clazz.getAnnotation(javax.persistence.Entity.class); <del> if (entityAnn == null) <add> if (entityAnn == null || entityAnn.name() == null) <ide> return clazz.getSimpleName(); <ide> else <ide> return entityAnn.name();
Java
apache-2.0
95fceeb27e0ffef84becddbe88ce10cfe8fa205f
0
weimingtom/python-for-android,pforret/python-for-android,yawnosnorous/python-for-android,pleaseproject/python-for-android,flyfei/python-for-android,kemalakyol48/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,zhuwenping/python-for-android,RockySteveJobs/python-for-android,Godiyos/python-for-android,bonitadecker77/python-for-android,kuri65536/python-for-android,zhouzhenghui/python-for-android,BackupGGCode/python-for-android,lokirius/python-for-android,nikhilprathapani/python-for-android,zhuwenping/python-for-android,MrLoick/python-for-android,imsparsh/python-for-android,Immortalin/python-for-android,pforret/python-for-android,bonitadecker77/python-for-android,invisiblek/python-for-android,kanagasabapathi/python-for-android,unseenlaser/python-for-android,dya2/python-for-android,xxsergzzxx/python-for-android,BackupGGCode/python-for-android,ybellavance/python-for-android,invisiblek/python-for-android,louietsai/python-for-android,RO-ny9/python-for-android,bhargav2408/python-for-android,louietsai/python-for-android,jcoady9/python-for-android,BeATz-UnKNoWN/python-for-android,andreparrish/python-for-android,meabsence/python-for-android,imsparsh/python-for-android,flyfei/python-for-android,MattsFleaMarket/python-for-android,nikhilprathapani/python-for-android,MrLoick/python-for-android,MattsFleaMarket/python-for-android,Big-B702/python-for-android,weimingtom/python-for-android,meabsence/python-for-android,denisff/python-for-android,Salat-Cx65/python-for-android,glwu/python-for-android,bhargav2408/python-for-android,sinkuri256/python-for-android,BackupGGCode/python-for-android,lokirius/python-for-android,unseenlaser/python-for-android,kemalakyol48/python-for-android,837468220/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,RO-ny9/python-for-android,miguelpalacio/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,dya2/python-for-android,kanagasabapathi/python-for-android,weimingtom/python-for-android,miguelpalacio/python-for-android,kanagasabapathi/python-for-android,MattsFleaMarket/python-for-android,jcoady9/python-for-android,yawnosnorous/python-for-android,weimingtom/python-for-android,kmonsoor/python-for-android,Zord13appdesa/python-for-android,kmonsoor/python-for-android,denisff/python-for-android,andreparrish/python-for-android,pleaseproject/python-for-android,glwu/python-for-android,RockySteveJobs/python-for-android,unseenlaser/python-for-android,kuri65536/python-for-android,miguelpalacio/python-for-android,Big-B702/python-for-android,flyfei/python-for-android,kemalakyol48/python-for-android,Krossom/python-for-android,jcoady9/python-for-android,unseenlaser/python-for-android,meabsence/python-for-android,louietsai/python-for-android,kemalakyol48/python-for-android,invisiblek/python-for-android,Immortalin/python-for-android,MrLoick/python-for-android,zhouzhenghui/python-for-android,MrLoick/python-for-android,kmonsoor/python-for-android,ybellavance/python-for-android,unseenlaser/python-for-android,yawnosnorous/python-for-android,jcoady9/python-for-android,RO-ny9/python-for-android,Godiyos/python-for-android,bonitadecker77/python-for-android,nikhilprathapani/python-for-android,pleaseproject/python-for-android,kemalakyol48/python-for-android,weimingtom/python-for-android,flyfei/python-for-android,RockySteveJobs/python-for-android,kanagasabapathi/python-for-android,yawnosnorous/python-for-android,imsparsh/python-for-android,pleaseproject/python-for-android,837468220/python-for-android,bhargav2408/python-for-android,MrLoick/python-for-android,Immortalin/python-for-android,flyfei/python-for-android,louietsai/python-for-android,flyfei/python-for-android,MattsFleaMarket/python-for-android,ybellavance/python-for-android,unseenlaser/python-for-android,lokirius/python-for-android,MattsFleaMarket/python-for-android,pforret/python-for-android,kanagasabapathi/python-for-android,pleaseproject/python-for-android,Godiyos/python-for-android,denisff/python-for-android,c0defreak/python-for-android,Zord13appdesa/python-for-android,andreparrish/python-for-android,BackupGGCode/python-for-android,837468220/python-for-android,meabsence/python-for-android,RockySteveJobs/python-for-android,kmonsoor/python-for-android,meabsence/python-for-android,Krossom/python-for-android,zhuwenping/python-for-android,Krossom/python-for-android,Big-B702/python-for-android,Salat-Cx65/python-for-android,837468220/python-for-android,RO-ny9/python-for-android,Zord13appdesa/python-for-android,Krossom/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,bonitadecker77/python-for-android,ybellavance/python-for-android,dya2/python-for-android,BackupGGCode/python-for-android,unseenlaser/python-for-android,pforret/python-for-android,Big-B702/python-for-android,Zord13appdesa/python-for-android,imsparsh/python-for-android,Krossom/python-for-android,louietsai/python-for-android,dya2/python-for-android,Immortalin/python-for-android,glwu/python-for-android,flyfei/python-for-android,837468220/python-for-android,ybellavance/python-for-android,lokirius/python-for-android,bhargav2408/python-for-android,louietsai/python-for-android,andreparrish/python-for-android,dya2/python-for-android,xxsergzzxx/python-for-android,louietsai/python-for-android,denisff/python-for-android,c0defreak/python-for-android,louietsai/python-for-android,kemalakyol48/python-for-android,dya2/python-for-android,kmonsoor/python-for-android,zhuwenping/python-for-android,nikhilprathapani/python-for-android,bonitadecker77/python-for-android,BeATz-UnKNoWN/python-for-android,lokirius/python-for-android,kanagasabapathi/python-for-android,lokirius/python-for-android,yawnosnorous/python-for-android,Salat-Cx65/python-for-android,MrLoick/python-for-android,sinkuri256/python-for-android,denisff/python-for-android,ybellavance/python-for-android,c0defreak/python-for-android,zhuwenping/python-for-android,imsparsh/python-for-android,weimingtom/python-for-android,pleaseproject/python-for-android,andreparrish/python-for-android,Big-B702/python-for-android,meabsence/python-for-android,837468220/python-for-android,invisiblek/python-for-android,Big-B702/python-for-android,invisiblek/python-for-android,MattsFleaMarket/python-for-android,imsparsh/python-for-android,zhuwenping/python-for-android,BeATz-UnKNoWN/python-for-android,weimingtom/python-for-android,c0defreak/python-for-android,sinkuri256/python-for-android,zhuwenping/python-for-android,meabsence/python-for-android,xxsergzzxx/python-for-android,xxsergzzxx/python-for-android,MrLoick/python-for-android,bonitadecker77/python-for-android,sinkuri256/python-for-android,zhouzhenghui/python-for-android,lokirius/python-for-android,kuri65536/python-for-android,Immortalin/python-for-android,bhargav2408/python-for-android,Godiyos/python-for-android,zhouzhenghui/python-for-android,ybellavance/python-for-android,RockySteveJobs/python-for-android,invisiblek/python-for-android,dya2/python-for-android,pleaseproject/python-for-android,MrLoick/python-for-android,Salat-Cx65/python-for-android,Godiyos/python-for-android,jcoady9/python-for-android,zhouzhenghui/python-for-android,andreparrish/python-for-android,flyfei/python-for-android,MattsFleaMarket/python-for-android,RockySteveJobs/python-for-android,nikhilprathapani/python-for-android,RockySteveJobs/python-for-android,denisff/python-for-android,zhuwenping/python-for-android,flyfei/python-for-android,MrLoick/python-for-android,bonitadecker77/python-for-android,dya2/python-for-android,Salat-Cx65/python-for-android,zhuwenping/python-for-android,meabsence/python-for-android,glwu/python-for-android,Zord13appdesa/python-for-android,RockySteveJobs/python-for-android,jcoady9/python-for-android,kmonsoor/python-for-android,yawnosnorous/python-for-android,Krossom/python-for-android,zhouzhenghui/python-for-android,Krossom/python-for-android,kemalakyol48/python-for-android,xxsergzzxx/python-for-android,lokirius/python-for-android,pleaseproject/python-for-android,837468220/python-for-android,glwu/python-for-android,miguelpalacio/python-for-android,unseenlaser/python-for-android,pforret/python-for-android,BeATz-UnKNoWN/python-for-android,MattsFleaMarket/python-for-android,nikhilprathapani/python-for-android,miguelpalacio/python-for-android,Immortalin/python-for-android,Godiyos/python-for-android,bonitadecker77/python-for-android,xxsergzzxx/python-for-android,RO-ny9/python-for-android,imsparsh/python-for-android,c0defreak/python-for-android,lokirius/python-for-android,837468220/python-for-android,denisff/python-for-android,yawnosnorous/python-for-android,pleaseproject/python-for-android,andreparrish/python-for-android,bhargav2408/python-for-android,RockySteveJobs/python-for-android,RO-ny9/python-for-android,Immortalin/python-for-android,glwu/python-for-android,Immortalin/python-for-android,Zord13appdesa/python-for-android,jcoady9/python-for-android,Godiyos/python-for-android,bonitadecker77/python-for-android,BeATz-UnKNoWN/python-for-android,BackupGGCode/python-for-android,nikhilprathapani/python-for-android,miguelpalacio/python-for-android,kmonsoor/python-for-android,kmonsoor/python-for-android,miguelpalacio/python-for-android,xxsergzzxx/python-for-android,Zord13appdesa/python-for-android,glwu/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,sinkuri256/python-for-android,nikhilprathapani/python-for-android,837468220/python-for-android,invisiblek/python-for-android,glwu/python-for-android,glwu/python-for-android,Immortalin/python-for-android,xxsergzzxx/python-for-android,Godiyos/python-for-android,invisiblek/python-for-android,xxsergzzxx/python-for-android,invisiblek/python-for-android,kemalakyol48/python-for-android,Salat-Cx65/python-for-android,weimingtom/python-for-android,jcoady9/python-for-android,jcoady9/python-for-android,kuri65536/python-for-android,RO-ny9/python-for-android,BackupGGCode/python-for-android,Big-B702/python-for-android,denisff/python-for-android,Immortalin/python-for-android,Godiyos/python-for-android,louietsai/python-for-android,BeATz-UnKNoWN/python-for-android,Salat-Cx65/python-for-android,Krossom/python-for-android,invisiblek/python-for-android,Salat-Cx65/python-for-android,Zord13appdesa/python-for-android,bhargav2408/python-for-android,yawnosnorous/python-for-android,andreparrish/python-for-android,BackupGGCode/python-for-android,meabsence/python-for-android,ybellavance/python-for-android,Krossom/python-for-android,BackupGGCode/python-for-android,kanagasabapathi/python-for-android,lokirius/python-for-android,nikhilprathapani/python-for-android,pforret/python-for-android,BeATz-UnKNoWN/python-for-android,Zord13appdesa/python-for-android,zhouzhenghui/python-for-android,sinkuri256/python-for-android,kuri65536/python-for-android,nikhilprathapani/python-for-android,BeATz-UnKNoWN/python-for-android,unseenlaser/python-for-android,dya2/python-for-android,c0defreak/python-for-android,jcoady9/python-for-android,c0defreak/python-for-android,BeATz-UnKNoWN/python-for-android,andreparrish/python-for-android,837468220/python-for-android,MattsFleaMarket/python-for-android,zhouzhenghui/python-for-android,weimingtom/python-for-android,denisff/python-for-android,imsparsh/python-for-android,glwu/python-for-android,pleaseproject/python-for-android,xxsergzzxx/python-for-android,ybellavance/python-for-android,RO-ny9/python-for-android,yawnosnorous/python-for-android,kuri65536/python-for-android,kanagasabapathi/python-for-android,ybellavance/python-for-android,Krossom/python-for-android,bhargav2408/python-for-android,sinkuri256/python-for-android,Salat-Cx65/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,andreparrish/python-for-android,Salat-Cx65/python-for-android,kanagasabapathi/python-for-android,Zord13appdesa/python-for-android,Godiyos/python-for-android,BackupGGCode/python-for-android,imsparsh/python-for-android,RockySteveJobs/python-for-android,meabsence/python-for-android,zhouzhenghui/python-for-android,yawnosnorous/python-for-android,MrLoick/python-for-android,kmonsoor/python-for-android,sinkuri256/python-for-android,MattsFleaMarket/python-for-android,denisff/python-for-android,imsparsh/python-for-android,BeATz-UnKNoWN/python-for-android,weimingtom/python-for-android,bhargav2408/python-for-android,c0defreak/python-for-android,Big-B702/python-for-android,pforret/python-for-android,RO-ny9/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,Big-B702/python-for-android,dya2/python-for-android,sinkuri256/python-for-android,RO-ny9/python-for-android,zhuwenping/python-for-android,kemalakyol48/python-for-android,Big-B702/python-for-android,unseenlaser/python-for-android,c0defreak/python-for-android,bhargav2408/python-for-android,flyfei/python-for-android,kmonsoor/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,kanagasabapathi/python-for-android,sinkuri256/python-for-android,rockyzhang/zhangyanhit-python-for-android-mips,bonitadecker77/python-for-android
package com.googlecode.pythonforandroid; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.Window; import android.widget.Button; import android.widget.Toast; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.FileUtils; import com.googlecode.android_scripting.InterpreterInstaller; import com.googlecode.android_scripting.InterpreterUninstaller; import com.googlecode.android_scripting.Log; import com.googlecode.android_scripting.activity.Main; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; import com.googlecode.android_scripting.interpreter.InterpreterUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Python Installer. Incorporates module installer. * * The module installer reads a zip file previously downloaded into "download", and unpacks it. If * the module contains shared libraries (*.so) then the module is unpacked into data, other installs * in extras. * * Typically, these will be /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6 * and /sdcard/com.googlecode.pythonforandroid/extras respectively. * * Egg files are just copied into * /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6 * * @author Damon * @author Robbie Matthews ([email protected]) * @author Manuel Naranjo ([email protected]) */ // TODO:(Robbie) The whole Import Module is more of a proof of concept than a fully realised // process. Needs some means of checking that these are properly formatted zip files, and probably a // means of uninstalling as well. Import handling could well be a separate activity, too. public class PythonMain extends Main { Button mButtonInstallScripts; Button mButtonInstallModules; Button mButtonUninstallModule; File mDownloads; private Dialog mDialog; protected String mModule; private CharSequence[] mList; private ProgressDialog mProgress; private boolean mPromptResult; private static enum MenuId { BROWSER, SL4A; public int getId() { return ordinal() + Menu.FIRST; } } private String readFirstLine(File target) { BufferedReader in; String result; try { in = new BufferedReader(new FileReader(target)); result = in.readLine(); if (result == null) { result = ""; } in.close(); } catch (Exception e) { e.printStackTrace(); result = ""; } return result; } final Handler mModuleHandler = new Handler() { @Override public void handleMessage(Message message) { Bundle bundle = message.getData(); boolean running = bundle.getBoolean("running"); if (running) { if (bundle.containsKey("max")) { mProgress.setProgress(0); mProgress.setMax(bundle.getInt("max")); } else if (bundle.containsKey("pos")) { mProgress.setProgress(bundle.getInt("pos")); } else if (bundle.containsKey("message")) { mProgress.setMessage(bundle.getString("message")); } else { mProgress.incrementProgressBy(1); } } else { mProgress.dismiss(); String info = message.getData().getString("info"); if (info != null) { showMessage("Import Module", info); } } } }; private Button mButtonBrowse; private File mFrom; private File mSoPath; private File mPythonPath; private File mEggPath; private PythonDescriptor mDescriptor; private int getInstalledVersion(String key) { SharedPreferences storage = getSharedPreferences("python-installer", 0); return storage.getInt(key, -1); } @Override protected InterpreterDescriptor getDescriptor() { mDescriptor = new PythonDescriptor(); return mDescriptor; } @Override protected InterpreterInstaller getInterpreterInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PythonInstaller(descriptor, context, listener); } @Override protected InterpreterUninstaller getInterpreterUninstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PythonUninstaller(descriptor, context, listener); } @Override protected void onResume() { String s; super.onResume(); Intent intent = getIntent(); if (intent.getData() != null) { s = intent.getData().getPath(); Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); File file = new File(intent.getData().getPath()); if (file.exists()) { performImport(file, file.getName()); } } } @Override protected void initializeViews() { super.initializeViews(); mButton.setVisibility(View.GONE); mDownloads = FileUtils.getExternalDownload(); if (!mDownloads.exists()) { for (File file : new File(Environment.getExternalStorageDirectory().getAbsolutePath()) .listFiles()) { if (file.isDirectory()) { if (file.getName().toLowerCase().startsWith("download")) { mDownloads = file; break; } } } } MarginLayoutParams marginParams = new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); final float scale = getResources().getDisplayMetrics().density; int marginPixels = (int) (MARGIN_DIP * scale + 0.5f); marginParams.setMargins(marginPixels, marginPixels, marginPixels, marginPixels); mButtonInstallScripts = new Button(this); mButtonInstallScripts.setLayoutParams(marginParams); mButtonInstallScripts.setText("Install Example Scripts"); mLayout.addView(mButtonInstallScripts); mButtonInstallScripts.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mCurrentTask != null) { return; } getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); mCurrentTask = RunningTask.INSTALL; InterpreterInstaller installTask; try { installTask = getInterpreterInstaller(mDescriptor, PythonMain.this, mTaskListener); } catch (Sl4aException e) { Log.e(PythonMain.this, e.getMessage(), e); return; } installTask.execute(); } }); mButtonInstallModules = new Button(this); mButtonInstallModules.setLayoutParams(marginParams); mButtonInstallModules.setText("Import Modules"); mLayout.addView(mButtonInstallModules); mButtonInstallModules.setOnClickListener(new OnClickListener() { public void onClick(View v) { doImportModule(); } }); mButtonBrowse = new Button(this); mButtonBrowse.setLayoutParams(marginParams); mButtonBrowse.setText("Browse Modules"); mLayout.addView(mButtonBrowse); mButtonBrowse.setOnClickListener(new OnClickListener() { public void onClick(View v) { doBrowseModule(); } }); mButtonUninstallModule = new Button(this); mButtonUninstallModule.setLayoutParams(marginParams); mButtonUninstallModule.setText("Uninstall Module"); mLayout.addView(mButtonUninstallModule); mButtonUninstallModule.setOnClickListener(new OnClickListener() { public void onClick(View v) { doDeleteModule(); } }); } @Override protected boolean checkInstalled() { broadcastInstallationStateChange(true); return true; } protected void doBrowseModule() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/python-for-android/wiki/Modules")); startActivity(intent); } public void doImportModule() { AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialog.dismiss(); if (which == DialogInterface.BUTTON_NEUTRAL) { showMessage("Import Module", "This will take a previously downloaded (and appropriately formatted) " + "python external module zip or egg file.\nSee sl4a wiki for more defails.\n" + "Looking for files in \n" + mDownloads); } } }; List<String> flist = new Vector<String>(); for (File f : mDownloads.listFiles()) { if (f.getName().endsWith(".zip") || f.getName().endsWith(".egg")) { flist.add(f.getName()); } } builder.setTitle("Import Module"); mList = flist.toArray(new CharSequence[flist.size()]); builder.setItems(mList, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mModule = (String) mList[which]; performImport(mModule); mDialog.dismiss(); } }); builder.setNegativeButton("Cancel", buttonListener); builder.setNeutralButton("Help", buttonListener); mModule = null; mDialog = builder.show(); if (mModule != null) { } } public void doDeleteModule() { mEggPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/egg-info"); AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialog.dismiss(); if (which == DialogInterface.BUTTON_NEUTRAL) { showMessage("Uninstall Module", "This will let you delete a module you got installed from an egg file"); } } }; List<String> flist = new Vector<String>(); for (File f : mEggPath.listFiles()) { if (f.getName().endsWith(".egg")) { flist.add(f.getName().replace(".egg", "")); } } builder.setTitle("Installed Modules"); mList = flist.toArray(new CharSequence[flist.size()]); builder.setItems(mList, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mModule = (String) mList[which]; performUninstall(mModule); mDialog.dismiss(); } }); builder.setNegativeButton("Cancel", buttonListener); builder.setNeutralButton("Help", buttonListener); mModule = null; mDialog = builder.show(); if (mModule != null) { } } protected void performImport(String module) { performImport(new File(mDownloads, mModule), module); } protected void performImport(File sourceFile, String module) { mModule = module; mFrom = sourceFile; mSoPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/lib/python2.6/lib-dynload"); mEggPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/egg-info"); mPythonPath = new File(mDescriptor.getEnvironmentVariables(this).get("PY4A_EXTRAS"), "python"); prompt("Install module " + module, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { if (mModule.toLowerCase().endsWith(".egg")) { copy(new File(mSoPath, mModule), mFrom); try { File out = new File(InterpreterUtils.getInterpreterRoot(PythonMain.this), "lib/python2.6/site-packages/" + mModule + ".pth"); FileOutputStream fout = new FileOutputStream(out); fout.write(new File(mSoPath, mModule).getAbsolutePath().getBytes()); fout.close(); FileUtils.chmod(out, 0755); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { extract("Extracting " + mModule, mFrom, mPythonPath, mSoPath, mEggPath); } } } }); } protected void performUninstall(String module) { mModule = module; mEggPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/egg-info"); mFrom = new File(mEggPath, module + ".egg"); mSoPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/lib/python2.6/lib-dynload"); mPythonPath = new File(mDescriptor.getEnvironmentVariables(this).get("PY4A_EXTRAS")); prompt("Uninstall module " + module, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { remove("Deleting " + mModule, mFrom, mPythonPath, mSoPath, mEggPath); } } }); } protected void extract(String caption, File from, File pypath, File sopath, File egginfo) { mProgress = showProgress(caption); Thread t = new RunExtract(caption, from, pypath, sopath, mModuleHandler, egginfo); t.start(); } protected void copy(File target, File from) { try { InputStream input = new BufferedInputStream(new FileInputStream(from)); target.getParentFile().mkdirs(); OutputStream output = new BufferedOutputStream(new FileOutputStream(target)); byte[] buf = new byte[1024]; int len; while ((len = input.read(buf)) > 0) { output.write(buf, 0, len); } output.close(); input.close(); FileUtils.recursiveChmod(target.getParentFile(), 0777); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void remove(String caption, File from, File pypath, File sopath, File egginfo) { mProgress = showProgress(caption); Thread t = new RunDelete(caption, from, pypath, sopath, mModuleHandler, egginfo); t.start(); } protected ProgressDialog showProgress(String caption) { ProgressDialog b = new ProgressDialog(this); b.setTitle(caption); b.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); b.show(); return b; } protected void showMessage(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(message); builder.setNeutralButton("OK", null); builder.show(); } protected boolean prompt(String message, DialogInterface.OnClickListener btnlisten) { mPromptResult = false; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Python Installer"); builder.setMessage(message); builder.setNegativeButton("Cancel", btnlisten); builder.setPositiveButton("OK", btnlisten); builder.show(); return mPromptResult; } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MenuId.BROWSER.getId(), Menu.NONE, "File Browser").setIcon( android.R.drawable.ic_menu_myplaces); menu.add(Menu.NONE, MenuId.SL4A.getId(), Menu.NONE, "SL4A").setIcon(R.drawable.sl4a_logo_32); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; int id = item.getItemId(); if (MenuId.BROWSER.getId() == id) { intent = new Intent(this, FileBrowser.class); intent.setAction(PythonConstants.ACTION_FILE_BROWSER); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else if (MenuId.SL4A.getId() == id) { intent = new Intent(); intent.setComponent(new ComponentName(PythonConstants.SL4A, PythonConstants.SL4A_MANAGER)); try { startActivity(intent); } catch (Exception e) { showMessage("Py4A", "SL4A may not be installed."); } } return true; } class RunExtract extends Thread { String caption; File from; File sopath; File pypath; File egginfo; Handler mHandler; RunExtract(String caption, File from, File pypath, File sopath, Handler h, File egginfo) { this.caption = caption; this.from = from; this.pypath = pypath; this.sopath = sopath; this.egginfo = egginfo; mHandler = h; } @Override public void run() { byte[] buf = new byte[4096]; boolean isInfo = false; List<ZipEntry> list = new ArrayList<ZipEntry>(); Vector<String> installed = new Vector<String>(); boolean hasSo = false; try { ZipFile zipfile = new ZipFile(from); int cnt = 0; sendmsg(true, "max", zipfile.size()); Enumeration<? extends ZipEntry> entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry ex = entries.nextElement(); if (ex.getName().endsWith(".so")) { hasSo = true; } list.add(ex); } for (ZipEntry entry : list) { cnt += 1; if (entry.isDirectory()) { continue; } File destinationPath; File destinationFile; isInfo = entry.getName().contains("EGG-INFO"); if (isInfo) { destinationPath = new File(egginfo, from.getName()); destinationFile = new File(destinationPath, entry.getName().split("/", 2)[1]); } else { // destinationPath = entry.getName().endsWith(".so") ? sopath : pypath; // Python does not cope well with splitting *.so and normal files. Sadly. // At the moment, if we have an *.so, we will copy entire library to main memory. destinationPath = hasSo ? sopath : pypath; destinationFile = new File(destinationPath, entry.getName()); } FileUtils.makeDirectories(destinationFile.getParentFile(), 0755); sendmsg(true, "pos", cnt); OutputStream output = new BufferedOutputStream(new FileOutputStream(destinationFile)); InputStream input = zipfile.getInputStream(entry); int len; while ((len = input.read(buf)) > 0) { output.write(buf, 0, len); } input.close(); output.flush(); output.close(); if (entry.getName().endsWith(".py")) { if (readFirstLine(destinationFile).contains("__bootstrap__")) { // don't include autogenerated bootstrap, not useful for us destinationFile.delete(); continue; } } if (!isInfo) { installed.add(destinationFile.getAbsolutePath()); } destinationFile.setLastModified(entry.getTime()); FileUtils.chmod(destinationFile, entry.getName().endsWith(".so") ? 0755 : 0644); } FileWriter fstream = new FileWriter(new File(new File(egginfo, from.getName()), "files.txt")); BufferedWriter out = new BufferedWriter(fstream); for (String line : installed) { out.write(line + "\n"); } out.close(); sendmsg(false, "Success"); } catch (Exception entry) { sendmsg(false, "Error" + entry); } } private void sendmsg(boolean running, String info) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); if (info != null) { bundle.putString("info", info); } message.setData(bundle); mHandler.sendMessage(message); } private void sendmsg(boolean running, String key, int value) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); bundle.putInt(key, value); message.setData(bundle); mHandler.sendMessage(message); } } class RunDelete extends Thread { String caption; File from; File sopath; File pypath; File egginfo; Handler mHandler; RunDelete(String caption, File from, File pypath, File sopath, Handler h, File egginfo) { this.caption = caption; this.from = from; this.pypath = pypath; this.sopath = sopath; this.egginfo = egginfo; mHandler = h; } private void delete(File source) { try { if (source.exists() && source.isDirectory()) { for (File entry : source.listFiles()) { if (entry.isDirectory()) { delete(entry); } else { entry.delete(); } System.out.println(entry + " deleted"); } source.delete(); System.out.println(source.getName() + " deleted"); } } catch (Exception e) { e.printStackTrace(); } } private void deleteInstalledFiles() { BufferedReader in; String line; File target; try { in = new BufferedReader(new FileReader(new File(from, "files.txt"))); while ((line = in.readLine()) != null) { target = new File(line); if (!target.exists()) { continue; } target.delete(); System.out.println(target.getAbsolutePath() + " deleted " + target.exists()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { sendmsg(true, "max", 4); String toplevel = readFirstLine(new File(from, "top_level.txt")); deleteInstalledFiles(); sendmsg(true, "pos", 1); delete(new File(sopath, toplevel)); sendmsg(true, "pos", 2); delete(new File(pypath, toplevel)); sendmsg(true, "pos", 3); delete(from); sendmsg(true, "pos", 4); sendmsg(false, "Success"); } private void sendmsg(boolean running, String info) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); if (info != null) { bundle.putString("info", info); } message.setData(bundle); mHandler.sendMessage(message); } private void sendmsg(boolean running, String key, int value) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); bundle.putInt(key, value); message.setData(bundle); mHandler.sendMessage(message); } } }
android/PythonForAndroid/src/com/googlecode/pythonforandroid/PythonMain.java
package com.googlecode.pythonforandroid; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.FileUtils; import com.googlecode.android_scripting.InterpreterInstaller; import com.googlecode.android_scripting.InterpreterUninstaller; import com.googlecode.android_scripting.activity.Main; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; import com.googlecode.android_scripting.interpreter.InterpreterUtils; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Python Installer. Incorporates module installer. * * The module installer reads a zip file previously downloaded into "download", and unpacks it. If * the module contains shared libraries (*.so) then the module is unpacked into data, other installs * in extras. * * Typically, these will be /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6 * and /sdcard/com.googlecode.pythonforandroid/extras respectively. * * @author Damon * @author Robbie Matthews ([email protected]) * @author Manuel Naranjo ([email protected]) */ // TODO:(Robbie) The whole Import Module is more of a proof of concept than a fully realised // process. Needs some means of checking that these are properly formatted zip files, and probably a // means of uninstalling as well. Import handling could well be a separate activity, too. public class PythonMain extends Main { Button mButtonInstallModules; Button mButtonUninstallModule; File mDownloads; private Dialog mDialog; protected String mModule; private CharSequence[] mList; private ProgressDialog mProgress; private boolean mPromptResult; private static enum MenuId { BROWSER, SL4A; public int getId() { return ordinal() + Menu.FIRST; } } private String readFirstLine(File target) { BufferedReader in; String result; try { in = new BufferedReader(new FileReader(target)); result = in.readLine(); if (result == null) { result = ""; } in.close(); } catch (Exception e) { e.printStackTrace(); result = ""; } return result; } final Handler mModuleHandler = new Handler() { @Override public void handleMessage(Message message) { Bundle bundle = message.getData(); boolean running = bundle.getBoolean("running"); if (running) { if (bundle.containsKey("max")) { mProgress.setProgress(0); mProgress.setMax(bundle.getInt("max")); } else if (bundle.containsKey("pos")) { mProgress.setProgress(bundle.getInt("pos")); } else if (bundle.containsKey("message")) { mProgress.setMessage(bundle.getString("message")); } else { mProgress.incrementProgressBy(1); } } else { mProgress.dismiss(); String info = message.getData().getString("info"); if (info != null) { showMessage("Import Module", info); } } } }; private Button mButtonBrowse; private File mFrom; private File mSoPath; private File mPythonPath; private File mEggPath; private TextView mHostVersion, mOfficialVersion; private PythonDescriptor mDescriptor; private int getInstalledVersion(String key) { SharedPreferences storage = getSharedPreferences("python-installer", 0); return storage.getInt(key, -1); } @Override protected InterpreterDescriptor getDescriptor() { mDescriptor = new PythonDescriptor(); return mDescriptor; } @Override protected InterpreterInstaller getInterpreterInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PythonInstaller(descriptor, context, listener); } @Override protected InterpreterUninstaller getInterpreterUninstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PythonUninstaller(descriptor, context, listener); } @Override protected void onResume() { String s; super.onResume(); Intent intent = getIntent(); if (intent.getData() != null) { s = intent.getData().getPath(); Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); File file = new File(intent.getData().getPath()); if (file.exists()) { performImport(file, file.getName()); } } } private String createVersionString(String header, int version, int extras, int scripts) { String out = header; out += " Versions, interpreter: "; out += version > -1 ? version : " ND"; out += ", extras: "; out += extras > -1 ? extras : " ND"; out += ", scripts: "; out += scripts > -1 ? scripts : " ND"; return out; } @Override protected void initializeViews() { super.initializeViews(); mDownloads = FileUtils.getExternalDownload(); if (!mDownloads.exists()) { for (File file : new File(Environment.getExternalStorageDirectory().getAbsolutePath()) .listFiles()) { if (file.isDirectory()) { if (file.getName().toLowerCase().startsWith("download")) { mDownloads = file; break; } } } } MarginLayoutParams marginParams = new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); final float scale = getResources().getDisplayMetrics().density; int marginPixels = (int) (MARGIN_DIP * scale + 0.5f); marginParams.setMargins(marginPixels, marginPixels, marginPixels, marginPixels); mOfficialVersion = new TextView(this); mOfficialVersion.setLayoutParams(marginParams); mOfficialVersion.setText(createVersionString("Latest", mDescriptor.getVersion(), mDescriptor.getExtrasVersion(), mDescriptor.getScriptsVersion())); mLayout.addView(mOfficialVersion); mHostVersion = new TextView(this); mHostVersion.setLayoutParams(marginParams); mHostVersion.setText(createVersionString("Installed", getInstalledVersion("interpreter"), getInstalledVersion("extras"), getInstalledVersion("scripts"))); mLayout.addView(mHostVersion); mButtonInstallModules = new Button(this); mButtonInstallModules.setLayoutParams(marginParams); mButtonInstallModules.setText("Import Modules"); mLayout.addView(mButtonInstallModules); mButtonInstallModules.setOnClickListener(new OnClickListener() { public void onClick(View v) { doImportModule(); } }); mButtonBrowse = new Button(this); mButtonBrowse.setLayoutParams(marginParams); mButtonBrowse.setText("Browse Modules"); mLayout.addView(mButtonBrowse); mButtonBrowse.setOnClickListener(new OnClickListener() { public void onClick(View v) { doBrowseModule(); } }); mButtonUninstallModule = new Button(this); mButtonUninstallModule.setLayoutParams(marginParams); mButtonUninstallModule.setText("Uninstall Module"); mLayout.addView(mButtonUninstallModule); mButtonUninstallModule.setOnClickListener(new OnClickListener() { public void onClick(View v) { doDeleteModule(); } }); if (getInstalledVersion("interpreter") == -1) { /* * mDescriptor.setOffline(true); install(); */ } } @Override protected boolean checkInstalled() { broadcastInstallationStateChange(true); return true; } @Override protected void setInstalled(boolean isInstalled) { mHostVersion.setText(createVersionString("Installed", getInstalledVersion("interpreter"), getInstalledVersion("extras"), getInstalledVersion("scripts"))); super.setInstalled(isInstalled); } protected void doBrowseModule() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/python-for-android/wiki/Modules")); startActivity(intent); } public void doImportModule() { AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialog.dismiss(); if (which == DialogInterface.BUTTON_NEUTRAL) { showMessage("Import Module", "This will take a previously downloaded (and appropriately formatted) " + "python external module zip or egg file.\nSee sl4a wiki for more defails.\n" + "Looking for files in \n" + mDownloads); } } }; List<String> flist = new Vector<String>(); for (File f : mDownloads.listFiles()) { if (f.getName().endsWith(".zip") || f.getName().endsWith(".egg")) { flist.add(f.getName()); } } builder.setTitle("Import Module"); mList = flist.toArray(new CharSequence[flist.size()]); builder.setItems(mList, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mModule = (String) mList[which]; performImport(mModule); mDialog.dismiss(); } }); builder.setNegativeButton("Cancel", buttonListener); builder.setNeutralButton("Help", buttonListener); mModule = null; mDialog = builder.show(); if (mModule != null) { } } public void doDeleteModule() { mEggPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/egg-info"); AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mDialog.dismiss(); if (which == DialogInterface.BUTTON_NEUTRAL) { showMessage("Uninstall Module", "This will let you delete a module you got installed from an egg file"); } } }; List<String> flist = new Vector<String>(); for (File f : mEggPath.listFiles()) { if (f.getName().endsWith(".egg")) { flist.add(f.getName().replace(".egg", "")); } } builder.setTitle("Installed Modules"); mList = flist.toArray(new CharSequence[flist.size()]); builder.setItems(mList, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mModule = (String) mList[which]; performUninstall(mModule); mDialog.dismiss(); } }); builder.setNegativeButton("Cancel", buttonListener); builder.setNeutralButton("Help", buttonListener); mModule = null; mDialog = builder.show(); if (mModule != null) { } } protected void performImport(String module) { performImport(new File(mDownloads, mModule), module); } protected void performImport(File sourceFile, String module) { mModule = module; mFrom = sourceFile; mSoPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/lib/python2.6/lib-dynload"); mEggPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/egg-info"); mPythonPath = new File(mDescriptor.getEnvironmentVariables(this).get("PY4A_EXTRAS"), "python"); prompt("Install module " + module, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { extract("Extracting " + mModule, mFrom, mPythonPath, mSoPath, mEggPath); } } }); } protected void performUninstall(String module) { mModule = module; mEggPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/egg-info"); mFrom = new File(mEggPath, module + ".egg"); mSoPath = new File(InterpreterUtils.getInterpreterRoot(this), "python/lib/python2.6/lib-dynload"); mPythonPath = new File(mDescriptor.getEnvironmentVariables(this).get("PY4A_EXTRAS")); prompt("Uninstall module " + module, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == AlertDialog.BUTTON_POSITIVE) { remove("Deleting " + mModule, mFrom, mPythonPath, mSoPath, mEggPath); } } }); } protected void extract(String caption, File from, File pypath, File sopath, File egginfo) { mProgress = showProgress(caption); Thread t = new RunExtract(caption, from, pypath, sopath, mModuleHandler, egginfo); t.start(); } protected void remove(String caption, File from, File pypath, File sopath, File egginfo) { mProgress = showProgress(caption); Thread t = new RunDelete(caption, from, pypath, sopath, mModuleHandler, egginfo); t.start(); } protected ProgressDialog showProgress(String caption) { ProgressDialog b = new ProgressDialog(this); b.setTitle(caption); b.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); b.show(); return b; } protected void showMessage(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(message); builder.setNeutralButton("OK", null); builder.show(); } protected boolean prompt(String message, DialogInterface.OnClickListener btnlisten) { mPromptResult = false; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Python Installer"); builder.setMessage(message); builder.setNegativeButton("Cancel", btnlisten); builder.setPositiveButton("OK", btnlisten); builder.show(); return mPromptResult; } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MenuId.BROWSER.getId(), Menu.NONE, "File Browser").setIcon( android.R.drawable.ic_menu_myplaces); menu.add(Menu.NONE, MenuId.SL4A.getId(), Menu.NONE, "SL4A").setIcon(R.drawable.sl4a_logo_32); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; int id = item.getItemId(); if (MenuId.BROWSER.getId() == id) { intent = new Intent(this, FileBrowser.class); intent.setAction(PythonConstants.ACTION_FILE_BROWSER); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } else if (MenuId.SL4A.getId() == id) { intent = new Intent(); intent.setComponent(new ComponentName(PythonConstants.SL4A, PythonConstants.SL4A_MANAGER)); try { startActivity(intent); } catch (Exception e) { showMessage("Py4A", "SL4A may not be installed."); } } return true; } class RunExtract extends Thread { String caption; File from; File sopath; File pypath; File egginfo; Handler mHandler; RunExtract(String caption, File from, File pypath, File sopath, Handler h, File egginfo) { this.caption = caption; this.from = from; this.pypath = pypath; this.sopath = sopath; this.egginfo = egginfo; mHandler = h; } @Override public void run() { byte[] buf = new byte[4096]; boolean isInfo = false; List<ZipEntry> list = new ArrayList<ZipEntry>(); Vector<String> installed = new Vector<String>(); boolean hasSo = false; try { ZipFile zipfile = new ZipFile(from); int cnt = 0; sendmsg(true, "max", zipfile.size()); Enumeration<? extends ZipEntry> entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry ex = entries.nextElement(); if (ex.getName().endsWith(".so")) { hasSo = true; } list.add(ex); } for (ZipEntry entry : list) { cnt += 1; if (entry.isDirectory()) { continue; } File destinationPath; File destinationFile; isInfo = entry.getName().contains("EGG-INFO"); if (isInfo) { destinationPath = new File(egginfo, from.getName()); destinationFile = new File(destinationPath, entry.getName().split("/", 2)[1]); } else { // destinationPath = entry.getName().endsWith(".so") ? sopath : pypath; // Python does not cope well with splitting *.so and normal files. Sadly. // At the moment, if we have an *.so, we will copy entire library to main memory. destinationPath = hasSo ? sopath : pypath; destinationFile = new File(destinationPath, entry.getName()); } FileUtils.makeDirectories(destinationFile.getParentFile(), 0755); sendmsg(true, "pos", cnt); OutputStream output = new BufferedOutputStream(new FileOutputStream(destinationFile)); InputStream input = zipfile.getInputStream(entry); int len; while ((len = input.read(buf)) > 0) { output.write(buf, 0, len); } input.close(); output.flush(); output.close(); if (entry.getName().endsWith(".py")) { if (readFirstLine(destinationFile).contains("__bootstrap__")) { // don't include autogenerated bootstrap, not useful for us destinationFile.delete(); continue; } } if (!isInfo) { installed.add(destinationFile.getAbsolutePath()); } destinationFile.setLastModified(entry.getTime()); FileUtils.chmod(destinationFile, entry.getName().endsWith(".so") ? 0755 : 0644); } FileWriter fstream = new FileWriter(new File(new File(egginfo, from.getName()), "files.txt")); BufferedWriter out = new BufferedWriter(fstream); for (String line : installed) { out.write(line + "\n"); } out.close(); sendmsg(false, "Success"); } catch (Exception entry) { sendmsg(false, "Error" + entry); } } private void sendmsg(boolean running, String info) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); if (info != null) { bundle.putString("info", info); } message.setData(bundle); mHandler.sendMessage(message); } private void sendmsg(boolean running, String key, int value) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); bundle.putInt(key, value); message.setData(bundle); mHandler.sendMessage(message); } } class RunDelete extends Thread { String caption; File from; File sopath; File pypath; File egginfo; Handler mHandler; RunDelete(String caption, File from, File pypath, File sopath, Handler h, File egginfo) { this.caption = caption; this.from = from; this.pypath = pypath; this.sopath = sopath; this.egginfo = egginfo; mHandler = h; } private void delete(File source) { try { if (source.exists() && source.isDirectory()) { for (File entry : source.listFiles()) { if (entry.isDirectory()) { delete(entry); } else { entry.delete(); } System.out.println(entry + " deleted"); } source.delete(); System.out.println(source.getName() + " deleted"); } } catch (Exception e) { e.printStackTrace(); } } private void deleteInstalledFiles() { BufferedReader in; String line; File target; try { in = new BufferedReader(new FileReader(new File(from, "files.txt"))); while ((line = in.readLine()) != null) { target = new File(line); if (!target.exists()) { continue; } target.delete(); System.out.println(target.getAbsolutePath() + " deleted " + target.exists()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { sendmsg(true, "max", 4); String toplevel = readFirstLine(new File(from, "top_level.txt")); deleteInstalledFiles(); sendmsg(true, "pos", 1); delete(new File(sopath, toplevel)); sendmsg(true, "pos", 2); delete(new File(pypath, toplevel)); sendmsg(true, "pos", 3); delete(from); sendmsg(true, "pos", 4); sendmsg(false, "Success"); } private void sendmsg(boolean running, String info) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); if (info != null) { bundle.putString("info", info); } message.setData(bundle); mHandler.sendMessage(message); } private void sendmsg(boolean running, String key, int value) { Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putBoolean("running", running); bundle.putInt(key, value); message.setData(bundle); mHandler.sendMessage(message); } } }
Install Eggs into /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6/lib-dynload (path may no be the most common, but who cares\!), create .pth files during installation so egg files are automatically added to the sys.path. .pth files are created in /data/data/com.googlecode.pythonforandroid/files/lib/python2.6/site-packages/ using <eggfile with egg extension>.pth scheme, removed the install/uninstall button and the version strings, added an install script button. Egg files are not handled by the uninstaller any more (needs to be fixed)
android/PythonForAndroid/src/com/googlecode/pythonforandroid/PythonMain.java
Install Eggs into /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6/lib-dynload (path may no be the most common, but who cares\!), create .pth files during installation so egg files are automatically added to the sys.path. .pth files are created in /data/data/com.googlecode.pythonforandroid/files/lib/python2.6/site-packages/ using <eggfile with egg extension>.pth scheme, removed the install/uninstall button and the version strings, added an install script button. Egg files are not handled by the uninstaller any more (needs to be fixed)
<ide><path>ndroid/PythonForAndroid/src/com/googlecode/pythonforandroid/PythonMain.java <ide> import android.view.View.OnClickListener; <ide> import android.view.ViewGroup.LayoutParams; <ide> import android.view.ViewGroup.MarginLayoutParams; <add>import android.view.Window; <ide> import android.widget.Button; <del>import android.widget.TextView; <ide> import android.widget.Toast; <ide> <ide> import com.googlecode.android_scripting.AsyncTaskListener; <ide> import com.googlecode.android_scripting.FileUtils; <ide> import com.googlecode.android_scripting.InterpreterInstaller; <ide> import com.googlecode.android_scripting.InterpreterUninstaller; <add>import com.googlecode.android_scripting.Log; <ide> import com.googlecode.android_scripting.activity.Main; <ide> import com.googlecode.android_scripting.exception.Sl4aException; <ide> import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; <ide> import com.googlecode.android_scripting.interpreter.InterpreterUtils; <ide> <add>import java.io.BufferedInputStream; <ide> import java.io.BufferedOutputStream; <ide> import java.io.BufferedReader; <ide> import java.io.BufferedWriter; <ide> import java.io.File; <add>import java.io.FileInputStream; <add>import java.io.FileNotFoundException; <ide> import java.io.FileOutputStream; <ide> import java.io.FileReader; <ide> import java.io.FileWriter; <add>import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.io.OutputStream; <ide> import java.util.ArrayList; <ide> * Typically, these will be /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6 <ide> * and /sdcard/com.googlecode.pythonforandroid/extras respectively. <ide> * <add> * Egg files are just copied into <add> * /data/data/com.googlecode.pythonforandroid/files/python/lib/python2.6 <add> * <ide> * @author Damon <ide> * @author Robbie Matthews ([email protected]) <ide> * @author Manuel Naranjo ([email protected]) <ide> // process. Needs some means of checking that these are properly formatted zip files, and probably a <ide> // means of uninstalling as well. Import handling could well be a separate activity, too. <ide> public class PythonMain extends Main { <add> Button mButtonInstallScripts; <ide> Button mButtonInstallModules; <ide> Button mButtonUninstallModule; <ide> File mDownloads; <ide> private File mSoPath; <ide> private File mPythonPath; <ide> private File mEggPath; <del> private TextView mHostVersion, mOfficialVersion; <ide> private PythonDescriptor mDescriptor; <ide> <ide> private int getInstalledVersion(String key) { <ide> } <ide> } <ide> <del> private String createVersionString(String header, int version, int extras, int scripts) { <del> String out = header; <del> out += " Versions, interpreter: "; <del> out += version > -1 ? version : " ND"; <del> out += ", extras: "; <del> out += extras > -1 ? extras : " ND"; <del> out += ", scripts: "; <del> out += scripts > -1 ? scripts : " ND"; <del> <del> return out; <del> } <del> <ide> @Override <ide> protected void initializeViews() { <ide> super.initializeViews(); <add> mButton.setVisibility(View.GONE); <ide> <ide> mDownloads = FileUtils.getExternalDownload(); <ide> if (!mDownloads.exists()) { <ide> int marginPixels = (int) (MARGIN_DIP * scale + 0.5f); <ide> marginParams.setMargins(marginPixels, marginPixels, marginPixels, marginPixels); <ide> <del> mOfficialVersion = new TextView(this); <del> mOfficialVersion.setLayoutParams(marginParams); <del> mOfficialVersion.setText(createVersionString("Latest", mDescriptor.getVersion(), <del> mDescriptor.getExtrasVersion(), mDescriptor.getScriptsVersion())); <del> mLayout.addView(mOfficialVersion); <del> <del> mHostVersion = new TextView(this); <del> mHostVersion.setLayoutParams(marginParams); <del> mHostVersion.setText(createVersionString("Installed", getInstalledVersion("interpreter"), <del> getInstalledVersion("extras"), getInstalledVersion("scripts"))); <del> mLayout.addView(mHostVersion); <add> mButtonInstallScripts = new Button(this); <add> mButtonInstallScripts.setLayoutParams(marginParams); <add> mButtonInstallScripts.setText("Install Example Scripts"); <add> mLayout.addView(mButtonInstallScripts); <add> mButtonInstallScripts.setOnClickListener(new OnClickListener() { <add> public void onClick(View v) { <add> if (mCurrentTask != null) { <add> return; <add> } <add> getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, <add> Window.PROGRESS_VISIBILITY_ON); <add> mCurrentTask = RunningTask.INSTALL; <add> InterpreterInstaller installTask; <add> try { <add> installTask = getInterpreterInstaller(mDescriptor, PythonMain.this, mTaskListener); <add> } catch (Sl4aException e) { <add> Log.e(PythonMain.this, e.getMessage(), e); <add> return; <add> } <add> installTask.execute(); <add> } <add> }); <ide> <ide> mButtonInstallModules = new Button(this); <ide> mButtonInstallModules.setLayoutParams(marginParams); <ide> doDeleteModule(); <ide> } <ide> }); <del> if (getInstalledVersion("interpreter") == -1) { <del> /* <del> * mDescriptor.setOffline(true); install(); <del> */ <del> } <del> <ide> } <ide> <ide> @Override <ide> protected boolean checkInstalled() { <ide> broadcastInstallationStateChange(true); <ide> return true; <del> } <del> <del> @Override <del> protected void setInstalled(boolean isInstalled) { <del> mHostVersion.setText(createVersionString("Installed", getInstalledVersion("interpreter"), <del> getInstalledVersion("extras"), getInstalledVersion("scripts"))); <del> super.setInstalled(isInstalled); <ide> } <ide> <ide> protected void doBrowseModule() { <ide> @Override <ide> public void onClick(DialogInterface dialog, int which) { <ide> if (which == AlertDialog.BUTTON_POSITIVE) { <del> extract("Extracting " + mModule, mFrom, mPythonPath, mSoPath, mEggPath); <add> if (mModule.toLowerCase().endsWith(".egg")) { <add> copy(new File(mSoPath, mModule), mFrom); <add> try { <add> File out = <add> new File(InterpreterUtils.getInterpreterRoot(PythonMain.this), <add> "lib/python2.6/site-packages/" + mModule + ".pth"); <add> FileOutputStream fout = new FileOutputStream(out); <add> fout.write(new File(mSoPath, mModule).getAbsolutePath().getBytes()); <add> fout.close(); <add> FileUtils.chmod(out, 0755); <add> } catch (FileNotFoundException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } catch (IOException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } catch (Exception e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> } else { <add> extract("Extracting " + mModule, mFrom, mPythonPath, mSoPath, mEggPath); <add> } <ide> } <ide> } <ide> }); <ide> mProgress = showProgress(caption); <ide> Thread t = new RunExtract(caption, from, pypath, sopath, mModuleHandler, egginfo); <ide> t.start(); <add> } <add> <add> protected void copy(File target, File from) { <add> try { <add> InputStream input = new BufferedInputStream(new FileInputStream(from)); <add> target.getParentFile().mkdirs(); <add> OutputStream output = new BufferedOutputStream(new FileOutputStream(target)); <add> byte[] buf = new byte[1024]; <add> int len; <add> <add> while ((len = input.read(buf)) > 0) { <add> output.write(buf, 0, len); <add> } <add> output.close(); <add> input.close(); <add> FileUtils.recursiveChmod(target.getParentFile(), 0777); <add> } catch (FileNotFoundException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } catch (IOException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } catch (Exception e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <ide> } <ide> <ide> protected void remove(String caption, File from, File pypath, File sopath, File egginfo) {
JavaScript
apache-2.0
1ccfe531ae0809ff68a55a19a62b8f13279901ae
0
app-scripters/apps-script-uber-kit,app-scripters/apps-script-uber-kit
/** * Authorizes and makes a request to the QuickBooks API. Assumes the use of a * sandbox company. */ function QB(options){ var t = this; //check if this is really object construction if (! t.serviceName) { throw new Error("you've forgotten 'new' keyword: var instance = new " + t.serviceName + "(...)"); } t._props = options.store || PropertiesService.getUserProperties(); t._isAuthCallback = options._isAuthCallback; t._creds = { consumerKey: options.consumerKey, consumerSecret: options.consumerSecret }; if (! options.callback || typeof options.callback !== "string"){ throw new Error("Oauth callback global function name should be specified in the 'callback' option!") } t._callbackName = options.callback; //onDenied is not needed for callback instance t.userOnDenied = options.onDenied || Lib.util.stub; t._service = t._getService(); t._data = {}; //tracks Authorization process state. //we should NOT initiate authorization here in the constructor, //because the same constructor //will be called in OAuth callback below, and request token will change otherwise t._auth = t._checkAuth(); if (t._auth) { t._refreshData(); } } QB.prototype.serviceName = 'QuickBooks'; QB.prototype._refreshData = function () { var t = this; t._data.companyId = t._props.getProperty('QuickBooks.companyId'); }; QB.prototype._checkAuth = function (failedRequestData) { var t = this; //if we in the callback process, all below is not needed if (t._isAuthCallback) return false; if (failedRequestData) t.reset(); if (failedRequestData || ! t._service.hasAccess()) { t._voidAuth(failedRequestData); } else { t._auth = true; } return t._auth; }; QB.prototype._voidAuth = function (failedRequestData) { var t = this; t._auth = false; t.userOnDenied(t._service.authorize(), failedRequestData ? ("Authorization reason: after failed request, data=" + JSON.stringify(failedRequestData)) : '' ); }; QB.prototype.reset = function() { this._auth = false; this._getService().reset(); }; QB.prototype.fetch = function(method, entity, idOrNull, params, payload) { var t = this; var noAuth = {auth: false, error: true}; if (! t._auth) return noAuth; var companyId = t._data.companyId; if (! companyId){ t.reset(); t._voidAuth(); return noAuth; } var url = 'https://quickbooks.api.intuit.com/v3/company/' + companyId + '/' + entity + (idOrNull == null ? '' : ('/' + (idOrNull === '' ? companyId : idOrNull))); var opts = { method: method, headers: { 'Accept': 'application/json' }, muteHttpExceptions: true }; if (method === 'post'){ opts.payload = payload; opts.contentType = 'application/json'; } const finalUrl = url + Lib.util.makeUrlParams(params); Logger.log("final URL = " + finalUrl); var response = t._service.fetch(finalUrl, opts); var code = parseInt(response.getResponseCode()); var data = response.getContentText(); if (code != 200){ if (code === 401) { //no auth t._checkAuth({code: code, data: data, headers: response.getHeaders()}); return noAuth; } return {auth: true, error: true, code: code, data: data}; } return {auth: true, error: false, code: 200, data: JSON.parse(data)}; }; QB.prototype.create = function(entity, json) { return this.fetch('post', entity, null, null, json); }; QB.prototype.query = function(query) { var response = this.fetch('get', 'query', null, {query: query}); if (! response.error) response.data = response.data.QueryResponse; return response; }; QB.prototype.read = function(entity, id) { return this.fetch('get', entity, id); }; QB.prototype.update = function(entity, json) { return this.fetch('post', entity, null, {operation: "update"}, json); }; QB.prototype.remove = function(entity, id) { return this.fetch('post', entity, null, {operation: "delete"}, { "Id": String(id), "SyncToken": "0" }); }; QB.prototype._getService = function() { var t = this; return Vendor.OAuth1.createService('QuickBooks') // Set the endpoint URLs. .setAccessTokenUrl('https://oauth.intuit.com/oauth/v1/get_access_token') .setRequestTokenUrl('https://oauth.intuit.com/oauth/v1/get_request_token') .setAuthorizationUrl('https://appcenter.intuit.com/Connect/Begin') //this is NOT working for QuickBooks, using default method via headers //.setParamLocation('uri-query') // Set the consumer key and secret. .setConsumerKey(t._creds.consumerKey) .setConsumerSecret(t._creds.consumerSecret) // Set the name of the callback function in the script referenced // above that should be invoked to complete the OAuth flow. .setCallbackFunction(t._callbackName) // Set the property store where authorized tokens should be persisted. .setPropertyStore(t._props); }; QB.handleCallback = function(qbOptions, request, onAccess) { var t = new QB(Lib.util.extend({}, qbOptions, { _isAuthCallback: true })); t._service = t._getService(); try { var authorized = t._service.handleCallback(request); }catch (e){ return HtmlService.createHtmlOutput('<p><b>OAuth: Internal error: </b></p>' + '<p><b>' + e.message + '</b></p>', '<p>Please check your login/password for ' + t.serviceName + ', close this window, and re-run the script.</p>' + '<p>Please contact your administrator, it the problem remains, with the error message above.</p>'); } t._auth = authorized; if (authorized) { PropertiesService.getUserProperties() .setProperty('QuickBooks.companyId', request.parameter.realmId); t._refreshData(); onAccess.call(t); //make sure service object is accessible under 'this' return HtmlService.createHtmlOutput('<b>OAuth Success! You may close this window.</b>'); }else{ return HtmlService.createHtmlOutput('<p><b>OAuth: Access DENIED!</b></p>' + '<p>Check login/password for ' + t.serviceName + ', close this window, and re-run the script.</p>' + '<p>Please contact your administrator, it the problem remains after that.</p>'); } }; Lib.oauth1.QuickBooks = QB;
lib-src/19.1.oauth1.QuickBooks.js
/** * Authorizes and makes a request to the QuickBooks API. Assumes the use of a * sandbox company. */ function QB(options){ var t = this; //check if this is really object construction if (! t.serviceName) { throw new Error("you've forgotten 'new' keyword: var instance = new " + t.serviceName + "(...)"); } t._props = options.store || PropertiesService.getUserProperties(); t._isAuthCallback = options._isAuthCallback; t._creds = { consumerKey: options.consumerKey, consumerSecret: options.consumerSecret }; if (! options.callback || typeof options.callback !== "string"){ throw new Error("Oauth callback global function name should be specified in the 'callback' option!") } t._callbackName = options.callback; //onDenied is not needed for callback instance t.userOnDenied = options.onDenied || Lib.util.stub; t._service = t._getService(); t._data = {}; //tracks Authorization process state. //we should NOT initiate authorization here in the constructor, //because the same constructor //will be called in OAuth callback below, and request token will change otherwise t._auth = t._checkAuth(); if (t._auth) { t._refreshData(); } } QB.prototype.serviceName = 'QuickBooks'; QB.prototype._refreshData = function () { var t = this; t._data.companyId = t._props.getProperty('QuickBooks.companyId'); }; QB.prototype._checkAuth = function (failedRequestData) { var t = this; //if we in the callback process, all below is not needed if (t._isAuthCallback) return false; if (failedRequestData) t.reset(); if (failedRequestData || ! t._service.hasAccess()) { t._auth = false; //if not authorised, then call the handler to create a user-facing auth URL t.userOnDenied(t._service.authorize(), failedRequestData ? ("Authorization reason: after failed request, data=" + JSON.stringify(failedRequestData)) : '' ); } else { t._auth = true; } return t._auth; }; QB.prototype.reset = function() { this._auth = false; this._getService().reset(); }; QB.prototype.fetch = function(method, entity, idOrNull, params, payload) { var t = this; var noAuth = {auth: false, error: true}; if (! t._auth) return noAuth; var companyId = t._data.companyId; var url = 'https://quickbooks.api.intuit.com/v3/company/' + companyId + '/' + entity + (idOrNull == null ? '' : ('/' + (idOrNull === '' ? companyId : idOrNull))); var opts = { method: method, headers: { 'Accept': 'application/json' }, muteHttpExceptions: true }; if (method === 'post'){ opts.payload = payload; opts.contentType = 'application/json'; } var response = t._service.fetch(url + Lib.util.makeUrlParams(params), opts); var code = parseInt(response.getResponseCode()); var data = response.getContentText(); if (code != 200){ if (code === 401) { //no auth t._checkAuth({code: code, data: data, headers: response.getHeaders()}); return noAuth; } return {auth: true, error: true, code: code, data: data}; } return {auth: true, error: false, code: 200, data: JSON.parse(data)}; }; QB.prototype.create = function(entity, json) { return this.fetch('post', entity, null, null, json); }; QB.prototype.query = function(query) { var response = this.fetch('get', 'query', null, {query: query}); if (! response.error) response.data = response.data.QueryResponse; return response; }; QB.prototype.read = function(entity, id) { return this.fetch('get', entity, id); }; QB.prototype.update = function(entity, json) { return this.fetch('post', entity, null, {operation: "update"}, json); }; QB.prototype.remove = function(entity, id) { return this.fetch('post', entity, null, {operation: "delete"}, { "Id": String(id), "SyncToken": "0" }); }; QB.prototype._getService = function() { var t = this; return Vendor.OAuth1.createService('QuickBooks') // Set the endpoint URLs. .setAccessTokenUrl('https://oauth.intuit.com/oauth/v1/get_access_token') .setRequestTokenUrl('https://oauth.intuit.com/oauth/v1/get_request_token') .setAuthorizationUrl('https://appcenter.intuit.com/Connect/Begin') //this is NOT working for QuickBooks, using default method via headers //.setParamLocation('uri-query') // Set the consumer key and secret. .setConsumerKey(t._creds.consumerKey) .setConsumerSecret(t._creds.consumerSecret) // Set the name of the callback function in the script referenced // above that should be invoked to complete the OAuth flow. .setCallbackFunction(t._callbackName) // Set the property store where authorized tokens should be persisted. .setPropertyStore(t._props); }; QB.handleCallback = function(qbOptions, request, onAccess) { var t = new QB(Lib.util.extend({}, qbOptions, { _isAuthCallback: true })); t._service = t._getService(); try { var authorized = t._service.handleCallback(request); }catch (e){ return HtmlService.createHtmlOutput('<p><b>OAuth: Internal error: </b></p>' + '<p><b>' + e.message + '</b></p>', '<p>Please check your login/password for ' + t.serviceName + ', close this window, and re-run the script.</p>' + '<p>Please contact your administrator, it the problem remains, with the error message above.</p>'); } t._auth = authorized; if (authorized) { PropertiesService.getUserProperties() .setProperty('QuickBooks.companyId', request.parameter.realmId); t._refreshData(); onAccess.call(t); //make sure service object is accessible under 'this' return HtmlService.createHtmlOutput('<b>OAuth Success! You may close this window.</b>'); }else{ return HtmlService.createHtmlOutput('<p><b>OAuth: Access DENIED!</b></p>' + '<p>Check login/password for ' + t.serviceName + ', close this window, and re-run the script.</p>' + '<p>Please contact your administrator, it the problem remains after that.</p>'); } }; Lib.oauth1.QuickBooks = QB;
QuickBooks: Auth detection improvements
lib-src/19.1.oauth1.QuickBooks.js
QuickBooks: Auth detection improvements
<ide><path>ib-src/19.1.oauth1.QuickBooks.js <ide> if (failedRequestData) t.reset(); <ide> <ide> if (failedRequestData || ! t._service.hasAccess()) { <del> t._auth = false; <del> //if not authorised, then call the handler to create a user-facing auth URL <del> t.userOnDenied(t._service.authorize(), <del> failedRequestData ? ("Authorization reason: after failed request, data=" <del> + JSON.stringify(failedRequestData)) : '' <del> ); <add> t._voidAuth(failedRequestData); <ide> } else { <ide> t._auth = true; <ide> } <ide> return t._auth; <add>}; <add> <add> <add>QB.prototype._voidAuth = function (failedRequestData) { <add> var t = this; <add> <add> t._auth = false; <add> <add> t.userOnDenied(t._service.authorize(), <add> failedRequestData ? ("Authorization reason: after failed request, data=" <add> + JSON.stringify(failedRequestData)) : '' <add> ); <ide> }; <ide> <ide> <ide> if (! t._auth) return noAuth; <ide> <ide> var companyId = t._data.companyId; <add> <add> if (! companyId){ <add> t.reset(); <add> t._voidAuth(); <add> return noAuth; <add> } <ide> <ide> var url = 'https://quickbooks.api.intuit.com/v3/company/' + <ide> companyId + '/' + entity + <ide> opts.payload = payload; <ide> opts.contentType = 'application/json'; <ide> } <del> <del> var response = t._service.fetch(url + Lib.util.makeUrlParams(params), opts); <add> const finalUrl = url + Lib.util.makeUrlParams(params); <add> Logger.log("final URL = " + finalUrl); <add> var response = t._service.fetch(finalUrl, opts); <ide> var code = parseInt(response.getResponseCode()); <ide> var data = response.getContentText(); <ide> if (code != 200){
Java
mit
618fb8d13ca31f75d66daa1ca53784ef59e288de
0
AbeSkray/poker-calculator
package com.skraylabs.poker.model; /** * Checked exception thrown when a string representing a {@link GameState} is formatted incorrectly. * This applies to general syntax errors that don't qualify for a more specific exception ( * {@link CardFormatException}, {@link BoardFormatException}, {@link GameStateFormatException}). */ public class GameStateFormatException extends PokerFormatException { /** * Generated serial ID. */ private static final long serialVersionUID = -3555305759559275725L; /** * Default detail message used when the invalid string sample is not provided. */ public static final String MSG_DEFAULT = "The provided string could not be resolved to a GameState format."; /** * Detail message used when the invalid string sample is provided. Expects one String argument. */ public static final String MSG_WITH_INVALID_STRING = "The string <\"%s\"> could not be resolved to a GameState format."; /** * Default constructor. */ public GameStateFormatException() { super(MSG_DEFAULT); } /** * Initializing constructor. * * @param message detail message */ public GameStateFormatException(String message) { super(message); } }
src/main/java/com/skraylabs/poker/model/GameStateFormatException.java
package com.skraylabs.poker.model; /** * Checked exception thrown when a string representing a {@link GameState} is formatted incorrectly. * This applies to general syntax errors that don't qualify for a more specific exception ( * {@link CardFormatException}, {@link BoardFormatException}, {@link GameStateFormatException}). */ public class GameStateFormatException extends PokerFormatException { /** * Generated serial ID. */ private static final long serialVersionUID = -3555305759559275725L; /** * Default detail message used when the invalid string sample is not provided. */ public static final String MSG_DEFAULT = "The provided string could not be resolved to a GameState format."; /** * Detail message used when the invalid string sample is provided. Expects one String argument. */ public static final String MSG_WITH_INVALID_STRING = "The string <\"%s\"> could not be resolved to a GameState format."; /** * Default constructor. */ public GameStateFormatException() { } /** * Initializing constructor. * * @param message detail message */ public GameStateFormatException(String message) { } }
GameStateFormatException: implement constructors.
src/main/java/com/skraylabs/poker/model/GameStateFormatException.java
GameStateFormatException: implement constructors.
<ide><path>rc/main/java/com/skraylabs/poker/model/GameStateFormatException.java <ide> * Default constructor. <ide> */ <ide> public GameStateFormatException() { <add> super(MSG_DEFAULT); <ide> } <ide> <ide> /** <ide> * @param message detail message <ide> */ <ide> public GameStateFormatException(String message) { <add> super(message); <ide> } <ide> }
Java
mit
43f701ba8ff559e1b92552f7ca0111c959dfdb67
0
Barteks2x/CubicChunksConverter,Barteks2x/CubicChunksConverter
/* * This file is part of CubicChunksConverter, licensed under the MIT License (MIT). * * Copyright (c) 2017 contributors * * 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 cubicchunks.converter.lib.util; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; import cubicchunks.regionlib.api.region.IRegion; import cubicchunks.regionlib.api.region.IRegionProvider; import cubicchunks.regionlib.api.region.key.IKey; import cubicchunks.regionlib.api.region.key.IKeyProvider; import cubicchunks.regionlib.api.region.key.RegionKey; import cubicchunks.regionlib.lib.Region; import cubicchunks.regionlib.lib.header.IKeyIdToSectorMap; import cubicchunks.regionlib.lib.header.IntPackedSectorMap; import cubicchunks.regionlib.util.CheckedConsumer; import cubicchunks.regionlib.util.CorruptedDataException; import cubicchunks.regionlib.util.WrappedException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class MemoryReadRegion<K extends IKey<K>> implements IRegion<K> { private final IKeyIdToSectorMap<?, ?, K> sectorMap; private final int sectorSize; private SeekableByteChannel file; private final RegionKey regionKey; private final IKeyProvider<K> keyProvider; private final int keyCount; private ByteBuffer fileBuffer; private MemoryReadRegion(SeekableByteChannel file, IntPackedSectorMap<K> sectorMap, RegionKey regionKey, IKeyProvider<K> keyProvider, int sectorSize) throws IOException { this.file = file; this.regionKey = regionKey; this.keyProvider = keyProvider; this.keyCount = keyProvider.getKeyCount(regionKey); this.sectorSize = sectorSize; this.sectorMap = sectorMap; } @Override public synchronized void writeValue(K key, ByteBuffer value) throws IOException { throw new UnsupportedOperationException("Writing not supported in this implementation"); } @Override public void writeSpecial(K key, Object marker) throws IOException { throw new UnsupportedOperationException("Writing not supported in this implementation"); } @Override public synchronized Optional<ByteBuffer> readValue(K key) throws IOException { if (fileBuffer == null) { this.fileBuffer = ByteBuffer.allocate((int) file.size()); file.position(0); file.read(fileBuffer); file.close(); file = null; } // a hack because Optional can't throw checked exceptions try { return sectorMap.trySpecialValue(key) .map(reader -> Optional.of(reader.apply(key))) .orElseGet(() -> doReadKey(key)); } catch (WrappedException e) { throw (IOException) e.get(); } } private Optional<ByteBuffer> doReadKey(K key) { return sectorMap.getEntryLocation(key).flatMap(loc -> { try { int sectorOffset = loc.getOffset(); int sectorCount = loc.getSize(); fileBuffer.position(sectorOffset * sectorSize); int dataLength = fileBuffer.getInt(); if (dataLength > sectorCount * sectorSize) { throw new CorruptedDataException( "Expected data size max" + sectorCount * sectorSize + " but found " + dataLength); } fileBuffer.position(sectorOffset * sectorSize + Integer.BYTES); fileBuffer.limit(sectorOffset * sectorSize + Integer.BYTES + dataLength); return Optional.of(ByteBuffer.allocate(dataLength).put(fileBuffer)); } catch (IOException e) { throw new WrappedException(e); } }); } /** * Returns true if something was stored there before within this region. */ @Override public synchronized boolean hasValue(K key) { return sectorMap.getEntryLocation(key).isPresent(); } @Override public void forEachKey(CheckedConsumer<? super K, IOException> cons) throws IOException { for (int id = 0; id < this.keyCount; id++) { int idFinal = id; // because java is stupid K key = sectorMap.getEntryLocation(id).map(loc -> keyProvider.fromRegionAndId(this.regionKey, idFinal)).orElse(null); if (key != null) { cons.accept(key); } } } private int getSectorNumber(int bytes) { return ceilDiv(bytes, sectorSize); } @Override public void close() throws IOException { if (file != null) { file.close(); } } private static int ceilDiv(int x, int y) { return -Math.floorDiv(-x, y); } public static <L extends IKey<L>> Region.Builder<L> builder() { return new Region.Builder<>(); } /** * Internal Region builder. Using it is very unsafe, there are no safeguards against using it improperly. Should only be used by * {@link IRegionProvider} implementations. */ // TODO: make a safer to use builder public static class Builder<K extends IKey<K>> { private Path directory; private int sectorSize = 512; private RegionKey regionKey; private IKeyProvider<K> keyProvider; private List<IntPackedSectorMap.SpecialSectorMapEntry<K>> specialEntries = new ArrayList<>(); public MemoryReadRegion.Builder<K> setDirectory(Path path) { this.directory = path; return this; } public MemoryReadRegion.Builder<K> setRegionKey(RegionKey key) { this.regionKey = key; return this; } public MemoryReadRegion.Builder<K> setKeyProvider(IKeyProvider<K> keyProvider) { this.keyProvider = keyProvider; return this; } public MemoryReadRegion.Builder<K> setSectorSize(int sectorSize) { this.sectorSize = sectorSize; return this; } public MemoryReadRegion<K> build() throws IOException { SeekableByteChannel file = Files.newByteChannel(directory.resolve(regionKey.getName()), CREATE, READ, WRITE); IntPackedSectorMap<K> sectorMap = IntPackedSectorMap.readOrCreate(file, keyProvider.getKeyCount(regionKey), specialEntries); return new MemoryReadRegion<>(file, sectorMap, this.regionKey, keyProvider, this.sectorSize); } } }
src/main/java/cubicchunks/converter/lib/util/MemoryReadRegion.java
/* * This file is part of CubicChunksConverter, licensed under the MIT License (MIT). * * Copyright (c) 2017 contributors * * 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 cubicchunks.converter.lib.util; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; import cubicchunks.regionlib.api.region.IRegion; import cubicchunks.regionlib.api.region.IRegionProvider; import cubicchunks.regionlib.api.region.key.IKey; import cubicchunks.regionlib.api.region.key.IKeyProvider; import cubicchunks.regionlib.api.region.key.RegionKey; import cubicchunks.regionlib.lib.Region; import cubicchunks.regionlib.lib.header.IKeyIdToSectorMap; import cubicchunks.regionlib.lib.header.IntPackedSectorMap; import cubicchunks.regionlib.util.CheckedConsumer; import cubicchunks.regionlib.util.CorruptedDataException; import cubicchunks.regionlib.util.WrappedException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class MemoryReadRegion<K extends IKey<K>> implements IRegion<K> { private final IKeyIdToSectorMap<?, ?, K> sectorMap; private final int sectorSize; private final RegionKey regionKey; private final IKeyProvider<K> keyProvider; private final int keyCount; private final ByteBuffer fileBuffer; private MemoryReadRegion(SeekableByteChannel file, IntPackedSectorMap<K> sectorMap, RegionKey regionKey, IKeyProvider<K> keyProvider, int sectorSize) throws IOException { this.regionKey = regionKey; this.keyProvider = keyProvider; this.keyCount = keyProvider.getKeyCount(regionKey); this.sectorSize = sectorSize; this.sectorMap = sectorMap; this.fileBuffer = ByteBuffer.allocate((int) file.size()); file.position(0); file.read(fileBuffer); file.close(); } @Override public synchronized void writeValue(K key, ByteBuffer value) throws IOException { throw new UnsupportedOperationException("Writing not supported in this implementation"); } @Override public void writeSpecial(K key, Object marker) throws IOException { throw new UnsupportedOperationException("Writing not supported in this implementation"); } @Override public synchronized Optional<ByteBuffer> readValue(K key) throws IOException { // a hack because Optional can't throw checked exceptions try { return sectorMap.trySpecialValue(key) .map(reader -> Optional.of(reader.apply(key))) .orElseGet(() -> doReadKey(key)); } catch (WrappedException e) { throw (IOException) e.get(); } } private Optional<ByteBuffer> doReadKey(K key) { return sectorMap.getEntryLocation(key).flatMap(loc -> { try { int sectorOffset = loc.getOffset(); int sectorCount = loc.getSize(); fileBuffer.position(sectorOffset * sectorSize); int dataLength = fileBuffer.getInt(); if (dataLength > sectorCount * sectorSize) { throw new CorruptedDataException( "Expected data size max" + sectorCount * sectorSize + " but found " + dataLength); } fileBuffer.position(sectorOffset * sectorSize + Integer.BYTES); fileBuffer.limit(sectorOffset * sectorSize + Integer.BYTES + dataLength); return Optional.of(ByteBuffer.allocate(dataLength).put(fileBuffer)); } catch (IOException e) { throw new WrappedException(e); } }); } /** * Returns true if something was stored there before within this region. */ @Override public synchronized boolean hasValue(K key) { return sectorMap.getEntryLocation(key).isPresent(); } @Override public void forEachKey(CheckedConsumer<? super K, IOException> cons) throws IOException { for (int id = 0; id < this.keyCount; id++) { int idFinal = id; // because java is stupid K key = sectorMap.getEntryLocation(id).map(loc -> keyProvider.fromRegionAndId(this.regionKey, idFinal)).orElse(null); if (key != null) { cons.accept(key); } } } private int getSectorNumber(int bytes) { return ceilDiv(bytes, sectorSize); } @Override public void close() { } private static int ceilDiv(int x, int y) { return -Math.floorDiv(-x, y); } public static <L extends IKey<L>> Region.Builder<L> builder() { return new Region.Builder<>(); } /** * Internal Region builder. Using it is very unsafe, there are no safeguards against using it improperly. Should only be used by * {@link IRegionProvider} implementations. */ // TODO: make a safer to use builder public static class Builder<K extends IKey<K>> { private Path directory; private int sectorSize = 512; private RegionKey regionKey; private IKeyProvider<K> keyProvider; private List<IntPackedSectorMap.SpecialSectorMapEntry<K>> specialEntries = new ArrayList<>(); public MemoryReadRegion.Builder<K> setDirectory(Path path) { this.directory = path; return this; } public MemoryReadRegion.Builder<K> setRegionKey(RegionKey key) { this.regionKey = key; return this; } public MemoryReadRegion.Builder<K> setKeyProvider(IKeyProvider<K> keyProvider) { this.keyProvider = keyProvider; return this; } public MemoryReadRegion.Builder<K> setSectorSize(int sectorSize) { this.sectorSize = sectorSize; return this; } public MemoryReadRegion<K> build() throws IOException { SeekableByteChannel file = Files.newByteChannel(directory.resolve(regionKey.getName()), CREATE, READ, WRITE); IntPackedSectorMap<K> sectorMap = IntPackedSectorMap.readOrCreate(file, keyProvider.getKeyCount(regionKey), specialEntries); return new MemoryReadRegion<>(file, sectorMap, this.regionKey, keyProvider, this.sectorSize); } } }
Lazy initialize file buffer in reading memory region for faster counting of files
src/main/java/cubicchunks/converter/lib/util/MemoryReadRegion.java
Lazy initialize file buffer in reading memory region for faster counting of files
<ide><path>rc/main/java/cubicchunks/converter/lib/util/MemoryReadRegion.java <ide> <ide> private final IKeyIdToSectorMap<?, ?, K> sectorMap; <ide> private final int sectorSize; <add> private SeekableByteChannel file; <ide> private final RegionKey regionKey; <ide> private final IKeyProvider<K> keyProvider; <ide> private final int keyCount; <del> private final ByteBuffer fileBuffer; <add> private ByteBuffer fileBuffer; <ide> <ide> private MemoryReadRegion(SeekableByteChannel file, <ide> IntPackedSectorMap<K> sectorMap, <ide> RegionKey regionKey, <ide> IKeyProvider<K> keyProvider, <ide> int sectorSize) throws IOException { <add> this.file = file; <ide> this.regionKey = regionKey; <ide> this.keyProvider = keyProvider; <ide> this.keyCount = keyProvider.getKeyCount(regionKey); <ide> this.sectorSize = sectorSize; <ide> this.sectorMap = sectorMap; <del> <del> this.fileBuffer = ByteBuffer.allocate((int) file.size()); <del> <del> file.position(0); <del> file.read(fileBuffer); <del> file.close(); <ide> } <ide> <ide> @Override public synchronized void writeValue(K key, ByteBuffer value) throws IOException { <ide> } <ide> <ide> @Override public synchronized Optional<ByteBuffer> readValue(K key) throws IOException { <add> if (fileBuffer == null) { <add> this.fileBuffer = ByteBuffer.allocate((int) file.size()); <add> <add> file.position(0); <add> file.read(fileBuffer); <add> file.close(); <add> file = null; <add> } <ide> // a hack because Optional can't throw checked exceptions <ide> try { <ide> return sectorMap.trySpecialValue(key) <ide> return ceilDiv(bytes, sectorSize); <ide> } <ide> <del> @Override public void close() { <add> @Override public void close() throws IOException { <add> if (file != null) { <add> file.close(); <add> } <ide> } <ide> <ide> private static int ceilDiv(int x, int y) {
Java
epl-1.0
c088374712505a627f9d08e070716419ca04982f
0
hansjoachim/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,rbevers/fitnesse
// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse; import fitnesse.http.MockRequestBuilder; import fitnesse.http.MockResponseSender; import fitnesse.http.Request; import fitnesse.http.Response; import fitnesse.socketservice.SocketFactory; import fitnesse.socketservice.SocketService; import fitnesse.util.MockSocket; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.BindException; import java.net.ServerSocket; import java.util.logging.Level; import java.util.logging.Logger; public class FitNesse { private static final Logger LOG = Logger.getLogger(FitNesse.class.getName()); private final FitNesseContext context; private boolean makeDirs = true; private volatile SocketService theService; public FitNesse(FitNesseContext context) { this.context = context; } public FitNesse dontMakeDirs() { makeDirs = false; return this; } private void establishRequiredDirectories() { establishDirectory(context.getRootPagePath()); establishDirectory(context.getRootPagePath() + "/files"); } private static void establishDirectory(String path) { File filesDir = new File(path); if (!filesDir.exists()) filesDir.mkdir(); } public boolean start() { if (makeDirs) { establishRequiredDirectories(); } try { if (context.port > 0) { ServerSocket serverSocket = context.useHTTPS ? SocketFactory.createSslServerSocket(context.port, context.sslClientAuth, context.sslParameterClassName) : SocketFactory.createServerSocket(context.port); theService = new SocketService(new FitNesseServer(context), false, serverSocket); } return true; } catch (BindException e) { LOG.severe("FitNesse cannot be started..."); LOG.severe("Port " + context.port + " is already in use."); LOG.severe("Use the -p <port#> command line argument to use a different port."); } catch (Exception e) { LOG.log(Level.SEVERE, "Error while starting the FitNesse socket service", e); } return false; } public void stop() throws IOException { if (theService != null) { theService.close(); theService = null; } } public boolean isRunning() { return theService != null; } public void executeSingleCommand(String command, OutputStream out) throws Exception { Request request = new MockRequestBuilder(command).noChunk().build(); FitNesseExpediter expediter = new FitNesseExpediter(new MockSocket(), context); Response response = expediter.createGoodResponse(request); if (response.getStatus() != 200){ throw new Exception("error loading page: " + response.getStatus()); } response.withoutHttpHeaders(); MockResponseSender sender = new MockResponseSender(out); sender.doSending(response); } }
src/fitnesse/FitNesse.java
// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse; import fitnesse.http.MockRequestBuilder; import fitnesse.http.MockResponseSender; import fitnesse.http.Request; import fitnesse.http.Response; import fitnesse.socketservice.SocketFactory; import fitnesse.socketservice.SocketService; import fitnesse.util.MockSocket; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.BindException; import java.net.ServerSocket; import java.util.logging.Level; import java.util.logging.Logger; public class FitNesse { private static final Logger LOG = Logger.getLogger(FitNesse.class.getName()); private final FitNesseContext context; private boolean makeDirs = true; private volatile SocketService theService; public FitNesse(FitNesseContext context) { this.context = context; } public FitNesse dontMakeDirs() { makeDirs = false; return this; } private void establishRequiredDirectories() { establishDirectory(context.getRootPagePath()); establishDirectory(context.getRootPagePath() + "/files"); } private static void establishDirectory(String path) { File filesDir = new File(path); if (!filesDir.exists()) filesDir.mkdir(); } public static void main(String[] args) throws Exception { System.out.println("DEPRECATED: use java -jar fitnesse.jar or java -cp fitnesse.jar fitnesseMain.FitNesseMain"); Class<?> mainClass = Class.forName("fitnesseMain.FitNesseMain"); Method mainMethod = mainClass.getMethod("main", String[].class); mainMethod.invoke(null, new Object[]{args}); } public boolean start() { if (makeDirs) { establishRequiredDirectories(); } try { if (context.port > 0) { ServerSocket serverSocket = context.useHTTPS ? SocketFactory.createSslServerSocket(context.port, context.sslClientAuth, context.sslParameterClassName) : SocketFactory.createServerSocket(context.port); theService = new SocketService(new FitNesseServer(context), false, serverSocket); } return true; } catch (BindException e) { LOG.severe("FitNesse cannot be started..."); LOG.severe("Port " + context.port + " is already in use."); LOG.severe("Use the -p <port#> command line argument to use a different port."); } catch (Exception e) { LOG.log(Level.SEVERE, "Error while starting the FitNesse socket service", e); } return false; } public void stop() throws IOException { if (theService != null) { theService.close(); theService = null; } } public boolean isRunning() { return theService != null; } public void executeSingleCommand(String command, OutputStream out) throws Exception { Request request = new MockRequestBuilder(command).noChunk().build(); FitNesseExpediter expediter = new FitNesseExpediter(new MockSocket(), context); Response response = expediter.createGoodResponse(request); if (response.getStatus() != 200){ throw new Exception("error loading page: " + response.getStatus()); } response.withoutHttpHeaders(); MockResponseSender sender = new MockResponseSender(out); sender.doSending(response); } }
Remove deprecated fitnesse.FitNesse.main().
src/fitnesse/FitNesse.java
Remove deprecated fitnesse.FitNesse.main().
<ide><path>rc/fitnesse/FitNesse.java <ide> filesDir.mkdir(); <ide> } <ide> <del> public static void main(String[] args) throws Exception { <del> System.out.println("DEPRECATED: use java -jar fitnesse.jar or java -cp fitnesse.jar fitnesseMain.FitNesseMain"); <del> Class<?> mainClass = Class.forName("fitnesseMain.FitNesseMain"); <del> Method mainMethod = mainClass.getMethod("main", String[].class); <del> mainMethod.invoke(null, new Object[]{args}); <del> } <del> <ide> public boolean start() { <ide> if (makeDirs) { <ide> establishRequiredDirectories();
Java
mit
25a29b39ae2dac4b10d66011552c4caf060e7b8a
0
Nunnery/MythicDrops
package net.nunnerycode.bukkit.mythicdrops.spawning; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.EntityDyingEvent; import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; import net.nunnerycode.bukkit.mythicdrops.items.MythicDropBuilder; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.CustomItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.EntityUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; public final class ItemSpawningListener implements Listener { private MythicDrops mythicDrops; public ItemSpawningListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.LOWEST) public void onCreatureSpawnEventLowest(CreatureSpawnEvent event) { if (mythicDrops.getConfigSettings().isBlankMobSpawnEnabled()) { if (event.getEntity() instanceof Skeleton) { event.getEntity().getEquipment().clear(); if (mythicDrops.getConfigSettings().isBlankMobSpawnSkeletonsSpawnWithBows()) { event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); } } else { event.getEntity().getEquipment().clear(); } } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getConfigSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getConfigSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getConfigSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } if (event.getEntity().getLocation().getY() > mythicDrops.getConfigSettings().getSpawnHeightLimit(event.getEntity ().getWorld().getName())) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); } @EventHandler(priority = EventPriority.HIGHEST) public void onCreatureSpawnEvent(CreatureSpawnEvent event) { if (event.isCancelled()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getConfigSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getConfigSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getConfigSettings().isPreventSpawner()) { return; } if (mythicDrops.getConfigSettings().getSpawnHeightLimit(event.getEntity().getWorld().getName()) <= event .getEntity().getLocation().getY()) { return; } double chance = mythicDrops.getConfigSettings().getGlobalSpawnChance() * mythicDrops.getConfigSettings() .getEntityTypeChanceToSpawn(event.getEntityType()); if (mythicDrops.getConfigSettings().isOnlyCustomItemsSpawn()) { if (mythicDrops.getConfigSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getConfigSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; continue; } break; } } return; } if (mythicDrops.getConfigSettings().getEntityTypeChanceToSpawn(event.getEntityType()) <= 0 && mythicDrops.getConfigSettings().getEntityTypeTiers(event.getEntityType()).isEmpty()) { return; } for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { Tier tier = getTier("*", event.getEntity()); if (tier == null) { continue; } try { EntityUtil.equipEntity(event.getEntity(), new MythicDropBuilder().inWorld(event.getEntity() .getWorld()).useDurability(true).withTier(tier).withItemGenerationReason (ItemGenerationReason.MONSTER_SPAWN).build()); } catch (Exception e) { continue; } chance *= 0.5; continue; } break; } if (mythicDrops.getConfigSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getConfigSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; continue; } break; } } } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Player || event.getEntity().getLastDamageCause() == null || event.getEntity() .getLastDamageCause() .isCancelled()) { return; } EntityDamageEvent.DamageCause damageCause = event.getEntity().getLastDamageCause().getCause(); if (damageCause == EntityDamageEvent.DamageCause.CONTACT || damageCause == EntityDamageEvent.DamageCause .SUFFOCATION || damageCause == EntityDamageEvent.DamageCause.FALL || damageCause == EntityDamageEvent .DamageCause.FIRE_TICK || damageCause == EntityDamageEvent.DamageCause.MELTING || damageCause == EntityDamageEvent.DamageCause.LAVA || damageCause == EntityDamageEvent.DamageCause.DROWNING || damageCause == EntityDamageEvent.DamageCause.BLOCK_EXPLOSION || damageCause == EntityDamageEvent .DamageCause.BLOCK_EXPLOSION || damageCause == EntityDamageEvent.DamageCause.VOID || damageCause == EntityDamageEvent.DamageCause.LIGHTNING || damageCause == EntityDamageEvent.DamageCause.SUICIDE || damageCause == EntityDamageEvent.DamageCause.STARVATION || damageCause == EntityDamageEvent .DamageCause.WITHER || damageCause == EntityDamageEvent.DamageCause.FALLING_BLOCK || damageCause == EntityDamageEvent.DamageCause.CUSTOM) { return; } List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); for (ItemStack is : array) { if (is == null || is.getType() == Material.AIR) { continue; } if (!is.hasItemMeta()) { continue; } CustomItem ci; try { ci = CustomItemUtil.getCustomItemFromItemStack(is); } catch (NullPointerException e) { ci = null; } if (ci != null) { if (RandomUtils.nextDouble() < ci.getChanceToDropOnDeath()) { newDrops.add(ci.toItemStack()); continue; } } Tier tier = TierUtil.getTierFromItemStack(is, mythicDrops.getConfigSettings().getEntityTypeTiers(event.getEntityType())); if (tier == null) { continue; } if (RandomUtils.nextDouble() < getTierDropChance(tier, event.getEntity().getWorld().getName())) { ItemStack newItemStack = is.getData().toItemStack(is.getAmount()); newItemStack.setItemMeta(is.getItemMeta().clone()); short minimumDurability = (short) (is.getType().getMaxDurability() - is.getType().getMaxDurability() * Math.max(tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); short maximumDurability = (short) (is.getType().getMaxDurability() - is.getType().getMaxDurability() * Math.min(tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); if (!(is.getDurability() <= maximumDurability && is.getDurability() >= minimumDurability)) { newItemStack.setDurability(ItemStackUtil.getDurabilityForMaterial(is.getType(), tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); } // newItemStack.addUnsafeEnchantments(is.getEnchantments()); newDrops.add(newItemStack); } } EntityDyingEvent ede = new EntityDyingEvent(event.getEntity(), array, newDrops); Bukkit.getPluginManager().callEvent(ede); Location location = event.getEntity().getLocation(); for (ItemStack itemstack : ede.getEquipmentDrops()) { if (itemstack.getData().getItemTypeId() == 0) { continue; } location.getWorld().dropItemNaturally(location, itemstack); } } private double getTierDropChance(Tier t, String worldName) { if (t.getWorldDropChanceMap().containsKey(worldName)) { return t.getWorldDropChanceMap().get(worldName); } if (t.getWorldDropChanceMap().containsKey("default")) { return t.getWorldDropChanceMap().get("default"); } return 1.0; } private Tier getTier(String tierName, LivingEntity livingEntity) { Tier tier; if (tierName.equals("*")) { tier = TierUtil.randomTierWithChance(mythicDrops.getConfigSettings().getEntityTypeTiers (livingEntity.getType())); if (tier == null) { tier = TierUtil.randomTierWithChance(mythicDrops.getConfigSettings().getEntityTypeTiers (livingEntity.getType())); } } else { tier = TierMap.getInstance().get(tierName.toLowerCase()); if (tier == null) { tier = TierMap.getInstance().get(tierName); } } return tier; } }
MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java
package net.nunnerycode.bukkit.mythicdrops.spawning; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.EntityDyingEvent; import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; import net.nunnerycode.bukkit.mythicdrops.items.MythicDropBuilder; import net.nunnerycode.bukkit.mythicdrops.tiers.TierMap; import net.nunnerycode.bukkit.mythicdrops.utils.CustomItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.EntityUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; public final class ItemSpawningListener implements Listener { private MythicDrops mythicDrops; public ItemSpawningListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.LOWEST) public void onCreatureSpawnEventLowest(CreatureSpawnEvent event) { if (mythicDrops.getConfigSettings().isBlankMobSpawnEnabled()) { if (event.getEntity() instanceof Skeleton) { event.getEntity().getEquipment().clear(); if (mythicDrops.getConfigSettings().isBlankMobSpawnSkeletonsSpawnWithBows()) { event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); } } else { event.getEntity().getEquipment().clear(); } } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getConfigSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getConfigSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getConfigSettings().isPreventSpawner()) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } if (event.getEntity().getLocation().getY() > mythicDrops.getConfigSettings().getSpawnHeightLimit(event.getEntity ().getWorld().getName())) { event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); return; } event.getEntity().setCanPickupItems(mythicDrops.getConfigSettings().isCanMobsPickUpEquipment()); } @EventHandler(priority = EventPriority.HIGHEST) public void onCreatureSpawnEvent(CreatureSpawnEvent event) { if (event.isCancelled()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getConfigSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getConfigSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getConfigSettings().isPreventSpawner()) { return; } if (mythicDrops.getConfigSettings().getSpawnHeightLimit(event.getEntity().getWorld().getName()) <= event .getEntity().getLocation().getY()) { return; } double chance = mythicDrops.getConfigSettings().getGlobalSpawnChance() * mythicDrops.getConfigSettings() .getEntityTypeChanceToSpawn(event.getEntityType()); if (mythicDrops.getConfigSettings().isOnlyCustomItemsSpawn()) { if (mythicDrops.getConfigSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getConfigSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; continue; } break; } } return; } if (mythicDrops.getConfigSettings().getEntityTypeChanceToSpawn(event.getEntityType()) <= 0 && mythicDrops.getConfigSettings().getEntityTypeTiers(event.getEntityType()).isEmpty()) { return; } for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { Tier tier = getTier("*", event.getEntity()); if (tier == null) { continue; } try { EntityUtil.equipEntity(event.getEntity(), new MythicDropBuilder().inWorld(event.getEntity() .getWorld()).useDurability(true).withTier(tier).build()); } catch (Exception e) { continue; } chance *= 0.5; continue; } break; } if (mythicDrops.getConfigSettings().isCustomItemsSpawn() && RandomUtils.nextDouble() < mythicDrops .getConfigSettings().getCustomItemSpawnChance() && !CustomItemMap.getInstance().isEmpty()) { for (int i = 0; i < 5; i++) { if (RandomUtils.nextDouble() < chance) { EntityUtil.equipEntity(event.getEntity(), CustomItemMap.getInstance().getRandomWithChance() .toItemStack()); chance *= 0.5; continue; } break; } } } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Player || event.getEntity().getLastDamageCause() == null || event.getEntity() .getLastDamageCause() .isCancelled()) { return; } EntityDamageEvent.DamageCause damageCause = event.getEntity().getLastDamageCause().getCause(); if (damageCause == EntityDamageEvent.DamageCause.CONTACT || damageCause == EntityDamageEvent.DamageCause .SUFFOCATION || damageCause == EntityDamageEvent.DamageCause.FALL || damageCause == EntityDamageEvent .DamageCause.FIRE_TICK || damageCause == EntityDamageEvent.DamageCause.MELTING || damageCause == EntityDamageEvent.DamageCause.LAVA || damageCause == EntityDamageEvent.DamageCause.DROWNING || damageCause == EntityDamageEvent.DamageCause.BLOCK_EXPLOSION || damageCause == EntityDamageEvent .DamageCause.BLOCK_EXPLOSION || damageCause == EntityDamageEvent.DamageCause.VOID || damageCause == EntityDamageEvent.DamageCause.LIGHTNING || damageCause == EntityDamageEvent.DamageCause.SUICIDE || damageCause == EntityDamageEvent.DamageCause.STARVATION || damageCause == EntityDamageEvent .DamageCause.WITHER || damageCause == EntityDamageEvent.DamageCause.FALLING_BLOCK || damageCause == EntityDamageEvent.DamageCause.CUSTOM) { return; } List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); for (ItemStack is : array) { if (is == null || is.getType() == Material.AIR) { continue; } if (!is.hasItemMeta()) { continue; } CustomItem ci; try { ci = CustomItemUtil.getCustomItemFromItemStack(is); } catch (NullPointerException e) { ci = null; } if (ci != null) { if (RandomUtils.nextDouble() < ci.getChanceToDropOnDeath()) { newDrops.add(ci.toItemStack()); continue; } } Tier tier = TierUtil.getTierFromItemStack(is, mythicDrops.getConfigSettings().getEntityTypeTiers(event.getEntityType())); if (tier == null) { continue; } if (RandomUtils.nextDouble() < getTierDropChance(tier, event.getEntity().getWorld().getName())) { ItemStack newItemStack = is.getData().toItemStack(is.getAmount()); newItemStack.setItemMeta(is.getItemMeta().clone()); short minimumDurability = (short) (is.getType().getMaxDurability() - is.getType().getMaxDurability() * Math.max(tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); short maximumDurability = (short) (is.getType().getMaxDurability() - is.getType().getMaxDurability() * Math.min(tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); if (!(is.getDurability() <= maximumDurability && is.getDurability() >= minimumDurability)) { newItemStack.setDurability(ItemStackUtil.getDurabilityForMaterial(is.getType(), tier.getMinimumDurabilityPercentage(), tier.getMaximumDurabilityPercentage())); } // newItemStack.addUnsafeEnchantments(is.getEnchantments()); newDrops.add(newItemStack); } } EntityDyingEvent ede = new EntityDyingEvent(event.getEntity(), array, newDrops); Bukkit.getPluginManager().callEvent(ede); Location location = event.getEntity().getLocation(); for (ItemStack itemstack : ede.getEquipmentDrops()) { if (itemstack.getData().getItemTypeId() == 0) { continue; } location.getWorld().dropItemNaturally(location, itemstack); } } private double getTierDropChance(Tier t, String worldName) { if (t.getWorldDropChanceMap().containsKey(worldName)) { return t.getWorldDropChanceMap().get(worldName); } if (t.getWorldDropChanceMap().containsKey("default")) { return t.getWorldDropChanceMap().get("default"); } return 1.0; } private Tier getTier(String tierName, LivingEntity livingEntity) { Tier tier; if (tierName.equals("*")) { tier = TierUtil.randomTierWithChance(mythicDrops.getConfigSettings().getEntityTypeTiers (livingEntity.getType())); if (tier == null) { tier = TierUtil.randomTierWithChance(mythicDrops.getConfigSettings().getEntityTypeTiers (livingEntity.getType())); } } else { tier = TierMap.getInstance().get(tierName.toLowerCase()); if (tier == null) { tier = TierMap.getInstance().get(tierName); } } return tier; } }
making sure that items can spawn with sockets
MythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java
making sure that items can spawn with sockets
<ide><path>ythicDrops/src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java <ide> import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; <ide> import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; <ide> import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; <add>import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; <ide> import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; <ide> import net.nunnerycode.bukkit.mythicdrops.events.EntityDyingEvent; <ide> import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; <ide> } <ide> try { <ide> EntityUtil.equipEntity(event.getEntity(), new MythicDropBuilder().inWorld(event.getEntity() <del> .getWorld()).useDurability(true).withTier(tier).build()); <add> .getWorld()).useDurability(true).withTier(tier).withItemGenerationReason <add> (ItemGenerationReason.MONSTER_SPAWN).build()); <ide> } catch (Exception e) { <ide> continue; <ide> }
Java
apache-2.0
6e98ee86e7df155eeb0e4e65e7b5c1ea4d0c5e15
0
codemucker/codemucker-lang
/* * Copyright 2011 Bert van Brakel * * 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.bertvanbrakel.lang; import java.util.Collection; public final class Check { public static void checkFailed(String msg){ throw new IllegalArgumentException(msg); } /** * Assert the given string is not null or blank where blank means the * trimmed string is zero length * * @param attName * @param value * * @throws NullPointerException * if the value is null * @throws IllegalArgumentException * if the value is blank (when trimmed length is zero) */ public static void checkNotBlank(final String attName, final String value) throws NullPointerException, IllegalArgumentException { if (value == null) { throw new NullPointerException(String.format( "Check failed. Expected non null value for '%s'", attName)); } else if (value.trim().length() == 0) { throw new IllegalArgumentException(String.format( "Check failed. Expected non blank value for '%s'", attName)); } } /** * Assert the given string is not null or zero length. Does not trim the * string, see {@link #checkNotBlank(String, String)} instead * * @param attName * @param value * * @throws NullPointerException * if the value is null * @throws IllegalArgumentException * if the value is empty (zero length) */ public static void checkNotEmpty(final String attName, final String value) throws NullPointerException, IllegalArgumentException { if (value == null) { throw new NullPointerException(String.format( "Check failed. Expected non null value for '%s'", attName)); } else if (value.length() == 0) { throw new IllegalArgumentException(String.format( "Check failed. Expected non empty value for '%s'", attName)); } } /** * Assert that the attribute with the given name is not null * * @param attName * @param value * * @throws NullPointerException * if the value is null */ public static <T> T checkNotNull(final String attName, final T value) throws NullPointerException { if (value == null) { throw new NullPointerException(String.format( "Check failed. Expected non null value for '%s'", attName)); } return value; } /** * Assert the attribute with the given name and value is not null and that * it starts with the given string * * @param attName * @param value * @param expectStartsWith * * @throws NullPointerException * if the value is null * @throws IllegalArgumentException * if the value is */ public static void checkStartsWith(final String attName, final String value, final String expectStartsWith) throws NullPointerException, IllegalArgumentException { checkNotNull(attName, value); if (!value.startsWith(expectStartsWith)) { throw new IllegalArgumentException( String.format( "Check failed. Expected '%s' to start with '%s' but was '%s'", attName, expectStartsWith, value)); } } /** * Assert the list with the given name is not null and that all items in the * list are non null * * @param attName * @param list * * @throws NullPointerException * if the list is null * @throws IllegalArgumentException * if any of the items are null. Message includes position of item which was null */ public static void checkNoNullItems(final String attName, final Collection<?> list) throws NullPointerException, IllegalArgumentException { checkNotNull(attName, list); int position = 0; for (final Object item : list) { if (item == null) { throw new IllegalArgumentException( String.format( "Check failed. Expected '%s' to not have any null items, but item %d (zero-based) was null", attName, position)); } position++; } } /** * Assert the array with the given name is not null and that all items in the * array are non null * * @param attName * @param array * * @throws NullPointerException * if the array is null * @throws IllegalArgumentException * if any of the items are null. Message includes position of item which was null */ public static void checkNoNullItems(final String attName, final Object[] array) throws NullPointerException, IllegalArgumentException { checkNotNull(attName, array); for (int i = 0; i < array.length; i++) { if (array[i] == null) { throw new IllegalArgumentException( String.format( "Check failed. Expected '%s' to not have any null items, but item %d (zero-based) was null", attName, i)); } } } public static void checkTrue(final String attName, final Object attValue, final boolean expression, final String msg) { if (!expression) { throw new IllegalArgumentException(String.format( "Check failed. Expected '%s' to be %s but was '%s'", attName, msg, attValue)); } } }
src/main/java/com/bertvanbrakel/lang/Check.java
/* * Copyright 2011 Bert van Brakel * * 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.bertvanbrakel.lang; import java.util.Collection; public final class Check { /** * Assert the given string is not null or blank where blank means the * trimmed string is zero length * * @param attName * @param value * * @throws NullPointerException * if the value is null * @throws IllegalArgumentException * if the value is blank (when trimmed length is zero) */ public static void checkNotBlank(final String attName, final String value) throws NullPointerException, IllegalArgumentException { if (value == null) { throw new NullPointerException(String.format( "Check failed. Expected non null value for '%s'", attName)); } else if (value.trim().length() == 0) { throw new IllegalArgumentException(String.format( "Check failed. Expected non blank value for '%s'", attName)); } } /** * Assert the given string is not null or zero length. Does not trim the * string, see {@link #checkNotBlank(String, String)} instead * * @param attName * @param value * * @throws NullPointerException * if the value is null * @throws IllegalArgumentException * if the value is empty (zero length) */ public static void checkNotEmpty(final String attName, final String value) throws NullPointerException, IllegalArgumentException { if (value == null) { throw new NullPointerException(String.format( "Check failed. Expected non null value for '%s'", attName)); } else if (value.length() == 0) { throw new IllegalArgumentException(String.format( "Check failed. Expected non empty value for '%s'", attName)); } } /** * Assert that the attribute with the given name is not null * * @param attName * @param value * * @throws NullPointerException * if the value is null */ public static <T> T checkNotNull(final String attName, final T value) throws NullPointerException { if (value == null) { throw new NullPointerException(String.format( "Check failed. Expected non null value for '%s'", attName)); } return value; } /** * Assert the attribute with the given name and value is not null and that * it starts with the given string * * @param attName * @param value * @param expectStartsWith * * @throws NullPointerException * if the value is null * @throws IllegalArgumentException * if the value is */ public static void checkStartsWith(final String attName, final String value, final String expectStartsWith) throws NullPointerException, IllegalArgumentException { checkNotNull(attName, value); if (!value.startsWith(expectStartsWith)) { throw new IllegalArgumentException( String.format( "Check failed. Expected '%s' to start with '%s' but was '%s'", attName, expectStartsWith, value)); } } /** * Assert the list with the given name is not null and that all items in the * list are non null * * @param attName * @param list * * @throws NullPointerException * if the list is null * @throws IllegalArgumentException * if any of the items are null. Message includes position of item which was null */ public static void checkNoNullItems(final String attName, final Collection<?> list) throws NullPointerException, IllegalArgumentException { checkNotNull(attName, list); int position = 0; for (final Object item : list) { if (item == null) { throw new IllegalArgumentException( String.format( "Check failed. Expected '%s' to not have any null items, but item %d (zero-based) was null", attName, position)); } position++; } } /** * Assert the array with the given name is not null and that all items in the * array are non null * * @param attName * @param array * * @throws NullPointerException * if the array is null * @throws IllegalArgumentException * if any of the items are null. Message includes position of item which was null */ public static void checkNoNullItems(final String attName, final Object[] array) throws NullPointerException, IllegalArgumentException { checkNotNull(attName, array); for (int i = 0; i < array.length; i++) { if (array[i] == null) { throw new IllegalArgumentException( String.format( "Check failed. Expected '%s' to not have any null items, but item %d (zero-based) was null", attName, i)); } } } public static void checkTrue(final String attName, final Object attValue, final boolean b, final String msg) { if (!b) { throw new IllegalArgumentException(String.format( "Check failed. Expected '%s' to be %s but was '%s'", attName, msg, attValue)); } } }
add some more check.. methods on CHeck
src/main/java/com/bertvanbrakel/lang/Check.java
add some more check.. methods on CHeck
<ide><path>rc/main/java/com/bertvanbrakel/lang/Check.java <ide> import java.util.Collection; <ide> <ide> public final class Check { <del> <add> <add> public static void checkFailed(String msg){ <add> throw new IllegalArgumentException(msg); <add> } <add> <ide> /** <ide> * Assert the given string is not null or blank where blank means the <ide> * trimmed string is zero length <ide> } <ide> } <ide> <del> public static void checkTrue(final String attName, final Object attValue, final boolean b, <add> public static void checkTrue(final String attName, final Object attValue, final boolean expression, <ide> final String msg) { <del> if (!b) { <add> if (!expression) { <ide> throw new IllegalArgumentException(String.format( <ide> "Check failed. Expected '%s' to be %s but was '%s'", <ide> attName, msg, attValue));
JavaScript
agpl-3.0
69480439c1204760ac6aa9cc8b713b56c4f5b513
0
lustersir/MuPDF,hackqiang/mupdf,seagullua/MuPDF,wzhsunn/mupdf,issuestand/mupdf,fluks/mupdf-x11-bookmarks,FabriceSalvaire/mupdf-v1.3,muennich/mupdf,derek-watson/mupdf,geetakaur/NewApps,wild0/opened_mupdf,ArtifexSoftware/mupdf,FabriceSalvaire/mupdf-cmake,robamler/mupdf-nacl,tophyr/mupdf,issuestand/mupdf,tophyr/mupdf,PuzzleFlow/mupdf,PuzzleFlow/mupdf,samturneruk/mupdf_secure_android,robamler/mupdf-nacl,hackqiang/mupdf,sebras/mupdf,zeniko/mupdf,wzhsunn/mupdf,geetakaur/NewApps,ylixir/mupdf,kobolabs/mupdf,asbloomf/mupdf,fluks/mupdf-x11-bookmarks,crow-misia/mupdf,hjiayz/forkmupdf,clchiou/mupdf,hxx0215/MuPDFMirror,fluks/mupdf-x11-bookmarks,wild0/opened_mupdf,asbloomf/mupdf,TamirEvan/mupdf,muennich/mupdf,tophyr/mupdf,TamirEvan/mupdf,nqv/mupdf,andyhan/mupdf,wzhsunn/mupdf,loungeup/mupdf,wild0/opened_mupdf,poor-grad-student/mupdf,hjiayz/forkmupdf,samturneruk/mupdf_secure_android,ArtifexSoftware/mupdf,tophyr/mupdf,github201407/MuPDF,loungeup/mupdf,hjiayz/forkmupdf,nqv/mupdf,xiangxw/mupdf,wzhsunn/mupdf,ccxvii/mupdf,fluks/mupdf-x11-bookmarks,lustersir/MuPDF,crow-misia/mupdf,Kalp695/mupdf,zeniko/mupdf,ccxvii/mupdf,michaelcadilhac/pdfannot,TamirEvan/mupdf,TamirEvan/mupdf,fluks/mupdf-x11-bookmarks,crow-misia/mupdf,clchiou/mupdf,seagullua/MuPDF,asbloomf/mupdf,ccxvii/mupdf,hxx0215/MuPDFMirror,ylixir/mupdf,ziel/mupdf,robamler/mupdf-nacl,sebras/mupdf,lustersir/MuPDF,seagullua/MuPDF,michaelcadilhac/pdfannot,xiangxw/mupdf,derek-watson/mupdf,poor-grad-student/mupdf,tophyr/mupdf,FabriceSalvaire/mupdf-cmake,flipstudio/MuPDF,issuestand/mupdf,FabriceSalvaire/mupdf-cmake,asbloomf/mupdf,zeniko/mupdf,ziel/mupdf,knielsen/mupdf,isavin/humblepdf,knielsen/mupdf,isavin/humblepdf,flipstudio/MuPDF,michaelcadilhac/pdfannot,FabriceSalvaire/mupdf-v1.3,hxx0215/MuPDFMirror,github201407/MuPDF,clchiou/mupdf,clchiou/mupdf,Kalp695/mupdf,samturneruk/mupdf_secure_android,cgogolin/penandpdf,hxx0215/MuPDFMirror,crow-misia/mupdf,hackqiang/mupdf,ArtifexSoftware/mupdf,PuzzleFlow/mupdf,ylixir/mupdf,samturneruk/mupdf_secure_android,sebras/mupdf,Kalp695/mupdf,muennich/mupdf,robamler/mupdf-nacl,seagullua/MuPDF,Kalp695/mupdf,tribals/mupdf,ArtifexSoftware/mupdf,lolo32/mupdf-mirror,ccxvii/mupdf,ziel/mupdf,lolo32/mupdf-mirror,wild0/opened_mupdf,michaelcadilhac/pdfannot,tribals/mupdf,derek-watson/mupdf,flipstudio/MuPDF,kobolabs/mupdf,cgogolin/penandpdf,kobolabs/mupdf,hackqiang/mupdf,hackqiang/mupdf,benoit-pierre/mupdf,clchiou/mupdf,nqv/mupdf,FabriceSalvaire/mupdf-v1.3,Kalp695/mupdf,PuzzleFlow/mupdf,cgogolin/penandpdf,knielsen/mupdf,crow-misia/mupdf,FabriceSalvaire/mupdf-cmake,tophyr/mupdf,fluks/mupdf-x11-bookmarks,benoit-pierre/mupdf,geetakaur/NewApps,sebras/mupdf,issuestand/mupdf,TamirEvan/mupdf,PuzzleFlow/mupdf,flipstudio/MuPDF,isavin/humblepdf,FabriceSalvaire/mupdf-cmake,lamemate/mupdf,isavin/humblepdf,github201407/MuPDF,cgogolin/penandpdf,Kalp695/mupdf,ylixir/mupdf,hxx0215/MuPDFMirror,knielsen/mupdf,isavin/humblepdf,ziel/mupdf,MokiMobility/muPDF,lolo32/mupdf-mirror,Kalp695/mupdf,MokiMobility/muPDF,MokiMobility/muPDF,seagullua/MuPDF,samturneruk/mupdf_secure_android,geetakaur/NewApps,geetakaur/NewApps,PuzzleFlow/mupdf,nqv/mupdf,kobolabs/mupdf,nqv/mupdf,FabriceSalvaire/mupdf-v1.3,seagullua/MuPDF,poor-grad-student/mupdf,knielsen/mupdf,kobolabs/mupdf,lustersir/MuPDF,issuestand/mupdf,lolo32/mupdf-mirror,ylixir/mupdf,lolo32/mupdf-mirror,knielsen/mupdf,loungeup/mupdf,TamirEvan/mupdf,isavin/humblepdf,derek-watson/mupdf,robamler/mupdf-nacl,xiangxw/mupdf,benoit-pierre/mupdf,muennich/mupdf,geetakaur/NewApps,loungeup/mupdf,ziel/mupdf,lamemate/mupdf,michaelcadilhac/pdfannot,ArtifexSoftware/mupdf,github201407/MuPDF,FabriceSalvaire/mupdf-v1.3,derek-watson/mupdf,lustersir/MuPDF,hjiayz/forkmupdf,benoit-pierre/mupdf,github201407/MuPDF,lustersir/MuPDF,wild0/opened_mupdf,benoit-pierre/mupdf,sebras/mupdf,lamemate/mupdf,MokiMobility/muPDF,muennich/mupdf,samturneruk/mupdf_secure_android,xiangxw/mupdf,asbloomf/mupdf,flipstudio/MuPDF,lolo32/mupdf-mirror,wild0/opened_mupdf,sebras/mupdf,clchiou/mupdf,lamemate/mupdf,ylixir/mupdf,lamemate/mupdf,xiangxw/mupdf,hxx0215/MuPDFMirror,poor-grad-student/mupdf,ArtifexSoftware/mupdf,ziel/mupdf,loungeup/mupdf,ccxvii/mupdf,isavin/humblepdf,issuestand/mupdf,robamler/mupdf-nacl,wild0/opened_mupdf,zeniko/mupdf,asbloomf/mupdf,wzhsunn/mupdf,derek-watson/mupdf,kobolabs/mupdf,xiangxw/mupdf,andyhan/mupdf,MokiMobility/muPDF,andyhan/mupdf,muennich/mupdf,hjiayz/forkmupdf,poor-grad-student/mupdf,tribals/mupdf,FabriceSalvaire/mupdf-cmake,poor-grad-student/mupdf,flipstudio/MuPDF,zeniko/mupdf,MokiMobility/muPDF,tribals/mupdf,lolo32/mupdf-mirror,loungeup/mupdf,benoit-pierre/mupdf,lamemate/mupdf,cgogolin/penandpdf,nqv/mupdf,FabriceSalvaire/mupdf-v1.3,andyhan/mupdf,tribals/mupdf,tribals/mupdf,TamirEvan/mupdf,hjiayz/forkmupdf,kobolabs/mupdf,PuzzleFlow/mupdf,andyhan/mupdf,crow-misia/mupdf,michaelcadilhac/pdfannot,ArtifexSoftware/mupdf,wzhsunn/mupdf,hackqiang/mupdf,ArtifexSoftware/mupdf,zeniko/mupdf,andyhan/mupdf,xiangxw/mupdf,cgogolin/penandpdf,TamirEvan/mupdf,ccxvii/mupdf,muennich/mupdf,fluks/mupdf-x11-bookmarks,github201407/MuPDF
var MuPDF = new Array(); MuPDF.monthName = ['January','February','March','April','May','June','July','August','September','October','November','December']; MuPDF.dayName = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; MuPDF.shortMonthName = new Array(); for (var i = 0; i < MuPDF.monthName.length; i++) MuPDF.shortMonthName.push(MuPDF.monthName[i].substr(0,3)); MuPDF.monthPattern = new RegExp(); MuPDF.monthPattern.compile('('+MuPDF.shortMonthName.join('|')+')'); MuPDF.padZeros = function(num, places) { var s = num.toString(); if (s.length < places) s = new Array(places-s.length+1).join('0') + s; return s; } MuPDF.convertCase = function(str,cmd) { switch (cmd) { case '>': return str.toUpperCase(); case '<': return str.toLowerCase(); default: return str; } } var border = new Array(); border.s = "Solid"; border.d = "Dashed"; border.b = "Beveled"; border.i = "Inset"; border.u = "Underline"; var color = new Array(); color.transparent = [ "T" ]; color.black = [ "G", 0]; color.white = [ "G", 1]; color.red = [ "RGB", 1,0,0 ]; color.green = [ "RGB", 0,1,0 ]; color.blue = [ "RGB", 0,0,1 ]; color.cyan = [ "CMYK", 1,0,0,0 ]; color.magenta = [ "CMYK", 0,1,0,0 ]; color.yellow = [ "CMYK", 0,0,1,0 ]; color.dkGray = [ "G", 0.25]; color.gray = [ "G", 0.5]; color.ltGray = [ "G", 0.75]; var util = new Array(); util.printd = function(fmt, d) { var regexp = /(m+|d+|y+|H+|h+|M+|s+|t+|[^mdyHhMst]+)/g; var res = ''; if (!d) return null; var tokens = fmt.match(regexp); for (var i = 0; i < tokens.length; i++) { switch(tokens[i]) { case 'mmmm': res += MuPDF.monthName[d.getMonth()]; break; case 'mmm': res += MuPDF.monthName[d.getMonth()].substr(0,3); break; case 'mm': res += MuPDF.padZeros(d.getMonth()+1, 2); break; case 'm': res += d.getMonth()+1; break; case 'dddd': res += MuPDF.dayName[d.getDay()]; break; case 'ddd': res += MuPDF.dayName[d.getDay()].substr(0,3); break; case 'dd': res += MuPDF.padZeros(d.getDate(), 2); break; case 'd': res += d.getDate(); break; case 'yyyy': res += d.getFullYear(); break; case 'yy': res += d.getFullYear()%100; break; case 'HH': res += MuPDF.padZeros(d.getHours(), 2); break; case 'H': res += d.getHours(); break; case 'hh': res += MuPDF.padZeros((d.getHours()+11)%12+1, 2); break; case 'h': res += (d.getHours()+11)%12+1; break; case 'MM': res += MuPDF.padZeros(d.getMinutes(), 2); break; case 'M': res += d.getMinutes(); break; case 'ss': res += MuPDF.padZeros(d.getSeconds(), 2); break; case 's': res += d.getSeconds(); break; case 'tt': res += d.getHours() < 12 ? 'am' : 'pm'; break; case 't': res += d.getHours() < 12 ? 'a' : 'p'; break; default: res += tokens[i]; } } return res; } util.printx = function(fmt, val) { var cs = '='; var res = ''; var i = 0; var m; while (i < fmt.length) { switch (fmt.charAt(i)) { case '\\': i++; if (i >= fmt.length) return res; res += fmt.charAt(i); break; case 'X': m = val.match(/\w/); if (!m) return res; res += MuPDF.convertCase(m[0],cs); val = val.replace(/^\W*\w/,''); break; case 'A': m = val.match(/[A-z]/); if (!m) return res; res += MuPDF.convertCase(m[0],cs); val = val.replace(/^[^A-z]*[A-z]/,''); break; case '9': m = val.match(/\d/); if (!m) return res; res += m[0]; val = val.replace(/^\D*\d/,''); break; case '*': res += val; val = ''; break; case '?': if (!val) return res; res += MuPDF.convertCase(val.charAt(0),cs); val = val.substr(1); break; case '=': case '>': case '<': cs = fmt.charAt(i); break; default: res += MuPDF.convertCase(fmt.charAt(i),cs); break; } i++; } return res; } function AFExtractTime(dt) { var ampm = dt.match(/(am|pm)/); dt = dt.replace(/(am|pm)/, ''); var t = dt.match(/\d{1,2}:\d{1,2}:\d{1,2}/); dt = dt.replace(/\d{1,2}:\d{1,2}:\d{1,2}/, ''); if (!t) { t = dt.match(/\d{1,2}:\d{1,2}/); dt = dt.replace(/\d{1,2}:\d{1,2}/, ''); } return [dt, t?t[0]+(ampm?ampm[0]:''):'']; } function AFParseDateOrder(fmt) { var order = ''; // Ensure all present with those not added in default order fmt += "mdy"; for (var i = 0; i < fmt.length; i++) { var c = fmt.charAt(i); if ('ymd'.indexOf(c) != -1 && order.indexOf(c) == -1) order += c; } return order; } function AFMatchMonth(d) { var m = d.match(MuPDF.monthPattern); return m ? MuPDF.shortMonthName.indexOf(m[0]) : null; } function AFParseTime(str, d) { if (!str) return d; if (!d) d = new Date(); var ampm = str.match(/(am|pm)/); var nums = str.match(/\d+/g); var hour, min, sec; if (!nums) return null; sec = 0; switch (nums.length) { case 3: sec = nums[2]; case 2: hour = nums[0]; min = nums[1]; break; default: return null; } if (ampm == 'am' && hour < 12) hour = 12 + hour; if (ampm == 'pm' && hour >= 12) hour = 0 + hour - 12; d.setHours(hour, min, sec); if (d.getHours() != hour || d.getMinutes() != min || d.getSeconds() != sec) return null; return d; } function AFParseDateEx(d, fmt) { var dt = AFExtractTime(d); var nums = dt[0].match(/\d+/g); var order = AFParseDateOrder(fmt); var text_month = AFMatchMonth(dt[0]); var dout = new Date(); var year = dout.getFullYear(); var month = dout.getMonth(); var date = dout.getDate(); dout.setHours(12,0,0); if (nums.length < 1 || nums.length > 3) return null; if (nums.length < 3 && text_month) { // Use the text month rather than one of the numbers month = text_month; order = order.replace('m',''); } order = order.substr(0, nums.length); // If year and month specified but not date then use the 1st if (order == "ym" || (order == "y" && text_month)) date = 1; for (var i = 0; i < nums.length; i++) { switch (order.charAt(i)) { case 'y': year = nums[i]; break; case 'm': month = nums[i] - 1; break; case 'd': date = nums[i]; break; } } if (year < 100) { if (fmt.search("yyyy") != -1) return null; if (year >= 50) year = 1900 + year; else if (year >= 0) year = 2000 + year; } dout.setFullYear(year, month, date); if (dout.getFullYear() != year || dout.getMonth() != month || dout.getDate() != date) return null; return AFParseTime(dt[1], dout); } function AFDate_KeystrokeEx(fmt) { if (event.willCommit && !AFParseDateEx(event.value)) event.rc = false; } function AFDate_Keystroke(index) { var formats = ['m/d','m/d/yy','mm/dd/yy','mm/yy','d-mmm','d-mmm-yy','dd-mm-yy','yy-mm-dd', 'mmm-yy','mmmm-yy','mmm d, yyyy','mmmm d, yyyy','m/d/yy h:MM tt','m/d/yy HH:MM']; AFDate_KeystrokeEx(formats[index]); } function AFDate_FormatEx(fmt) { var d = AFParseDateEx(event.value, fmt); event.value = d ? util.printd(fmt, d) : ""; } function AFDate_Format(index) { var formats = ['m/d','m/d/yy','mm/dd/yy','mm/yy','d-mmm','d-mmm-yy','dd-mm-yy','yy-mm-dd', 'mmm-yy','mmmm-yy','mmm d, yyyy','mmmm d, yyyy','m/d/yy h:MM tt','m/d/yy HH:MM']; AFDate_FormatEx(formats[index]); } function AFTime_Keystroke(index) { if (event.willCommit && !AFParseTime(event.value, null)) event.rc = false; } function AFTime_FormatEx(fmt) { var d = AFParseTime(event.value, null); event.value = d ? util.printd(fmt, d) : ''; } function AFTime_Format(index) { var formats = ['HH:MM','h:MM tt','HH:MM:ss','h:MM:ss tt']; AFTime_FormatEx(formats[index]); } function AFSpecial_Format(index) { var res; switch (index) { case 0: res = util.printx('99999', event.value); break; case 1: res = util.printx('99999-9999', event.value); break; case 2: res = util.printx('9999999999', event.value); res = util.printx(res.length >= 10 ? '(999) 999-9999' : '999-9999', event.value); break; case 3: res = util.printx('999-99-9999', event.value); break; } event.value = res ? res : ''; } function AFNumber_Keystroke(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) { if (sepStyle & 2) { if (!event.value.match(/^[+-]?\d*[,.]?\d*$/)) { event.rc = false; return; } } else { if (!event.value.match(/^[+-]?\d*\.?\d*$/)) { event.rc = false; return; } } if (event.willCommit && !event.value.match(/\d/)) event.rc = false; } function AFNumber_Format(nDec,sepStyle,negStyle,currStyle,strCurrency,bCurrencyPrepend) { var val = event.value; var fracpart; var intpart; var point = sepStyle&2 ? ',' : '.'; var separator = sepStyle&2 ? '.' : ','; if (/^\D*\./.test(val)) val = '0'+val; var groups = val.match(/\d+/g); switch (groups.length) { case 0: return; case 1: fracpart = ''; intpart = groups[0]; break; default: fracpart = groups.pop(); intpart = groups.join(''); break; } // Remove leading zeros intpart = intpart.replace(/^0*/,''); if (!intpart) intpart = '0'; if ((sepStyle & 1) == 0) { // Add the thousands sepearators: pad to length multiple of 3 with zeros, // split into 3s, join with separator, and remove the leading zeros intpart = new Array(2-(intpart.length+2)%3+1).join('0') + intpart; intpart = intpart.match(/.../g).join(separator).replace(/^0*/,''); } if (!intpart) intpart = '0'; // Adjust fractional part to correct number of decimal places fracpart += new Array(nDec+1).join('0'); fracpart = fracpart.substr(0,nDec); if (fracpart) intpart += point+fracpart; if (bCurrencyPrepend) intpart = strCurrency+intpart; else intpart += strCurrency; if (/-/.test(val)) { switch (negStyle) { case 0: intpart = '-'+intpart; break; case 1: break; case 2: case 3: intpart = '('+intpart+')'; break; } } if (negStyle&1) event.target.textColor = /-/.text(val) ? color.red : color.black; event.value = intpart; } function AFSimple_Calculate(op, list) { var res; switch (op) { case 'SUM': res = 0; break; case 'PRD': res = 1; break; case 'AVG': res = 0; break; } if (typeof list == 'string') list = list.split(/ *, */); for (var i = 0; i < list.length; i++) { var field = getField(list[i]); var value = Number(field.value); switch (op) { case 'SUM': res += value; break; case 'PRD': res *= value; break; case 'AVG': res += value; break; case 'MIN': if (i == 0 || value < res) res = value; break; case 'MAX': if (i == 0 || value > res) res = value; break; } } if (op == 'AVG') res /= list.length; event.value = res; } function AFRange_Validate(lowerCheck, lowerLimit, upperCheck, upperLimit) { if (upperCheck && event.value > upperLimit) event.rc = false; if (lowerCheck && event.value < lowerLimit) event.rc = false; }
pdf/pdf_util.js
var MuPDF = new Array(); MuPDF.monthName = ['January','February','March','April','May','June','July','August','September','October','November','December']; MuPDF.dayName = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; MuPDF.shortMonthName = new Array(); for (var i = 0; i < MuPDF.monthName.length; i++) MuPDF.shortMonthName.push(MuPDF.monthName[i].substr(0,3)); MuPDF.monthPattern = new RegExp(); MuPDF.monthPattern.compile('('+MuPDF.shortMonthName.join('|')+')'); MuPDF.padZeros = function(num, places) { var s = num.toString(); if (s.length < places) s = new Array(places-s.length+1).join('0') + s; return s; } MuPDF.convertCase = function(str,cmd) { switch (cmd) { case '>': return str.toUpperCase(); case '<': return str.toLowerCase(); default: return str; } } var border = new Array(); border.s = "Solid"; border.d = "Dashed"; border.b = "Beveled"; border.i = "Inset"; border.u = "Underline"; var color = new Array(); color.transparent = [ "T" ]; color.black = [ "G", 0]; color.white = [ "G", 1]; color.red = [ "RGB", 1,0,0 ]; color.green = [ "RGB", 0,1,0 ]; color.blue = [ "RGB", 0,0,1 ]; color.cyan = [ "CMYK", 1,0,0,0 ]; color.magenta = [ "CMYK", 0,1,0,0 ]; color.yellow = [ "CMYK", 0,0,1,0 ]; color.dkGray = [ "G", 0.25]; color.gray = [ "G", 0.5]; color.ltGray = [ "G", 0.75]; var util = new Array(); util.printd = function(fmt, d) { var regexp = /(m+|d+|y+|H+|h+|M+|s+|t+|[^mdyHhMst]+)/g; var res = ''; if (!d) return null; var tokens = fmt.match(regexp); for (var i = 0; i < tokens.length; i++) { switch(tokens[i]) { case 'mmmm': res += MuPDF.monthName[d.getMonth()]; break; case 'mmm': res += MuPDF.monthName[d.getMonth()].substr(0,3); break; case 'mm': res += MuPDF.padZeros(d.getMonth()+1, 2); break; case 'm': res += d.getMonth()+1; break; case 'dddd': res += MuPDF.dayName[d.getDay()]; break; case 'ddd': res += MuPDF.dayName[d.getDay()].substr(0,3); break; case 'dd': res += MuPDF.padZeros(d.getDate(), 2); break; case 'd': res += d.getDate(); break; case 'yyyy': res += d.getFullYear(); break; case 'yy': res += d.getFullYear()%100; break; case 'HH': res += MuPDF.padZeros(d.getHours(), 2); break; case 'H': res += d.getHours(); break; case 'hh': res += MuPDF.padZeros((d.getHours()+11)%12+1, 2); break; case 'h': res += (d.getHours()+11)%12+1; break; case 'MM': res += MuPDF.padZeros(d.getMinutes(), 2); break; case 'M': res += d.getMinutes(); break; case 'ss': res += MuPDF.padZeros(d.getSeconds(), 2); break; case 's': res += d.getSeconds(); break; case 'tt': res += d.getHours() < 12 ? 'am' : 'pm'; break; case 't': res += d.getHours() < 12 ? 'a' : 'p'; break; default: res += tokens[i]; } } return res; } util.printx = function(fmt, val) { var cs = '='; var res = ''; var i = 0; var m; while (i < fmt.length) { switch (fmt.charAt(i)) { case '\\': i++; if (i >= fmt.length) return res; res += fmt.charAt(i); break; case 'X': m = val.match(/\w/); if (!m) return res; res += MuPDF.convertCase(m[0],cs); val = val.replace(/^\W*\w/,''); break; case 'A': m = val.match(/[A-z]/); if (!m) return res; res += MuPDF.convertCase(m[0],cs); val = val.replace(/^[^A-z]*[A-z]/,''); break; case '9': m = val.match(/\d/); if (!m) return res; res += m[0]; val = val.replace(/^\D*\d/,''); break; case '*': res += val; val = ''; break; case '?': if (!val) return res; res += MuPDF.convertCase(val.charAt(0),cs); val = val.substr(1); break; case '=': case '>': case '<': cs = fmt.charAt(i); break; default: res += MuPDF.convertCase(fmt.charAt(i),cs); break; } i++; } return res; } function AFExtractTime(dt) { var ampm = dt.match(/(am|pm)/); dt = dt.replace(/(am|pm)/, ''); var t = dt.match(/\d{1,2}:\d{1,2}:\d{1,2}/); dt = dt.replace(/\d{1,2}:\d{1,2}:\d{1,2}/, ''); if (!t) { t = dt.match(/\d{1,2}:\d{1,2}/); dt = dt.replace(/\d{1,2}:\d{1,2}/, ''); } return [dt, t?t[0]+(ampm?ampm[0]:''):'']; } function AFParseDateOrder(fmt) { var order = ''; // Ensure all present with those not added in default order fmt += "mdy"; for (var i = 0; i < fmt.length; i++) { var c = fmt.charAt(i); if ('ymd'.indexOf(c) != -1 && order.indexOf(c) == -1) order += c; } return order; } function AFMatchMonth(d) { var m = d.match(MuPDF.monthPattern); return m ? MuPDF.shortMonthName.indexOf(m[0]) : null; } function AFParseTime(str, d) { if (!str) return d; if (!d) d = new Date(); var ampm = str.match(/(am|pm)/); var nums = str.match(/\d+/g); var hour, min, sec; if (!nums) return null; sec = 0; switch (nums.length) { case 3: sec = nums[2]; case 2: hour = nums[0]; min = nums[1]; break; default: return null; } if (ampm == 'am' && hour < 12) hour = 12 + hour; if (ampm == 'pm' && hour >= 12) hour = 0 + hour - 12; d.setHours(hour, min, sec); if (d.getHours() != hour || d.getMinutes() != min || d.getSeconds() != sec) return null; return d; } function AFParseDateEx(d, fmt) { var dt = AFExtractTime(d); var nums = dt[0].match(/\d+/g); var order = AFParseDateOrder(fmt); var text_month = AFMatchMonth(dt[0]); var dout = new Date(); var year = dout.getFullYear(); var month = dout.getMonth(); var date = dout.getDate(); dout.setHours(12,0,0); if (nums.length < 1 || nums.length > 3) return null; if (nums.length < 3 && text_month) { // Use the text month rather than one of the numbers month = text_month; order = order.replace('m',''); } order = order.substr(0, nums.length); // If year and month specified but not date then use the 1st if (order == "ym" || (order == "y" && text_month)) date = 1; for (var i = 0; i < nums.length; i++) { switch (order.charAt(i)) { case 'y': year = nums[i]; break; case 'm': month = nums[i] - 1; break; case 'd': date = nums[i]; break; } } if (year < 100) { if (fmt.search("yyyy") != -1) return null; if (year >= 50) year = 1900 + year; else if (year >= 0) year = 2000 + year; } dout.setFullYear(year, month, date); if (dout.getFullYear() != year || dout.getMonth() != month || dout.getDate() != date) return null; return AFParseTime(dt[1], dout); } function AFDate_FormatEx(fmt) { var d = AFParseDateEx(event.value, fmt); event.value = d ? util.printd(fmt, d) : ""; } function AFDate_Format(index) { var formats = ['m/d','m/d/yy','mm/dd/yy','mm/yy','d-mmm','d-mmm-yy','dd-mm-yy','yy-mm-dd', 'mmm-yy','mmmm-yy','mmm d, yyyy','mmmm d, yyyy','m/d/yy h:MM tt','m/d/yy HH:MM']; AFDate_FormatEx(formats[index]); } function AFTime_FormatEx(fmt) { var d = AFParseTime(event.value, null); event.value = d ? util.printd(fmt, d) : ''; } function AFTime_Format(index) { var formats = ['HH:MM','h:MM tt','HH:MM:ss','h:MM:ss tt']; AFTime_FormatEx(formats[index]); } function AFSpecial_Format(index) { var res; switch (index) { case 0: res = util.printx('99999', event.value); break; case 1: res = util.printx('99999-9999', event.value); break; case 2: res = util.printx('9999999999', event.value); res = util.printx(res.length >= 10 ? '(999) 999-9999' : '999-9999', event.value); break; case 3: res = util.printx('999-99-9999', event.value); break; } event.value = res ? res : ''; } function AFNumber_Format(nDec,sepStyle,negStyle,currStyle,strCurrency,bCurrencyPrepend) { var val = event.value; var fracpart; var intpart; var point = sepStyle&2 ? ',' : '.'; var separator = sepStyle&2 ? '.' : ','; if (/^\D*\./.test(val)) val = '0'+val; var groups = val.match(/\d+/g); switch (groups.length) { case 0: return; case 1: fracpart = ''; intpart = groups[0]; break; default: fracpart = groups.pop(); intpart = groups.join(''); break; } // Remove leading zeros intpart = intpart.replace(/^0*/,''); if (!intpart) intpart = '0'; if ((sepStyle & 1) == 0) { // Add the thousands sepearators: pad to length multiple of 3 with zeros, // split into 3s, join with separator, and remove the leading zeros intpart = new Array(2-(intpart.length+2)%3+1).join('0') + intpart; intpart = intpart.match(/.../g).join(separator).replace(/^0*/,''); } if (!intpart) intpart = '0'; // Adjust fractional part to correct number of decimal places fracpart += new Array(nDec+1).join('0'); fracpart = fracpart.substr(0,nDec); if (fracpart) intpart += point+fracpart; if (bCurrencyPrepend) intpart = strCurrency+intpart; else intpart += strCurrency; if (/-/.test(val)) { switch (negStyle) { case 0: intpart = '-'+intpart; break; case 1: break; case 2: case 3: intpart = '('+intpart+')'; break; } } if (negStyle&1) event.target.textColor = /-/.text(val) ? color.red : color.black; event.value = intpart; } function AFSimple_Calculate(op, list) { var res; switch (op) { case 'SUM': res = 0; break; case 'PRD': res = 1; break; case 'AVG': res = 0; break; } if (typeof list == 'string') list = list.split(/ *, */); for (var i = 0; i < list.length; i++) { var field = getField(list[i]); var value = Number(field.value); switch (op) { case 'SUM': res += value; break; case 'PRD': res *= value; break; case 'AVG': res += value; break; case 'MIN': if (i == 0 || value < res) res = value; break; case 'MAX': if (i == 0 || value > res) res = value; break; } } if (op == 'AVG') res /= list.length; event.value = res; }
Javascript: implement main Keystroke and Validate functions
pdf/pdf_util.js
Javascript: implement main Keystroke and Validate functions
<ide><path>df/pdf_util.js <ide> return AFParseTime(dt[1], dout); <ide> } <ide> <add>function AFDate_KeystrokeEx(fmt) <add>{ <add> if (event.willCommit && !AFParseDateEx(event.value)) <add> event.rc = false; <add>} <add> <add>function AFDate_Keystroke(index) <add>{ <add> var formats = ['m/d','m/d/yy','mm/dd/yy','mm/yy','d-mmm','d-mmm-yy','dd-mm-yy','yy-mm-dd', <add> 'mmm-yy','mmmm-yy','mmm d, yyyy','mmmm d, yyyy','m/d/yy h:MM tt','m/d/yy HH:MM']; <add> AFDate_KeystrokeEx(formats[index]); <add>} <add> <ide> function AFDate_FormatEx(fmt) <ide> { <ide> var d = AFParseDateEx(event.value, fmt); <ide> AFDate_FormatEx(formats[index]); <ide> } <ide> <add>function AFTime_Keystroke(index) <add>{ <add> if (event.willCommit && !AFParseTime(event.value, null)) <add> event.rc = false; <add>} <add> <ide> function AFTime_FormatEx(fmt) <ide> { <ide> var d = AFParseTime(event.value, null); <ide> } <ide> <ide> event.value = res ? res : ''; <add>} <add> <add>function AFNumber_Keystroke(nDec, sepStyle, negStyle, currStyle, strCurrency, bCurrencyPrepend) <add>{ <add> if (sepStyle & 2) <add> { <add> if (!event.value.match(/^[+-]?\d*[,.]?\d*$/)) <add> { <add> event.rc = false; <add> return; <add> } <add> } <add> else <add> { <add> if (!event.value.match(/^[+-]?\d*\.?\d*$/)) <add> { <add> event.rc = false; <add> return; <add> } <add> } <add> <add> if (event.willCommit && !event.value.match(/\d/)) <add> event.rc = false; <ide> } <ide> <ide> function AFNumber_Format(nDec,sepStyle,negStyle,currStyle,strCurrency,bCurrencyPrepend) <ide> <ide> event.value = res; <ide> } <add> <add>function AFRange_Validate(lowerCheck, lowerLimit, upperCheck, upperLimit) <add>{ <add> if (upperCheck && event.value > upperLimit) <add> event.rc = false; <add> <add> if (lowerCheck && event.value < lowerLimit) <add> event.rc = false; <add>}
Java
apache-2.0
2bb144145c50c10b970a5926b368851aa69d81e7
0
MaTriXy/MobFox-Android-SDK,aiurlano/MobFox-Android-SDK,palaniyappanBala/MobFox-Android-SDK,aiurlano/MobFox-Android-SDK,MaTriXy/MobFox-Android-SDK,palaniyappanBala/MobFox-Android-SDK,aiurlano/MobFox-Android-SDK,palaniyappanBala/MobFox-Android-SDK,MaTriXy/MobFox-Android-SDK
package com.adsdk.sdk.customevents; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import android.app.Activity; import android.os.Handler; public class AdColonyFullscreen extends CustomEventFullscreen { private static boolean initialized; private boolean reported; private Class<?> adColonyClass; private Class<?> listenerClass; private Class<?> videoAdClass; private Method isReadyMethod; private Object videoAd; @Override public void loadFullscreen(Activity activity, CustomEventFullscreenListener customEventFullscreenListener, String optionalParameters, String trackingPixel) { String[] adIdParts = optionalParameters.split(";"); String clientOptions = adIdParts[0]; String appId = adIdParts[1]; String zoneIds = adIdParts[2]; listener = customEventFullscreenListener; this.trackingPixel = trackingPixel; reported = false; try { adColonyClass = Class.forName("com.jirbo.adcolony.AdColony"); listenerClass = Class.forName("com.jirbo.adcolony.AdColonyAdListener"); videoAdClass = Class.forName("com.jirbo.adcolony.AdColonyVideoAd"); } catch (ClassNotFoundException e) { if (listener != null) { listener.onFullscreenFailed(); } return; } try { if (!initialized) { Method configureMethod = adColonyClass.getMethod("configure", new Class[] { Activity.class, String.class, String.class, String[].class }); configureMethod.invoke(null, activity, clientOptions, appId, new String[] { zoneIds }); initialized = true; } isReadyMethod = videoAdClass.getMethod("isReady"); Constructor<?> videoAdConstructor = videoAdClass.getConstructor(); Method withListenerMethod = videoAdClass.getMethod("withListener", listenerClass); videoAd = videoAdConstructor.newInstance(); withListenerMethod.invoke(videoAd, createListener()); boolean isReady = (Boolean) isReadyMethod.invoke(videoAd); if (isReady) { if (listener != null && !reported) { reported = true; listener.onFullscreenLoaded(AdColonyFullscreen.this); } } else { Handler h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { boolean isReady = false; try { isReady = (Boolean) isReadyMethod.invoke(videoAd); } catch (Exception e) { } if (isReady) { if (listener != null && !reported) { reported = true; listener.onFullscreenLoaded(AdColonyFullscreen.this); } } else { if (listener != null && !reported) { reported = true; listener.onFullscreenFailed(); } } } }, 5000); } } catch (Exception e) { if (listener != null) { listener.onFullscreenFailed(); } } } private Object createListener() { Object instance = Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class<?>[] { listenerClass }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("onAdColonyAdStarted")) { reportImpression(); if (listener != null) { listener.onFullscreenOpened(); } } else if (method.getName().equals("onAdColonyAdAttemptFinished")) { Method notShownMethod = videoAdClass.getMethod("notShown"); Method noFillMethod = videoAdClass.getMethod("noFill"); boolean notShown = (Boolean) notShownMethod.invoke(videoAd); boolean noFill = (Boolean) noFillMethod.invoke(videoAd); if (notShown || noFill) { if (listener != null && !reported) { reported = true; listener.onFullscreenFailed(); } } else if (listener != null) { listener.onFullscreenClosed(); } } return null; } }); return instance; } @Override public void showFullscreen() { try { boolean isReady = (Boolean) isReadyMethod.invoke(videoAd); if (videoAd != null && isReady) { Method showMethod = videoAdClass.getMethod("show"); showMethod.invoke(videoAd); } } catch (Exception e) { if (listener != null) { listener.onFullscreenFailed(); } } } }
src/com/adsdk/sdk/customevents/AdColonyFullscreen.java
package com.adsdk.sdk.customevents; import android.app.Activity; import android.os.Handler; import com.jirbo.adcolony.AdColony; import com.jirbo.adcolony.AdColonyAd; import com.jirbo.adcolony.AdColonyAdListener; import com.jirbo.adcolony.AdColonyVideoAd; public class AdColonyFullscreen extends CustomEventFullscreen { private static boolean initialized; private AdColonyVideoAd videoAd; private boolean reported; @Override public void loadFullscreen(Activity activity, CustomEventFullscreenListener customEventFullscreenListener, String optionalParameters, String trackingPixel) { String[] adIdParts = optionalParameters.split(";"); String clientOptions = adIdParts[0]; String appId = adIdParts[1]; String zoneIds = adIdParts[2]; listener = customEventFullscreenListener; this.trackingPixel = trackingPixel; reported = false; try { Class.forName("com.jirbo.adcolony.AdColony"); Class.forName("com.jirbo.adcolony.AdColonyAd"); Class.forName("com.jirbo.adcolony.AdColonyAdAvailabilityListener"); Class.forName("com.jirbo.adcolony.AdColonyAdListener"); Class.forName("com.jirbo.adcolony.AdColonyVideoAd"); } catch (ClassNotFoundException e) { if (listener != null) { listener.onFullscreenFailed(); } return; } if(!initialized) { AdColony.configure(activity, clientOptions, appId, zoneIds); initialized = true; } videoAd = new AdColonyVideoAd().withListener(createListener()); if(videoAd.isReady()) { if (listener != null && !reported) { reported = true; listener.onFullscreenLoaded(AdColonyFullscreen.this); } } else { Handler h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { if(videoAd.isReady()) { if (listener != null && !reported) { reported = true; listener.onFullscreenLoaded(AdColonyFullscreen.this); } } else { if (listener != null && !reported) { reported = true; listener.onFullscreenFailed(); } } } }, 5000); } } private AdColonyAdListener createListener() { return new AdColonyAdListener() { @Override public void onAdColonyAdStarted(AdColonyAd arg0) { reportImpression(); if (listener != null) { listener.onFullscreenOpened(); } } @Override public void onAdColonyAdAttemptFinished(AdColonyAd ad) { if(ad.notShown() || ad.noFill()) { if (listener != null && !reported) { reported = true; listener.onFullscreenFailed(); } } else if (listener != null) { listener.onFullscreenClosed(); } } }; } @Override public void showFullscreen() { if(videoAd != null && videoAd.isReady()) { videoAd.show(); } } }
Use reflection in AdColony custom event.
src/com/adsdk/sdk/customevents/AdColonyFullscreen.java
Use reflection in AdColony custom event.
<ide><path>rc/com/adsdk/sdk/customevents/AdColonyFullscreen.java <ide> package com.adsdk.sdk.customevents; <add> <add>import java.lang.reflect.Constructor; <add>import java.lang.reflect.InvocationHandler; <add>import java.lang.reflect.Method; <add>import java.lang.reflect.Proxy; <ide> <ide> import android.app.Activity; <ide> import android.os.Handler; <ide> <del>import com.jirbo.adcolony.AdColony; <del>import com.jirbo.adcolony.AdColonyAd; <del>import com.jirbo.adcolony.AdColonyAdListener; <del>import com.jirbo.adcolony.AdColonyVideoAd; <add>public class AdColonyFullscreen extends CustomEventFullscreen { <ide> <del>public class AdColonyFullscreen extends CustomEventFullscreen { <del> <ide> private static boolean initialized; <del> private AdColonyVideoAd videoAd; <ide> private boolean reported; <del> <add> private Class<?> adColonyClass; <add> private Class<?> listenerClass; <add> private Class<?> videoAdClass; <add> private Method isReadyMethod; <add> private Object videoAd; <ide> <ide> @Override <ide> public void loadFullscreen(Activity activity, CustomEventFullscreenListener customEventFullscreenListener, String optionalParameters, String trackingPixel) { <ide> String clientOptions = adIdParts[0]; <ide> String appId = adIdParts[1]; <ide> String zoneIds = adIdParts[2]; <del> <add> <ide> listener = customEventFullscreenListener; <ide> this.trackingPixel = trackingPixel; <ide> reported = false; <ide> <ide> try { <del> Class.forName("com.jirbo.adcolony.AdColony"); <del> Class.forName("com.jirbo.adcolony.AdColonyAd"); <del> Class.forName("com.jirbo.adcolony.AdColonyAdAvailabilityListener"); <del> Class.forName("com.jirbo.adcolony.AdColonyAdListener"); <del> Class.forName("com.jirbo.adcolony.AdColonyVideoAd"); <add> adColonyClass = Class.forName("com.jirbo.adcolony.AdColony"); <add> listenerClass = Class.forName("com.jirbo.adcolony.AdColonyAdListener"); <add> videoAdClass = Class.forName("com.jirbo.adcolony.AdColonyVideoAd"); <ide> } catch (ClassNotFoundException e) { <ide> if (listener != null) { <ide> listener.onFullscreenFailed(); <ide> } <ide> return; <ide> } <del> <del> if(!initialized) { <del> AdColony.configure(activity, clientOptions, appId, zoneIds); <del> initialized = true; <add> <add> try { <add> <add> if (!initialized) { <add> Method configureMethod = adColonyClass.getMethod("configure", new Class[] { Activity.class, String.class, String.class, String[].class }); <add> configureMethod.invoke(null, activity, clientOptions, appId, new String[] { zoneIds }); <add> <add> initialized = true; <add> } <add> isReadyMethod = videoAdClass.getMethod("isReady"); <add> <add> Constructor<?> videoAdConstructor = videoAdClass.getConstructor(); <add> Method withListenerMethod = videoAdClass.getMethod("withListener", listenerClass); <add> videoAd = videoAdConstructor.newInstance(); <add> withListenerMethod.invoke(videoAd, createListener()); <add> <add> boolean isReady = (Boolean) isReadyMethod.invoke(videoAd); <add> <add> if (isReady) { <add> if (listener != null && !reported) { <add> reported = true; <add> listener.onFullscreenLoaded(AdColonyFullscreen.this); <add> } <add> } else { <add> Handler h = new Handler(); <add> h.postDelayed(new Runnable() { <add> <add> @Override <add> public void run() { <add> boolean isReady = false; <add> <add> try { <add> isReady = (Boolean) isReadyMethod.invoke(videoAd); <add> } catch (Exception e) { <add> <add> } <add> <add> if (isReady) { <add> if (listener != null && !reported) { <add> reported = true; <add> listener.onFullscreenLoaded(AdColonyFullscreen.this); <add> } <add> } else { <add> if (listener != null && !reported) { <add> reported = true; <add> listener.onFullscreenFailed(); <add> } <add> } <add> <add> } <add> }, 5000); <add> } <add> <add> } catch (Exception e) { <add> if (listener != null) { <add> listener.onFullscreenFailed(); <add> } <ide> } <del> <del> videoAd = new AdColonyVideoAd().withListener(createListener()); <del> if(videoAd.isReady()) { <del> if (listener != null && !reported) { <del> reported = true; <del> listener.onFullscreenLoaded(AdColonyFullscreen.this); <del> } <del> } else { <del> Handler h = new Handler(); <del> h.postDelayed(new Runnable() { <del> <del> @Override <del> public void run() { <del> if(videoAd.isReady()) { <del> if (listener != null && !reported) { <del> reported = true; <del> listener.onFullscreenLoaded(AdColonyFullscreen.this); <del> } <del> } else { <add> } <add> <add> private Object createListener() { <add> <add> Object instance = Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class<?>[] { listenerClass }, new InvocationHandler() { <add> <add> @Override <add> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { <add> <add> if (method.getName().equals("onAdColonyAdStarted")) { <add> reportImpression(); <add> if (listener != null) { <add> listener.onFullscreenOpened(); <add> } <add> } else if (method.getName().equals("onAdColonyAdAttemptFinished")) { <add> Method notShownMethod = videoAdClass.getMethod("notShown"); <add> Method noFillMethod = videoAdClass.getMethod("noFill"); <add> <add> boolean notShown = (Boolean) notShownMethod.invoke(videoAd); <add> boolean noFill = (Boolean) noFillMethod.invoke(videoAd); <add> <add> if (notShown || noFill) { <ide> if (listener != null && !reported) { <ide> reported = true; <ide> listener.onFullscreenFailed(); <ide> } <add> } else if (listener != null) { <add> listener.onFullscreenClosed(); <ide> } <del> <add> <ide> } <del> }, 5000); <del> } <del> } <add> return null; <add> } <add> }); <ide> <del> private AdColonyAdListener createListener() { <del> return new AdColonyAdListener() { <del> <del> @Override <del> public void onAdColonyAdStarted(AdColonyAd arg0) { <del> reportImpression(); <del> if (listener != null) { <del> listener.onFullscreenOpened(); <del> } <del> } <del> <del> @Override <del> public void onAdColonyAdAttemptFinished(AdColonyAd ad) { <del> if(ad.notShown() || ad.noFill()) { <del> if (listener != null && !reported) { <del> reported = true; <del> listener.onFullscreenFailed(); <del> } <del> } else if (listener != null) { <del> listener.onFullscreenClosed(); <del> } <del> } <del> }; <add> return instance; <add> <ide> } <ide> <ide> @Override <ide> public void showFullscreen() { <del> if(videoAd != null && videoAd.isReady()) { <del> videoAd.show(); <add> try { <add> boolean isReady = (Boolean) isReadyMethod.invoke(videoAd); <add> <add> if (videoAd != null && isReady) { <add> Method showMethod = videoAdClass.getMethod("show"); <add> showMethod.invoke(videoAd); <add> } <add> } catch (Exception e) { <add> if (listener != null) { <add> listener.onFullscreenFailed(); <add> } <ide> } <ide> } <ide>
JavaScript
mit
d0e9503481817d3433e0cddf1d862a6b91cfc50d
0
termith-anr/totem,termith-anr/idefix,termith-anr/idefix,termith-anr/totem
/** * Created by matthias on 01/11/201. * VERSION: PHASE 1 (2014-11-01) */ /************************ **** MODULES **** ************************/ var objectPath = require('object-path'), kuler = require('kuler'), sha1 = require('sha1'), jsonselect = require('JSONSelect'); 'use strict'; module.exports = function(options, config) { options = options || {}; config = config.get(); return function (input, submit) { /* * pertinencesNames is an array of methods names , insert in input * keywords is an array of words , insert in input * */ var pertinencesNames = [], keywords = [], arr = []; jsonselect.match(".keywords" , input.content.json , function(element){ var pertinences = element.filter(function(content){ return ((content.scheme !== "inist-francis" ) && (content.scheme !== "inist-pascal" ) && (content.scheme !== "cc" ) && (content.scheme !== "author" ) && (content['xml#lang'] == "fr" ) ); }); var silences = element.filter(function(content){ return (((content.scheme == "inist-francis" ) || (content.scheme == "inist-pascal" )) && ((content['xml#lang'] == "fr" ))); }); /* * PERTINENCES ACTIONS * */ pertinencesNames = jsonselect.match(".scheme" , pertinences); //console.log("pertinencesNames : " , pertinencesNames); jsonselect.forEach(":has(:root > .term)" , pertinences ,function(terms){ var methodName = terms.scheme; jsonselect.forEach(".#text" , terms , function(word){ var id = sha1("pertinence"+methodName+word); //console.log(" id " , id , " word ", word); var obj = { "id" : id, "type" : "pertinence", "method" : methodName, "word" : word }; arr.push(obj); }); //console.log(arr); }); /* * SILENCES ACTIONS * */ jsonselect.forEach(":has(:root > .term)" , silences ,function(terms){ for(var i = 0 ; i < pertinencesNames.length ; i++) { var methodName = pertinencesNames[i]; jsonselect.forEach(".#text", terms, function (word) { var id = sha1("silence" + methodName + word); console.log(" id " , id , " word ", word); var obj = { "id": id, "type": "silence", "method": methodName, "word": word }; arr.push(obj); }); } console.log(arr); }); }); objectPath.ensureExists(input, "keywords" , arr); objectPath.ensureExists(input, "pertinenceMethods" , pertinencesNames); /*********************** **** FUNCTIONS **** ************************/ /** * Infos show any kind of informations in console about the configuration * @param err STRING the message to show * @param type STRING (error , warning , info , valid) * @param option STRING the option concerned */ var infos = function(err,type,option) { switch(type) { case "error": console.error(kuler("ERROR - Config fails on option : " + option + " - Error is : \n" + err, "#e67e22")); break; case "warning": console.warn(kuler("WARNING - Config problem on option : " + option + " , warning is : \n" + err, "#f39c12")); break; case "info": console.info(kuler("WARNING - Config problem on option : " + option + " , info is : \n" + err, "#3498db")); break; case "valid": console.log(kuler("SUCCESS - " + option + " , on : \n" + err, "#2ecc71")); break; } }; /** * Check if option is send * @param option {STRING} is the option to check * @param type {STRING}(config/options) what to check? * @returns {boolean} */ var check = function(option,type){ if(type === "config"){ if(typeof(config[option]) == "undefined"){ infos("L'option générale n'a pas été précisée","error",option); process.exit(1); } } if(type === "options"){ if(typeof(options[option]) == "undefined"){ infos("L'option du loader n'a pas été précisée","error",option); process.exit(1); } } return true; }; /** * getContent of input * @param key {STRING} what to get * @param path {STRING} path where to get * @returns {*} */ var getContent = function(key,path){ var content; path = "content.json." +path; if(key === "pertinence"){ content = objectPath.get(input , path); } if(key === "silence"){ content = objectPath.get(input ,path); } return content; }; /*** * filterContent of array to keep usefull * @param content {ARRAY} * @param type {STRING} what ? pertinence /silence * @returns {*} */ var filterContent = function(content , type){ if(type === "pertinence") { return content.filter(function(content){ return ((content.scheme !== "inist-francis" ) && (content.scheme !== "inist-pascal" ) && (content.scheme !== "cc" ) && (content.scheme !== "author" ) && (content['xml#lang'] == "fr" ) ); }); } if(type === "silence"){ return content.filter(function(content) { return (((content.scheme == "inist-francis" ) || (content.scheme == "inist-pascal" )) && ((content['xml#lang'] == "fr" ))); }); } }; /** * getMethodsNames of pertinences document * @param content {ARRAY} the array containing brut pertinence * @returns {Array} */ var getMethodsNames = function(content){ var arr = []; for(var i=0 ; i < content.length ; i++){ arr.push(content[i].scheme); } return arr; }; /** * formContent , build an array of object words , the formm for keywords database * @param content {ARRAY} an array of pertinence or silence keywords * @param type {STRING} specify silence/pertinence type * @param methodsName {ARRAY} an array of methods pertinence names * @returns {Array} */ var formContent = function(content,type,methodsName){ var arr = []; if(type === "pertinence") { //console.log('content ' , content); for(var i= 0 ; i < content.length ; i++){ var methodName = content[i].scheme.toString(); //console.log(methodName); for(var key in content[i].term){ var word = content[i].term[key]['#text'].toString(), id = sha1(type+methodName+word), objectWord = {id : id , type : type , method : methodName , word : word}; //console.log(objectWord); arr.push(objectWord); } } return arr; } if(type === "silence") { for(var i = 0 ; i < content[0].term.length ; i++){ // Pour chaque mot //console.log(' MOT N° : ' , i); for(var j= 0 ; j < methodsName.length ; j++) { // Pour chaque méthode //console.log(' METHODE N° ' , j ); var word = content[0].term[i]['#text'].toString(), id = sha1(type + methodsName[j] + word), objectWord = {id: id, type: type, method: methodsName[j], word: word}; arr.push(objectWord); } } return arr; } }; /** * insertContent in the flux to mongo then * @param content {*} what to insert * @param path {STRING} where to insert */ var insertContent = function(content , path){ objectPath.ensureExists(input, path, content); }; /************************ **** EXECUTION **** ************************/ /*if(check("pathPertinence","config") && check("pathSilence","config")){ var pertinence = getContent("pertinence", config.pathPertinence), silence = getContent("silence", config.pathSilence); silence = filterContent(silence,"silence"); pertinence = filterContent(pertinence,"pertinence"); var arrPertinence = formContent(pertinence, "pertinence"), pertinenceMethods = getMethodsNames(pertinence), arrSilence = formContent(silence, "silence" , pertinenceMethods), listOfKeywords = arrPertinence.concat(arrSilence); //console.log(listOfKeywords); //console.log("--------------------------------\n"); insertContent(listOfKeywords,"keywords"); insertContent(pertinenceMethods,"pertinenceMethods"); }*/ /************************ **** NEXT LOADER **** ************************/ submit(null, input); } };
loaders/tei-format/2014-11-01.js
/** * Created by matthias on 01/11/201. * VERSION: PHASE 1 (2014-11-01) */ /************************ **** MODULES **** ************************/ var objectPath = require('object-path'), kuler = require('kuler'), sha1 = require('sha1'), jsonselect = require('JSONSelect'); 'use strict'; module.exports = function(options, config) { options = options || {}; config = config.get(); return function (input, submit) { var pertinenceObject = [], silenceObject = []; jsonselect.forEach(".keywords:only-child" , input.content.json , function(element){ var arr = []; var pertinences = element.filter(function(content){ return ((content.scheme !== "inist-francis" ) && (content.scheme !== "inist-pascal" ) && (content.scheme !== "cc" ) && (content.scheme !== "author" ) && (content['xml#lang'] == "fr" ) ); }); var silences = element.filter(function(content){ return (((content.scheme == "inist-francis" ) || (content.scheme == "inist-pascal" )) && ((content['xml#lang'] == "fr" ))); }); var pertinencesNames = jsonselect.match(".scheme" , pertinences); //console.log("pertinencesNames : " , pertinencesNames); jsonselect.forEach(":has(:root > .term)" , pertinences ,function(terms){ var methodName = terms.scheme; jsonselect.forEach(".#text" , terms , function(word){ var id = sha1("pertinence"+methodName+word); //console.log(" id " , id , " word ", word); var obj = { "id" : id, "type" : "pertinence", "method" : methodName, "word" : word }; arr.push(obj); }); console.log(arr); }); }); /*********************** **** FUNCTIONS **** ************************/ /** * Infos show any kind of informations in console about the configuration * @param err STRING the message to show * @param type STRING (error , warning , info , valid) * @param option STRING the option concerned */ var infos = function(err,type,option) { switch(type) { case "error": console.error(kuler("ERROR - Config fails on option : " + option + " - Error is : \n" + err, "#e67e22")); break; case "warning": console.warn(kuler("WARNING - Config problem on option : " + option + " , warning is : \n" + err, "#f39c12")); break; case "info": console.info(kuler("WARNING - Config problem on option : " + option + " , info is : \n" + err, "#3498db")); break; case "valid": console.log(kuler("SUCCESS - " + option + " , on : \n" + err, "#2ecc71")); break; } }; /** * Check if option is send * @param option {STRING} is the option to check * @param type {STRING}(config/options) what to check? * @returns {boolean} */ var check = function(option,type){ if(type === "config"){ if(typeof(config[option]) == "undefined"){ infos("L'option générale n'a pas été précisée","error",option); process.exit(1); } } if(type === "options"){ if(typeof(options[option]) == "undefined"){ infos("L'option du loader n'a pas été précisée","error",option); process.exit(1); } } return true; }; /** * getContent of input * @param key {STRING} what to get * @param path {STRING} path where to get * @returns {*} */ var getContent = function(key,path){ var content; path = "content.json." +path; if(key === "pertinence"){ content = objectPath.get(input , path); } if(key === "silence"){ content = objectPath.get(input ,path); } return content; }; /*** * filterContent of array to keep usefull * @param content {ARRAY} * @param type {STRING} what ? pertinence /silence * @returns {*} */ var filterContent = function(content , type){ if(type === "pertinence") { return content.filter(function(content){ return ((content.scheme !== "inist-francis" ) && (content.scheme !== "inist-pascal" ) && (content.scheme !== "cc" ) && (content.scheme !== "author" ) && (content['xml#lang'] == "fr" ) ); }); } if(type === "silence"){ return content.filter(function(content) { return (((content.scheme == "inist-francis" ) || (content.scheme == "inist-pascal" )) && ((content['xml#lang'] == "fr" ))); }); } }; /** * getMethodsNames of pertinences document * @param content {ARRAY} the array containing brut pertinence * @returns {Array} */ var getMethodsNames = function(content){ var arr = []; for(var i=0 ; i < content.length ; i++){ arr.push(content[i].scheme); } return arr; }; /** * formContent , build an array of object words , the formm for keywords database * @param content {ARRAY} an array of pertinence or silence keywords * @param type {STRING} specify silence/pertinence type * @param methodsName {ARRAY} an array of methods pertinence names * @returns {Array} */ var formContent = function(content,type,methodsName){ var arr = []; if(type === "pertinence") { //console.log('content ' , content); for(var i= 0 ; i < content.length ; i++){ var methodName = content[i].scheme.toString(); //console.log(methodName); for(var key in content[i].term){ var word = content[i].term[key]['#text'].toString(), id = sha1(type+methodName+word), objectWord = {id : id , type : type , method : methodName , word : word}; //console.log(objectWord); arr.push(objectWord); } } return arr; } if(type === "silence") { for(var i = 0 ; i < content[0].term.length ; i++){ // Pour chaque mot //console.log(' MOT N° : ' , i); for(var j= 0 ; j < methodsName.length ; j++) { // Pour chaque méthode //console.log(' METHODE N° ' , j ); var word = content[0].term[i]['#text'].toString(), id = sha1(type + methodsName[j] + word), objectWord = {id: id, type: type, method: methodsName[j], word: word}; arr.push(objectWord); } } return arr; } }; /** * insertContent in the flux to mongo then * @param content {*} what to insert * @param path {STRING} where to insert */ var insertContent = function(content , path){ objectPath.ensureExists(input, path, content); }; /************************ **** EXECUTION **** ************************/ if(check("pathPertinence","config") && check("pathSilence","config")){ var pertinence = getContent("pertinence", config.pathPertinence), silence = getContent("silence", config.pathSilence); silence = filterContent(silence,"silence"); pertinence = filterContent(pertinence,"pertinence"); var arrPertinence = formContent(pertinence, "pertinence"), pertinenceMethods = getMethodsNames(pertinence), arrSilence = formContent(silence, "silence" , pertinenceMethods), listOfKeywords = arrPertinence.concat(arrSilence); //console.log(listOfKeywords); //console.log("--------------------------------\n"); insertContent(listOfKeywords,"keywords"); insertContent(pertinenceMethods,"pertinenceMethods"); } /************************ **** NEXT LOADER **** ************************/ submit(null, input); } };
JSONSelect phase 1 ok
loaders/tei-format/2014-11-01.js
JSONSelect phase 1 ok
<ide><path>oaders/tei-format/2014-11-01.js <ide> config = config.get(); <ide> return function (input, submit) { <ide> <del> var pertinenceObject = [], <del> silenceObject = []; <del> <del> jsonselect.forEach(".keywords:only-child" , input.content.json , function(element){ <del> var arr = []; <add> /* <add> * pertinencesNames is an array of methods names , insert in input <add> * keywords is an array of words , insert in input <add> * */ <add> var pertinencesNames = [], <add> keywords = [], <add> arr = []; <add> <add> jsonselect.match(".keywords" , input.content.json , function(element){ <ide> <ide> var pertinences = element.filter(function(content){ <ide> return ((content.scheme !== "inist-francis" ) && (content.scheme !== "inist-pascal" ) && (content.scheme !== "cc" ) && (content.scheme !== "author" ) && (content['xml#lang'] == "fr" ) ); <ide> return (((content.scheme == "inist-francis" ) || (content.scheme == "inist-pascal" )) && ((content['xml#lang'] == "fr" ))); <ide> }); <ide> <del> var pertinencesNames = jsonselect.match(".scheme" , pertinences); <add> /* <add> * PERTINENCES ACTIONS <add> * */ <add> pertinencesNames = jsonselect.match(".scheme" , pertinences); <ide> <ide> //console.log("pertinencesNames : " , pertinencesNames); <ide> <ide> arr.push(obj); <ide> <ide> }); <del> <add> //console.log(arr); <add> }); <add> <add> /* <add> * SILENCES ACTIONS <add> * */ <add> <add> jsonselect.forEach(":has(:root > .term)" , silences ,function(terms){ <add> <add> for(var i = 0 ; i < pertinencesNames.length ; i++) { <add> <add> var methodName = pertinencesNames[i]; <add> <add> jsonselect.forEach(".#text", terms, function (word) { <add> var id = sha1("silence" + methodName + word); <add> console.log(" id " , id , " word ", word); <add> var obj = { <add> "id": id, <add> "type": "silence", <add> "method": methodName, <add> "word": word <add> }; <add> <add> arr.push(obj); <add> <add> }); <add> <add> } <ide> console.log(arr); <ide> }); <add> <ide> }); <add> <add> objectPath.ensureExists(input, "keywords" , arr); <add> objectPath.ensureExists(input, "pertinenceMethods" , pertinencesNames); <ide> <ide> /*********************** <ide> **** FUNCTIONS **** <ide> /************************ <ide> **** EXECUTION **** <ide> ************************/ <del> if(check("pathPertinence","config") && check("pathSilence","config")){ <add> /*if(check("pathPertinence","config") && check("pathSilence","config")){ <ide> var pertinence = getContent("pertinence", config.pathPertinence), <ide> silence = getContent("silence", config.pathSilence); <ide> silence = filterContent(silence,"silence"); <ide> //console.log("--------------------------------\n"); <ide> insertContent(listOfKeywords,"keywords"); <ide> insertContent(pertinenceMethods,"pertinenceMethods"); <del> } <add> }*/ <ide> /************************ <ide> **** NEXT LOADER **** <ide> ************************/
JavaScript
mit
ca380375fb39b063e2f0ddd7fcec6e59c4a32df8
0
buchuki/pyjaco,chrivers/pyjaco,chrivers/pyjaco,buchuki/pyjaco,buchuki/pyjaco,chrivers/pyjaco
/** Copyright 2010-2011 Ondrej Certik <[email protected]> Copyright 2010-2011 Mateusz Paprocki <[email protected]> Copyright 2011 Christian Iversen <[email protected]> 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. **/ var basestring = __inherit(object, "basestring"); $PY.basestring = basestring; basestring.PY$__init__ = function(s) { if (s === undefined) { this.obj = ''; } else if (typeof s === "string") { this.obj = s; } else if (s.toString !== undefined) { this.obj = s.toString(); } else { this.obj = js(s); } }; var __basestring_real__ = basestring.PY$__create__; basestring.PY$__create__ = function(cls, obj) { if ($PY.isinstance(obj, basestring) == true) { return obj; } else if (obj.PY$__class__ === undefined && obj.PY$__super__ !== undefined) { return object.PY$__repr__.apply(obj); } else if (obj.PY$__str__ !== undefined) { return obj.PY$__str__(); } else { return __basestring_real__(cls, obj); } }; basestring.PY$__str__ = function () { return this; }; basestring.PY$__repr__ = function () { return this.PY$__class__("'" + this.obj + "'"); }; basestring._js_ = function () { return this.obj; }; basestring.PY$__hash__ = function () { var value = this.obj.charCodeAt(0) << 7; var len = this.obj.length; for (var i = 1; i < len; i++) { value = ((1000003 * value) & 0xFFFFFFFF) ^ this.obj[i]; value = value ^ len; } if (value == -1) { value = -2; } return value; }; basestring.PY$__len__ = function() { return int(this.obj.length); }; basestring.PY$__iter__ = function() { return iter(this.obj); }; basestring.PY$__mod__ = function(args) { return basestring(sprintf(this, args)); }; basestring.PY$__eq__ = function(s) { if (typeof(s) === "string") return this.obj == s ? True : False; else if ($PY.isinstance(s, $PY.basestring) == true) { return this.obj == s.obj ? True : False; } else return False; }; basestring.PY$__gt__ = function(s) { if (typeof(s) === "string") return this.obj > s ? True : False; else if ($PY.isinstance(s, $PY.basestring) == true) return this.obj > s.obj ? True : False; else if ($PY.isinstance(s, $PY.tuple) == true) return False; else return True; }; basestring.PY$__lt__ = function(s) { if (typeof(s) === "string") return this.obj < s ? True : False; else if ($PY.isinstance(s, $PY.basestring) == true) return this.obj < s.obj ? True : False; else if ($PY.isinstance(s, $PY.tuple) == true) return True; else return False; }; basestring.PY$__contains__ = function(item) { for (var index in this.obj) { if (item == this.obj[index]) { return True; } } return False; }; basestring.PY$__getitem__ = function(index) { var seq; index = js(index); if ($PY.isinstance(index, slice) == true) { var s = index; var inds = js(s.PY$indices(py_builtins.len(this))); var start = inds[0]; var stop = inds[1]; var step = inds[2]; if (step != 1) { seq = ""; for (var i = start; i < stop; i += step) { seq = seq + js(this.obj.charAt(i)); } return this.PY$__class__(seq); } else { return this.PY$__class__(this.obj.slice(start, stop)); } } else if ((index >= 0) && (index < js(py_builtins.len(this)))) return this.obj.charAt(index); else if ((index < 0) && (index >= -js(py_builtins.len(this)))) return this.obj.charAt(index + js(py_builtins.len(this))); else throw py_builtins.IndexError("string index out of range"); }; basestring.PY$__setitem__ = function() { throw py_builtins.TypeError("'str' object doesn't support item assignment"); }; basestring.PY$__delitem__ = function() { throw py_builtins.TypeError("'str' object doesn't support item deletion"); }; basestring.PY$__mul__ = function(c) { if ($PY.isinstance(c, int) == true) { var max = js(c); var res = ""; for (var i = 0; i < max; i++) { res += this.obj; } return basestring(res); } else { throw py_builtins.TypeError(sprintf("Cannot multiply string and <%s>", c.PY$__class__.PY$__name__)); } }; basestring.PY$__add__ = function(c) { if ($PY.isinstance(c, basestring) == true) { return this.PY$__class__(this.obj + c.PY$__str__()._js_()); } else { throw py_builtins.TypeError(sprintf("Cannot add string and <%s>", c.PY$__class__.PY$__name__)); } }; basestring.PY$__iadd__ = basestring.PY$__add__; basestring.PY$count = function(needle, start, end) { if (start === undefined) { start = 0; } else { start = js(start); } if (end === undefined) end = null; else end = js(end); var count = 0; var s = this.PY$__getitem__(slice(start, end)); var idx = js(s.PY$find(needle)); while (idx != -1) { count += 1; s = s.PY$__getitem__(slice(idx+1, null)); idx = js(s.PY$find(needle)); } return count; }; basestring.PY$index = function(value, start, end) { if (start === undefined) { start = 0; } for (var i = js(start); (end === undefined) || (start < end); i++) { var _value = this.obj[i]; if (_value === undefined) { break; } if (_value == value) { return int(i); } } throw py_builtins.ValueError("substring not found"); }; basestring.PY$find = function(s) { return int(this.obj.indexOf(js(s))); }; basestring.PY$rfind = function(s) { return int(this.obj.lastIndexOf(js(s))); }; basestring.PY$join = function(s) { // return this.PY$__class__(js(s).join(js(this))); var res = ""; var that = this; iterate(s, function(elm) { if (res != "") res += that.obj; res += str(elm)._js_(); }); return str(res); }; basestring.PY$replace = function(old, _new, count) { old = js(old); _new = js(_new); var old_s; var new_s; if (count !== undefined) count = js(count); else count = -1; old_s = ""; new_s = this.obj; while ((count != 0) && (new_s != old_s)) { old_s = new_s; new_s = new_s.replace(old, _new); count -= 1; } return this.PY$__class__(new_s); }; basestring.PY$lstrip = function(chars) { if (js(py_builtins.len(this)) === 0) return this; if (chars !== undefined) chars = tuple(chars); else chars = tuple(["\n", "\t", " "]); var i = 0; while ((i < js(py_builtins.len(this))) && (js(chars.PY$__contains__(this.PY$__getitem__(i))))) { i += 1; } return this.PY$__getitem__(slice(i, null)); }; basestring.PY$rstrip = function(chars) { if (js(py_builtins.len(this)) === 0) return this; if (chars !== undefined) chars = tuple(chars); else chars = tuple(["\n", "\t", " "]); var i = js(py_builtins.len(this))-1; while ((i >= 0) && (js(chars.PY$__contains__(this.PY$__getitem__(i))))) { i -= 1; } return this.PY$__getitem__(slice(i+1)); }; basestring.PY$strip = function(chars) { return this.PY$lstrip(chars).PY$rstrip(chars); }; basestring.PY$split = function(sep, max) { var r_new; if (sep === undefined) { var strings = this.obj.split(/\s+/); for (var x = 0; x < strings.length; x++) { strings[x] = str(strings[x]); }; return list(strings); } else { sep = js(sep); } if (max === undefined) { max = 0xFFFFFFFF; } else { max = js(max); if (max === 0) { return list([this]); } } r_new = list(); var i = -sep.length; var c = 0; var q = 0; while (c < max) { i = this.obj.indexOf(sep, i + sep.length); if (i === -1) { break; } r_new.PY$append(this.PY$__class__(this.obj.substring(q, i))); q = i + sep.length; c++; } r_new.PY$append(this.PY$__class__(this.obj.substring(q))); return r_new; }; basestring.PY$splitlines = function() { return this.PY$split("\n"); }; basestring.PY$lower = function() { return this.PY$__class__(this.obj.toLowerCase()); }; basestring.PY$upper = function() { return this.PY$__class__(this.obj.toUpperCase()); }; basestring.PY$encode = function() { return this; }; basestring.PY$decode = function() { return this; }; basestring.PY$startswith = function(other) { return bool(this.obj.indexOf(js(other)) === 0); }; basestring.PY$endswith = function(other) { var x = js(other); var i = this.obj.lastIndexOf(x); return (i !== -1 && i == (this.obj.length - x.length)) ? True : False; }; var str = __inherit(basestring, "str"); var unicode = __inherit(basestring, "unicode"); $PY.str = str; $PY.unicode = unicode; unicode.PY$__create__ = function(cls, obj) { if (obj.PY$__unicode__ !== undefined) { return obj.PY$__unicode__(); } else { return basestring.PY$__create__(cls, obj); } };
library/25-type-str.js
/** Copyright 2010-2011 Ondrej Certik <[email protected]> Copyright 2010-2011 Mateusz Paprocki <[email protected]> Copyright 2011 Christian Iversen <[email protected]> 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. **/ var basestring = __inherit(object, "basestring"); $PY.basestring = basestring; basestring.PY$__init__ = function(s) { if (s === undefined) { this.obj = ''; } else if (typeof s === "string") { this.obj = s; } else if (s.toString !== undefined) { this.obj = s.toString(); } else { this.obj = js(s); } }; var __basestring_real__ = basestring.PY$__create__; basestring.PY$__create__ = function(cls, obj) { if ($PY.isinstance(obj, basestring) == true) { return obj; } else if (obj.PY$__class__ === undefined && obj.PY$__super__ !== undefined) { return object.PY$__repr__.apply(obj); } else if (obj.PY$__str__ !== undefined) { return obj.PY$__str__(); } else { return __basestring_real__(cls, obj); } }; basestring.PY$__str__ = function () { return this; }; basestring.PY$__repr__ = function () { return "'" + this + "'"; }; basestring._js_ = function () { return this.obj; }; basestring.PY$__hash__ = function () { var value = this.obj.charCodeAt(0) << 7; var len = this.obj.length; for (var i = 1; i < len; i++) { value = ((1000003 * value) & 0xFFFFFFFF) ^ this.obj[i]; value = value ^ len; } if (value == -1) { value = -2; } return value; }; basestring.PY$__len__ = function() { return int(this.obj.length); }; basestring.PY$__iter__ = function() { return iter(this.obj); }; basestring.PY$__mod__ = function(args) { return basestring(sprintf(this, args)); }; basestring.PY$__eq__ = function(s) { if (typeof(s) === "string") return this.obj == s ? True : False; else if ($PY.isinstance(s, $PY.basestring) == true) { return this.obj == s.obj ? True : False; } else return False; }; basestring.PY$__gt__ = function(s) { if (typeof(s) === "string") return this.obj > s ? True : False; else if ($PY.isinstance(s, $PY.basestring) == true) return this.obj > s.obj ? True : False; else if ($PY.isinstance(s, $PY.tuple) == true) return False; else return True; }; basestring.PY$__lt__ = function(s) { if (typeof(s) === "string") return this.obj < s ? True : False; else if ($PY.isinstance(s, $PY.basestring) == true) return this.obj < s.obj ? True : False; else if ($PY.isinstance(s, $PY.tuple) == true) return True; else return False; }; basestring.PY$__contains__ = function(item) { for (var index in this.obj) { if (item == this.obj[index]) { return True; } } return False; }; basestring.PY$__getitem__ = function(index) { var seq; if ($PY.isinstance(index, slice) == true) { var s = index; var inds = js(s.PY$indices(py_builtins.len(this))); var start = inds[0]; var stop = inds[1]; var step = inds[2]; seq = ""; for (var i = start; i < stop; i += step) { seq = seq + js(this.PY$__getitem__(i)); } return this.PY$__class__(seq); } else if ((index >= 0) && (index < js(py_builtins.len(this)))) return this.obj[index]; else if ((index < 0) && (index >= -js(py_builtins.len(this)))) return this.obj[index+js(py_builtins.len(this))]; else throw py_builtins.IndexError("string index out of range"); }; basestring.PY$__setitem__ = function() { throw py_builtins.TypeError("'str' object doesn't support item assignment"); }; basestring.PY$__delitem__ = function() { throw py_builtins.TypeError("'str' object doesn't support item deletion"); }; basestring.PY$__mul__ = function(c) { if ($PY.isinstance(c, int) == true) { var max = js(c); var res = ""; for (var i = 0; i < max; i++) { res += this.obj; } return basestring(res); } else { throw py_builtins.TypeError(sprintf("Cannot multiply string and <%s>", c.PY$__class__.PY$__name__)); } }; basestring.PY$__add__ = function(c) { if ($PY.isinstance(c, basestring) == true) { return this.PY$__class__(this.obj + c.PY$__str__()); } else { throw py_builtins.TypeError(sprintf("Cannot add string and <%s>", c.PY$__class__.PY$__name__)); } }; basestring.PY$__iadd__ = basestring.PY$__add__; basestring.PY$count = function(needle, start, end) { if (start === undefined) start = 0; if (end === undefined) end = null; var count = 0; var s = this.PY$__getitem__(slice(start, end)); var idx = s.PY$find(needle); while (idx != -1) { count += 1; s = s.PY$__getitem__(slice(idx+1, null)); idx = s.PY$find(needle); } return count; }; basestring.PY$index = function(value, start, end) { if (start === undefined) { start = 0; } for (var i = js(start); (end === undefined) || (start < end); i++) { var _value = this.obj[i]; if (_value === undefined) { break; } if (_value == value) { return int(i); } } throw py_builtins.ValueError("substring not found"); }; basestring.PY$find = function(s) { return this.obj.search(s); }; basestring.PY$rfind = function(s) { return int(this.obj.lastIndexOf(js(s))); }; basestring.PY$join = function(s) { // return this.PY$__class__(js(s).join(js(this))); var res = ""; var that = this; iterate(s, function(elm) { if (res != "") res += that.obj; res += str(elm)._js_(); }); return str(res); }; basestring.PY$replace = function(old, _new, count) { old = js(old); _new = js(_new); var old_s; var new_s; if (count !== undefined) count = js(count); else count = -1; old_s = ""; new_s = this.obj; while ((count != 0) && (new_s != old_s)) { old_s = new_s; new_s = new_s.replace(old, _new); count -= 1; } return this.PY$__class__(new_s); }; basestring.PY$lstrip = function(chars) { if (js(py_builtins.len(this)) === 0) return this; if (chars !== undefined) chars = tuple(chars); else chars = tuple(["\n", "\t", " "]); var i = 0; while ((i < js(py_builtins.len(this))) && (js(chars.PY$__contains__(this.PY$__getitem__(i))))) { i += 1; } return this.PY$__getitem__(slice(i, null)); }; basestring.PY$rstrip = function(chars) { if (js(py_builtins.len(this)) === 0) return this; if (chars !== undefined) chars = tuple(chars); else chars = tuple(["\n", "\t", " "]); var i = js(py_builtins.len(this))-1; while ((i >= 0) && (js(chars.PY$__contains__(this.PY$__getitem__(i))))) { i -= 1; } return this.PY$__getitem__(slice(i+1)); }; basestring.PY$strip = function(chars) { return this.PY$lstrip(chars).PY$rstrip(chars); }; basestring.PY$split = function(sep, max) { var r_new; if (sep === undefined) { var strings = this.obj.split(/\s+/); for (var x = 0; x < strings.length; x++) { strings[x] = str(strings[x]); }; return list(strings); } else { sep = js(sep); } if (max === undefined) { max = 0xFFFFFFFF; } else { max = js(max); if (max === 0) { return list([this]); } } r_new = list(); var i = -sep.length; var c = 0; var q = 0; while (c < max) { i = this.obj.indexOf(sep, i + sep.length); if (i === -1) { break; } r_new.PY$append(this.PY$__class__(this.obj.substring(q, i))); q = i + sep.length; c++; } r_new.PY$append(this.PY$__class__(this.obj.substring(q))); return r_new; }; basestring.PY$splitlines = function() { return this.PY$split("\n"); }; basestring.PY$lower = function() { return this.PY$__class__(this.obj.toLowerCase()); }; basestring.PY$upper = function() { return this.PY$__class__(this.obj.toUpperCase()); }; basestring.PY$encode = function() { return this; }; basestring.PY$decode = function() { return this; }; basestring.PY$startswith = function(other) { return bool(this.obj.indexOf(js(other)) === 0); }; basestring.PY$endswith = function(other) { var x = js(other); var i = this.obj.lastIndexOf(x); return (i !== -1 && i == (this.obj.length - x.length)) ? True : False; }; var str = __inherit(basestring, "str"); var unicode = __inherit(basestring, "unicode"); $PY.str = str; $PY.unicode = unicode; unicode.PY$__create__ = function(cls, obj) { if (obj.PY$__unicode__ !== undefined) { return obj.PY$__unicode__(); } else { return basestring.PY$__create__(cls, obj); } };
* basestring.PY$__repr__ now returns a string-class * Avoid str.__getitem__ where not necessary in PY$__getitem__ with slice * Use s.charAt(x) instead of s[x] * Use js(x) for all pythonic x values
library/25-type-str.js
* basestring.PY$__repr__ now returns a string-class * Avoid str.__getitem__ where not necessary in PY$__getitem__ with slice * Use s.charAt(x) instead of s[x] * Use js(x) for all pythonic x values
<ide><path>ibrary/25-type-str.js <ide> }; <ide> <ide> basestring.PY$__repr__ = function () { <del> return "'" + this + "'"; <add> return this.PY$__class__("'" + this.obj + "'"); <ide> }; <ide> <ide> basestring._js_ = function () { <ide> <ide> basestring.PY$__getitem__ = function(index) { <ide> var seq; <add> index = js(index); <ide> if ($PY.isinstance(index, slice) == true) { <ide> var s = index; <ide> var inds = js(s.PY$indices(py_builtins.len(this))); <ide> var start = inds[0]; <ide> var stop = inds[1]; <ide> var step = inds[2]; <del> seq = ""; <del> for (var i = start; i < stop; i += step) { <del> seq = seq + js(this.PY$__getitem__(i)); <del> } <del> return this.PY$__class__(seq); <add> if (step != 1) { <add> seq = ""; <add> for (var i = start; i < stop; i += step) { <add> seq = seq + js(this.obj.charAt(i)); <add> } <add> return this.PY$__class__(seq); <add> } else { <add> return this.PY$__class__(this.obj.slice(start, stop)); <add> } <ide> } else if ((index >= 0) && (index < js(py_builtins.len(this)))) <del> return this.obj[index]; <add> return this.obj.charAt(index); <ide> else if ((index < 0) && (index >= -js(py_builtins.len(this)))) <del> return this.obj[index+js(py_builtins.len(this))]; <add> return this.obj.charAt(index + js(py_builtins.len(this))); <ide> else <ide> throw py_builtins.IndexError("string index out of range"); <ide> }; <ide> <ide> basestring.PY$__add__ = function(c) { <ide> if ($PY.isinstance(c, basestring) == true) { <del> return this.PY$__class__(this.obj + c.PY$__str__()); <add> return this.PY$__class__(this.obj + c.PY$__str__()._js_()); <ide> } else { <ide> throw py_builtins.TypeError(sprintf("Cannot add string and <%s>", c.PY$__class__.PY$__name__)); <ide> } <ide> basestring.PY$__iadd__ = basestring.PY$__add__; <ide> <ide> basestring.PY$count = function(needle, start, end) { <del> if (start === undefined) <add> if (start === undefined) { <ide> start = 0; <add> } else { <add> start = js(start); <add> } <ide> if (end === undefined) <ide> end = null; <add> else <add> end = js(end); <ide> var count = 0; <ide> var s = this.PY$__getitem__(slice(start, end)); <del> var idx = s.PY$find(needle); <add> var idx = js(s.PY$find(needle)); <ide> while (idx != -1) { <ide> count += 1; <ide> s = s.PY$__getitem__(slice(idx+1, null)); <del> idx = s.PY$find(needle); <add> idx = js(s.PY$find(needle)); <ide> } <ide> return count; <ide> }; <ide> }; <ide> <ide> basestring.PY$find = function(s) { <del> return this.obj.search(s); <add> return int(this.obj.indexOf(js(s))); <ide> }; <ide> <ide> basestring.PY$rfind = function(s) {
JavaScript
mit
06cd2aa781adff4c3c9b968a0dd717928b8305fd
0
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
'use strict'; var ensureObject = require('es5-ext/object/valid-object') , assign = require('es5-ext/object/assign') , forEach = require('es5-ext/object/for-each') , isEmpty = require('es5-ext/object/is-empty') , capitalize = require('es5-ext/string/#/capitalize') , debug = require('debug-ext')('pdf-generator') , ensureDriver = require('dbjs-persistence/ensure-driver') , db = require('../../../db') , _ = require('mano').i18n.bind('Statistics time per role pdf') , resolveFullStepPath = require('../../../utils/resolve-processing-step-full-path') , getDurationDaysHours = require('../../../view/utils/get-duration-days-hours'); var getProcessingTimesByStepProcessor = require('../../statistics/business-process/query-times'); var getEmptyResult = function () { return { count: '-', avgTime: '-', minTime: '-', maxTime: '-', totalTime: '-' }; }; module.exports = function (configData) { var options = { logo: configData.logo, driver: ensureDriver(configData.driver), db: db, processingStepsMeta: ensureObject(configData.processingStepsMeta), customFilter: configData.customFilter }; return { headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/csv; charset=utf-8' }, controller: function (query) { return getProcessingTimesByStepProcessor(assign(options, query))(function (result) { var inserts = { data: [], locale: db.locale, logo: options.logo, currentDate: db.DateTime().toString() }; debug('Generating statistics time per role csv'); forEach(result.byStepAndProcessor, function (data, key) { var step = getEmptyResult(); step.label = db['BusinessProcess' + capitalize.call(options.processingStepsMeta[key]._services[0])].prototype .processingSteps.map.getBySKeyPath(resolveFullStepPath(key)).label; inserts.data.push(step); if (isEmpty(data)) return; step = assign(step, { count: 0, avgTime: 0, minTime: Infinity, maxTime: 0, totalTime: 0 }); forEach(data, function (byProcessor) { byProcessor = byProcessor.processing; step.count += byProcessor.count; step.minTime = Math.min(byProcessor.minTime, step.minTime); step.maxTime = Math.max(byProcessor.maxTime, step.maxTime); step.totalTime += byProcessor.totalTime; }); step.avgTime = getDurationDaysHours(step.totalTime / step.count); step.minTime = getDurationDaysHours(step.minTime); step.maxTime = getDurationDaysHours(step.maxTime); }); // TODO: Rely on businessProcess not steps data below var total, processingTotal, correctionTotal, correctionByUsers; correctionTotal = result.all.correction; correctionTotal.label = _("Total correcting time"); correctionByUsers = result.all.correction; correctionByUsers.label = _("Corrections by the users"); processingTotal = result.all.processing; processingTotal.label = _("Total process without corrections"); total = {}; total.label = _("Total process"); total.count = processingTotal.count; total.totalTime = processingTotal.totalTime + correctionTotal.totalTime; total.minTime = processingTotal.minTime; total.maxTime = processingTotal.maxTime; total.avgTime = total.totalTime / total.count; [correctionTotal, correctionByUsers, processingTotal, total].forEach( function (totalItem) { if (totalItem.avgTime) { totalItem.avgTime = getDurationDaysHours(totalItem.avgTime); } if (totalItem.minTime) { totalItem.minTime = getDurationDaysHours(totalItem.minTime); } if (totalItem.maxTime) { totalItem.maxTime = getDurationDaysHours(totalItem.maxTime); } if (!totalItem.count) { totalItem = assign(totalItem, getEmptyResult()); } inserts.data.push(totalItem); } ); return inserts.data.map(function (row) { return [ row.label, row.count, row.avgTime, row.minTime, row.maxTime ].join(); }).join('\n'); }); } }; };
server/routes/controllers/statistics-time-per-role-csv.js
'use strict'; var ensureObject = require('es5-ext/object/valid-object') , assign = require('es5-ext/object/assign') , forEach = require('es5-ext/object/for-each') , isEmpty = require('es5-ext/object/is-empty') , capitalize = require('es5-ext/string/#/capitalize') , ensureDatabase = require('dbjs/valid-dbjs') , debug = require('debug-ext')('pdf-generator') , ensureDriver = require('dbjs-persistence/ensure-driver') , _ = require('mano').i18n.bind('Statistics time per role pdf') , resolveFullStepPath = require('../../../utils/resolve-processing-step-full-path') , getDurationDaysHours = require('../../../view/utils/get-duration-days-hours'); var getProcessingTimesByStepProcessor = require('../../statistics/business-process/query-times'); var getEmptyResult = function () { return { count: '-', avgTime: '-', minTime: '-', maxTime: '-', totalTime: '-' }; }; module.exports = function (configData) { var options, db = ensureDatabase(configData.db); options = { logo: configData.logo, driver: ensureDriver(configData.driver), db: db, processingStepsMeta: ensureObject(configData.processingStepsMeta), customFilter: configData.customFilter }; return { headers: { 'Cache-Control': 'no-cache', 'Content-Type': 'text/csv; charset=utf-8' }, controller: function (query) { return getProcessingTimesByStepProcessor(assign(options, query))(function (result) { var inserts = { data: [], locale: db.locale, logo: options.logo, currentDate: db.DateTime().toString() }; debug('Generating statistics time per role csv'); forEach(result.byStepAndProcessor, function (data, key) { var step = getEmptyResult(); step.label = db['BusinessProcess' + capitalize.call(options.processingStepsMeta[key]._services[0])].prototype .processingSteps.map.getBySKeyPath(resolveFullStepPath(key)).label; inserts.data.push(step); if (isEmpty(data)) return; step = assign(step, { count: 0, avgTime: 0, minTime: Infinity, maxTime: 0, totalTime: 0 }); forEach(data, function (byProcessor) { byProcessor = byProcessor.processing; step.count += byProcessor.count; step.minTime = Math.min(byProcessor.minTime, step.minTime); step.maxTime = Math.max(byProcessor.maxTime, step.maxTime); step.totalTime += byProcessor.totalTime; }); step.avgTime = getDurationDaysHours(step.totalTime / step.count); step.minTime = getDurationDaysHours(step.minTime); step.maxTime = getDurationDaysHours(step.maxTime); }); // TODO: Rely on businessProcess not steps data below var total, processingTotal, correctionTotal, correctionByUsers; correctionTotal = result.all.correction; correctionTotal.label = _("Total correcting time"); correctionByUsers = result.all.correction; correctionByUsers.label = _("Corrections by the users"); processingTotal = result.all.processing; processingTotal.label = _("Total process without corrections"); total = {}; total.label = _("Total process"); total.count = processingTotal.count; total.totalTime = processingTotal.totalTime + correctionTotal.totalTime; total.minTime = processingTotal.minTime; total.maxTime = processingTotal.maxTime; total.avgTime = total.totalTime / total.count; [correctionTotal, correctionByUsers, processingTotal, total].forEach( function (totalItem) { if (totalItem.avgTime) { totalItem.avgTime = getDurationDaysHours(totalItem.avgTime); } if (totalItem.minTime) { totalItem.minTime = getDurationDaysHours(totalItem.minTime); } if (totalItem.maxTime) { totalItem.maxTime = getDurationDaysHours(totalItem.maxTime); } if (!totalItem.count) { totalItem = assign(totalItem, getEmptyResult()); } inserts.data.push(totalItem); } ); return inserts.data.map(function (row) { return [ row.label, row.count, row.avgTime, row.minTime, row.maxTime ].join(); }).join('\n'); }); } }; };
Reuse db
server/routes/controllers/statistics-time-per-role-csv.js
Reuse db
<ide><path>erver/routes/controllers/statistics-time-per-role-csv.js <ide> , forEach = require('es5-ext/object/for-each') <ide> , isEmpty = require('es5-ext/object/is-empty') <ide> , capitalize = require('es5-ext/string/#/capitalize') <del> , ensureDatabase = require('dbjs/valid-dbjs') <ide> , debug = require('debug-ext')('pdf-generator') <ide> , ensureDriver = require('dbjs-persistence/ensure-driver') <add> , db = require('../../../db') <ide> , _ = require('mano').i18n.bind('Statistics time per role pdf') <ide> , resolveFullStepPath = require('../../../utils/resolve-processing-step-full-path') <ide> , getDurationDaysHours = require('../../../view/utils/get-duration-days-hours'); <ide> }; <ide> <ide> module.exports = function (configData) { <del> var options, db = ensureDatabase(configData.db); <del> options = { <add> var options = { <ide> logo: configData.logo, <ide> driver: ensureDriver(configData.driver), <ide> db: db,
JavaScript
apache-2.0
1b38fe77342dba1647de0fd1a19a727b717a92ee
0
researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds
/** * Created by quasarchimaere on 04.04.2019. */ import angular from "angular"; import ngAnimate from "angular-animate"; import { attach, getIn, get, delay } from "../../utils.js"; import { connect2Redux } from "../../won-utils.js"; import won from "../../won-es6.js"; import { actionCreators } from "../../actions/actions.js"; import postMessagesModule from "../post-messages.js"; import atomCardModule from "../atom-card.js"; import atomMapModule from "../atom-map.js"; import postHeaderModule from "../post-header.js"; import * as generalSelectors from "../../selectors/general-selectors.js"; import * as viewSelectors from "../../selectors/view-selectors.js"; import * as processUtils from "../../process-utils.js"; import * as wonLabelUtils from "../../won-label-utils.js"; import * as atomUtils from "../../atom-utils.js"; import "style/_map.scss"; import "style/_atom-overlay.scss"; import "style/_connection-overlay.scss"; const serviceDependencies = ["$ngRedux", "$scope"]; class Controller { constructor() { attach(this, serviceDependencies, arguments); this.selection = 0; window.ownermap4dbg = this; this.WON = won.WON; const selectFromState = state => { const viewAtomUri = generalSelectors.getViewAtomUriFromRoute(state); const viewConnUri = generalSelectors.getViewConnectionUriFromRoute(state); const atomsWithLocation = getIn(state, ["owner", "atoms"]).filter( metaAtom => atomUtils.hasLocation(metaAtom) ); const atomUrisArray = atomsWithLocation && [...atomsWithLocation.keys()]; const lastAtomUrisUpdateDate = getIn(state, [ "owner", "lastAtomsUpdateTime", ]); const process = get(state, "process"); const isOwnerAtomUrisLoading = processUtils.isProcessingAtomUrisFromOwnerLoad( process ); const isOwnerAtomUrisToLoad = !lastAtomUrisUpdateDate && !isOwnerAtomUrisLoading; let locations = []; atomsWithLocation && atomsWithLocation.map(atom => { const atomLocation = atomUtils.getLocation(atom); locations.push(atomLocation); }); return { locations, atomsWithLocation, lastAtomUrisUpdateDate, friendlyLastAtomUrisUpdateTimestamp: lastAtomUrisUpdateDate && wonLabelUtils.relativeTime( generalSelectors.selectLastUpdateTime(state), lastAtomUrisUpdateDate ), atomUrisArray, atomUrisSize: atomsWithLocation ? atomsWithLocation.size : 0, isOwnerAtomUrisLoading, isOwnerAtomUrisToLoad, showSlideIns: viewSelectors.hasSlideIns(state) && viewSelectors.showSlideIns(state), showModalDialog: viewSelectors.showModalDialog(state), showAtomOverlay: !!viewAtomUri, showConnectionOverlay: !!viewConnUri, viewAtomUri, viewConnUri, }; }; connect2Redux(selectFromState, actionCreators, [], this); this.$scope.$watch( () => this.isOwnerAtomUrisToLoad, () => delay(0).then(() => this.ensureAtomUrisLoaded()) ); } ensureAtomUrisLoaded() { if (this.isOwnerAtomUrisToLoad) { this.atoms__loadAllActiveAtomUrisFromOwner(); } } reload() { if (!this.isOwnerAtomUrisLoading) { this.atoms__loadAllActiveAtomUrisFromOwner(); } } } Controller.$inject = serviceDependencies; export default angular .module("won.owner.components.map", [ ngAnimate, postMessagesModule, atomMapModule, atomCardModule, postHeaderModule, ]) .controller("MapController", Controller).name;
webofneeds/won-owner-webapp/src/main/webapp/app/components/map/map.js
/** * Created by quasarchimaere on 04.04.2019. */ import angular from "angular"; import ngAnimate from "angular-animate"; import { attach, getIn, get, delay } from "../../utils.js"; import { connect2Redux } from "../../won-utils.js"; import won from "../../won-es6.js"; import { actionCreators } from "../../actions/actions.js"; import postMessagesModule from "../post-messages.js"; import atomCardModule from "../atom-card.js"; import atomMapModule from "../atom-map.js"; import postHeaderModule from "../post-header.js"; import * as generalSelectors from "../../selectors/general-selectors.js"; import * as viewSelectors from "../../selectors/view-selectors.js"; import * as processUtils from "../../process-utils.js"; import * as wonLabelUtils from "../../won-label-utils.js"; import * as atomUtils from "../../atom-utils.js"; import "style/_map.scss"; import "style/_atom-overlay.scss"; import "style/_connection-overlay.scss"; const serviceDependencies = ["$ngRedux", "$scope"]; class Controller { constructor() { attach(this, serviceDependencies, arguments); this.selection = 0; window.ownermap4dbg = this; this.WON = won.WON; const selectFromState = state => { const viewAtomUri = generalSelectors.getViewAtomUriFromRoute(state); const viewConnUri = generalSelectors.getViewConnectionUriFromRoute(state); const atoms = getIn(state, ["owner", "atoms"]); const atomUris = getIn(state, ["owner", "atomUris"]); const lastAtomUrisUpdateDate = getIn(state, [ "owner", "lastAtomsUpdateTime", ]); const process = get(state, "process"); const isOwnerAtomUrisLoading = processUtils.isProcessingAtomUrisFromOwnerLoad( process ); const isOwnerAtomUrisToLoad = !lastAtomUrisUpdateDate && !isOwnerAtomUrisLoading; const atomsWithLocation = getIn(state, ["atoms"]).filter(atom => atomUtils.hasLocation(atom) ); let locations = []; atomsWithLocation && atomsWithLocation.map(atom => { const atomLocation = atomUtils.getLocation(atom); locations.push(atomLocation); }); return { atoms, locations, atomsWithLocation, lastAtomUrisUpdateDate, friendlyLastAtomUrisUpdateTimestamp: lastAtomUrisUpdateDate && wonLabelUtils.relativeTime( generalSelectors.selectLastUpdateTime(state), lastAtomUrisUpdateDate ), atomUrisArray: atomUris && atomUris.toArray().splice(0, 200), //FIXME: CURRENTLY LIMIT TO 200 entries atomUrisSize: atomUris ? atomUris.size : 0, isOwnerAtomUrisLoading, isOwnerAtomUrisToLoad, showSlideIns: viewSelectors.hasSlideIns(state) && viewSelectors.showSlideIns(state), showModalDialog: viewSelectors.showModalDialog(state), showAtomOverlay: !!viewAtomUri, showConnectionOverlay: !!viewConnUri, viewAtomUri, viewConnUri, }; }; connect2Redux(selectFromState, actionCreators, [], this); this.$scope.$watch( () => this.isOwnerAtomUrisToLoad, () => delay(0).then(() => this.ensureAtomUrisLoaded()) ); } ensureAtomUrisLoaded() { if (this.isOwnerAtomUrisToLoad) { this.atoms__loadAllActiveAtomUrisFromOwner(); } } reload() { if (!this.isOwnerAtomUrisLoading) { this.atoms__loadAllActiveAtomUrisFromOwner(); } } } Controller.$inject = serviceDependencies; export default angular .module("won.owner.components.map", [ ngAnimate, postMessagesModule, atomMapModule, atomCardModule, postHeaderModule, ]) .controller("MapController", Controller).name;
Only display atoms with a location in the map/whatsaround view
webofneeds/won-owner-webapp/src/main/webapp/app/components/map/map.js
Only display atoms with a location in the map/whatsaround view
<ide><path>ebofneeds/won-owner-webapp/src/main/webapp/app/components/map/map.js <ide> const viewAtomUri = generalSelectors.getViewAtomUriFromRoute(state); <ide> const viewConnUri = generalSelectors.getViewConnectionUriFromRoute(state); <ide> <del> const atoms = getIn(state, ["owner", "atoms"]); <del> const atomUris = getIn(state, ["owner", "atomUris"]); <add> const atomsWithLocation = getIn(state, ["owner", "atoms"]).filter( <add> metaAtom => atomUtils.hasLocation(metaAtom) <add> ); <add> <add> const atomUrisArray = atomsWithLocation && [...atomsWithLocation.keys()]; <add> <ide> const lastAtomUrisUpdateDate = getIn(state, [ <ide> "owner", <ide> "lastAtomsUpdateTime", <ide> const isOwnerAtomUrisToLoad = <ide> !lastAtomUrisUpdateDate && !isOwnerAtomUrisLoading; <ide> <del> const atomsWithLocation = getIn(state, ["atoms"]).filter(atom => <del> atomUtils.hasLocation(atom) <del> ); <del> <ide> let locations = []; <ide> atomsWithLocation && <ide> atomsWithLocation.map(atom => { <ide> }); <ide> <ide> return { <del> atoms, <ide> locations, <ide> atomsWithLocation, <ide> lastAtomUrisUpdateDate, <ide> generalSelectors.selectLastUpdateTime(state), <ide> lastAtomUrisUpdateDate <ide> ), <del> atomUrisArray: atomUris && atomUris.toArray().splice(0, 200), //FIXME: CURRENTLY LIMIT TO 200 entries <del> atomUrisSize: atomUris ? atomUris.size : 0, <add> atomUrisArray, <add> atomUrisSize: atomsWithLocation ? atomsWithLocation.size : 0, <ide> isOwnerAtomUrisLoading, <ide> isOwnerAtomUrisToLoad, <ide> showSlideIns:
Java
apache-2.0
4724e8fb9a912ed0ec35229aaaed5111b913a194
0
googleads/googleads-mobile-flutter,googleads/googleads-mobile-flutter,googleads/googleads-mobile-flutter,googleads/googleads-mobile-flutter
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.flutter.plugins.googlemobileads; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.admanager.AdManagerAdRequest; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAd.OnNativeAdLoadedListener; import com.google.android.gms.ads.nativead.NativeAdOptions; import com.google.android.gms.ads.nativead.NativeAdView; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory; import java.util.Map; /** A wrapper for {@link NativeAd}. */ class FlutterNativeAd extends FlutterAd { private static final String TAG = "FlutterNativeAd"; @NonNull private final AdInstanceManager manager; @NonNull private final String adUnitId; @NonNull private final NativeAdFactory adFactory; @NonNull private final FlutterAdLoader flutterAdLoader; @Nullable private FlutterAdRequest request; @Nullable private FlutterAdManagerAdRequest adManagerRequest; @Nullable private Map<String, Object> customOptions; @Nullable private NativeAdView nativeAdView; @Nullable private final FlutterNativeAdOptions nativeAdOptions; static class Builder { @Nullable private AdInstanceManager manager; @Nullable private String adUnitId; @Nullable private NativeAdFactory adFactory; @Nullable private FlutterAdRequest request; @Nullable private FlutterAdManagerAdRequest adManagerRequest; @Nullable private Map<String, Object> customOptions; @Nullable private Integer id; @Nullable private FlutterNativeAdOptions nativeAdOptions; @Nullable private FlutterAdLoader flutterAdLoader; public Builder setAdFactory(@NonNull NativeAdFactory adFactory) { this.adFactory = adFactory; return this; } public Builder setId(int id) { this.id = id; return this; } public Builder setCustomOptions(@Nullable Map<String, Object> customOptions) { this.customOptions = customOptions; return this; } public Builder setManager(@NonNull AdInstanceManager manager) { this.manager = manager; return this; } public Builder setAdUnitId(@NonNull String adUnitId) { this.adUnitId = adUnitId; return this; } public Builder setRequest(@NonNull FlutterAdRequest request) { this.request = request; return this; } public Builder setAdManagerRequest(@NonNull FlutterAdManagerAdRequest request) { this.adManagerRequest = request; return this; } public Builder setNativeAdOptions(@Nullable FlutterNativeAdOptions nativeAdOptions) { this.nativeAdOptions = nativeAdOptions; return this; } public Builder setFlutterAdLoader(@NonNull FlutterAdLoader flutterAdLoader) { this.flutterAdLoader = flutterAdLoader; return this; } FlutterNativeAd build() { if (manager == null) { throw new IllegalStateException("AdInstanceManager cannot be null."); } else if (adUnitId == null) { throw new IllegalStateException("AdUnitId cannot be null."); } else if (adFactory == null) { throw new IllegalStateException("NativeAdFactory cannot be null."); } else if (request == null && adManagerRequest == null) { throw new IllegalStateException("adRequest or addManagerRequest must be non-null."); } final FlutterNativeAd nativeAd; if (request == null) { nativeAd = new FlutterNativeAd( id, manager, adUnitId, adFactory, adManagerRequest, flutterAdLoader, customOptions, nativeAdOptions); } else { nativeAd = new FlutterNativeAd( id, manager, adUnitId, adFactory, request, flutterAdLoader, customOptions, nativeAdOptions); } return nativeAd; } } protected FlutterNativeAd( int adId, @NonNull AdInstanceManager manager, @NonNull String adUnitId, @NonNull NativeAdFactory adFactory, @NonNull FlutterAdRequest request, @NonNull FlutterAdLoader flutterAdLoader, @Nullable Map<String, Object> customOptions, @Nullable FlutterNativeAdOptions nativeAdOptions) { super(adId); this.manager = manager; this.adUnitId = adUnitId; this.adFactory = adFactory; this.request = request; this.flutterAdLoader = flutterAdLoader; this.customOptions = customOptions; this.nativeAdOptions = nativeAdOptions; } protected FlutterNativeAd( int adId, @NonNull AdInstanceManager manager, @NonNull String adUnitId, @NonNull NativeAdFactory adFactory, @NonNull FlutterAdManagerAdRequest adManagerRequest, @NonNull FlutterAdLoader flutterAdLoader, @Nullable Map<String, Object> customOptions, @Nullable FlutterNativeAdOptions nativeAdOptions) { super(adId); this.manager = manager; this.adUnitId = adUnitId; this.adFactory = adFactory; this.adManagerRequest = adManagerRequest; this.flutterAdLoader = flutterAdLoader; this.customOptions = customOptions; this.nativeAdOptions = nativeAdOptions; } @Override void load() { final OnNativeAdLoadedListener loadedListener = new FlutterNativeAdLoadedListener(this); final AdListener adListener = new FlutterNativeAdListener(adId, manager); // Note we delegate loading the ad to FlutterAdLoader mainly for testing purposes. // As of 20.0.0 of GMA, mockito is unable to mock AdLoader. final NativeAdOptions options = this.nativeAdOptions == null ? new NativeAdOptions.Builder().build() : nativeAdOptions.asNativeAdOptions(); if (request != null) { flutterAdLoader.loadNativeAd( adUnitId, loadedListener, options, adListener, request.asAdRequest(adUnitId)); } else if (adManagerRequest != null) { AdManagerAdRequest adManagerAdRequest = adManagerRequest.asAdManagerAdRequest(adUnitId); flutterAdLoader.loadAdManagerNativeAd( adUnitId, loadedListener, options, adListener, adManagerAdRequest); } else { Log.e(TAG, "A null or invalid ad request was provided."); } } @Override @Nullable public PlatformView getPlatformView() { if (nativeAdView == null) { return null; } return new FlutterPlatformView(nativeAdView); } void onNativeAdLoaded(@NonNull NativeAd nativeAd) { nativeAdView = adFactory.createNativeAd(nativeAd, customOptions); nativeAd.setOnPaidEventListener(new FlutterPaidEventListener(manager, this)); manager.onAdLoaded(adId, nativeAd.getResponseInfo()); } @Override void dispose() { if (nativeAdView != null) { nativeAdView.destroy(); nativeAdView = null; } } }
packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterNativeAd.java
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.flutter.plugins.googlemobileads; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.admanager.AdManagerAdRequest; import com.google.android.gms.ads.nativead.NativeAd; import com.google.android.gms.ads.nativead.NativeAd.OnNativeAdLoadedListener; import com.google.android.gms.ads.nativead.NativeAdOptions; import com.google.android.gms.ads.nativead.NativeAdView; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory; import java.util.Map; /** A wrapper for {@link NativeAd}. */ class FlutterNativeAd extends FlutterAd { private static final String TAG = "FlutterNativeAd"; @NonNull private final AdInstanceManager manager; @NonNull private final String adUnitId; @NonNull private final NativeAdFactory adFactory; @NonNull private final FlutterAdLoader flutterAdLoader; @Nullable private FlutterAdRequest request; @Nullable private FlutterAdManagerAdRequest adManagerRequest; @Nullable private Map<String, Object> customOptions; @Nullable private NativeAdView nativeAdView; @Nullable private final FlutterNativeAdOptions nativeAdOptions; static class Builder { @Nullable private AdInstanceManager manager; @Nullable private String adUnitId; @Nullable private NativeAdFactory adFactory; @Nullable private FlutterAdRequest request; @Nullable private FlutterAdManagerAdRequest adManagerRequest; @Nullable private Map<String, Object> customOptions; @Nullable private Integer id; @Nullable private FlutterNativeAdOptions nativeAdOptions; @Nullable private FlutterAdLoader flutterAdLoader; public Builder setAdFactory(@NonNull NativeAdFactory adFactory) { this.adFactory = adFactory; return this; } public Builder setId(int id) { this.id = id; return this; } public Builder setCustomOptions(@Nullable Map<String, Object> customOptions) { this.customOptions = customOptions; return this; } public Builder setManager(@NonNull AdInstanceManager manager) { this.manager = manager; return this; } public Builder setAdUnitId(@NonNull String adUnitId) { this.adUnitId = adUnitId; return this; } public Builder setRequest(@NonNull FlutterAdRequest request) { this.request = request; return this; } public Builder setAdManagerRequest(@NonNull FlutterAdManagerAdRequest request) { this.adManagerRequest = request; return this; } public Builder setNativeAdOptions(@Nullable FlutterNativeAdOptions nativeAdOptions) { this.nativeAdOptions = nativeAdOptions; return this; } public Builder setFlutterAdLoader(@NonNull FlutterAdLoader flutterAdLoader) { this.flutterAdLoader = flutterAdLoader; return this; } FlutterNativeAd build() { if (manager == null) { throw new IllegalStateException("AdInstanceManager cannot not be null."); } else if (adUnitId == null) { throw new IllegalStateException("AdUnitId cannot not be null."); } else if (adFactory == null) { throw new IllegalStateException("NativeAdFactory cannot not be null."); } else if (request == null && adManagerRequest == null) { throw new IllegalStateException("adRequest or addManagerRequest must be non-null."); } final FlutterNativeAd nativeAd; if (request == null) { nativeAd = new FlutterNativeAd( id, manager, adUnitId, adFactory, adManagerRequest, flutterAdLoader, customOptions, nativeAdOptions); } else { nativeAd = new FlutterNativeAd( id, manager, adUnitId, adFactory, request, flutterAdLoader, customOptions, nativeAdOptions); } return nativeAd; } } protected FlutterNativeAd( int adId, @NonNull AdInstanceManager manager, @NonNull String adUnitId, @NonNull NativeAdFactory adFactory, @NonNull FlutterAdRequest request, @NonNull FlutterAdLoader flutterAdLoader, @Nullable Map<String, Object> customOptions, @Nullable FlutterNativeAdOptions nativeAdOptions) { super(adId); this.manager = manager; this.adUnitId = adUnitId; this.adFactory = adFactory; this.request = request; this.flutterAdLoader = flutterAdLoader; this.customOptions = customOptions; this.nativeAdOptions = nativeAdOptions; } protected FlutterNativeAd( int adId, @NonNull AdInstanceManager manager, @NonNull String adUnitId, @NonNull NativeAdFactory adFactory, @NonNull FlutterAdManagerAdRequest adManagerRequest, @NonNull FlutterAdLoader flutterAdLoader, @Nullable Map<String, Object> customOptions, @Nullable FlutterNativeAdOptions nativeAdOptions) { super(adId); this.manager = manager; this.adUnitId = adUnitId; this.adFactory = adFactory; this.adManagerRequest = adManagerRequest; this.flutterAdLoader = flutterAdLoader; this.customOptions = customOptions; this.nativeAdOptions = nativeAdOptions; } @Override void load() { final OnNativeAdLoadedListener loadedListener = new FlutterNativeAdLoadedListener(this); final AdListener adListener = new FlutterNativeAdListener(adId, manager); // Note we delegate loading the ad to FlutterAdLoader mainly for testing purposes. // As of 20.0.0 of GMA, mockito is unable to mock AdLoader. final NativeAdOptions options = this.nativeAdOptions == null ? new NativeAdOptions.Builder().build() : nativeAdOptions.asNativeAdOptions(); if (request != null) { flutterAdLoader.loadNativeAd( adUnitId, loadedListener, options, adListener, request.asAdRequest(adUnitId)); } else if (adManagerRequest != null) { AdManagerAdRequest adManagerAdRequest = adManagerRequest.asAdManagerAdRequest(adUnitId); flutterAdLoader.loadAdManagerNativeAd( adUnitId, loadedListener, options, adListener, adManagerAdRequest); } else { Log.e(TAG, "A null or invalid ad request was provided."); } } @Override @Nullable public PlatformView getPlatformView() { if (nativeAdView == null) { return null; } return new FlutterPlatformView(nativeAdView); } void onNativeAdLoaded(@NonNull NativeAd nativeAd) { nativeAdView = adFactory.createNativeAd(nativeAd, customOptions); nativeAd.setOnPaidEventListener(new FlutterPaidEventListener(manager, this)); manager.onAdLoaded(adId, nativeAd.getResponseInfo()); } @Override void dispose() { if (nativeAdView != null) { nativeAdView.destroy(); nativeAdView = null; } } }
Remove double negatives (`cannot not`) in errors (#671) `FlutterNativeAd.Builder.build()` alerts the caller to invalid `null` values with messages of the form: xxx cannot not be null This replaces that double negative with simpler and more correct messages of the form: xxx cannot be null
packages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterNativeAd.java
Remove double negatives (`cannot not`) in errors (#671)
<ide><path>ackages/google_mobile_ads/android/src/main/java/io/flutter/plugins/googlemobileads/FlutterNativeAd.java <ide> <ide> FlutterNativeAd build() { <ide> if (manager == null) { <del> throw new IllegalStateException("AdInstanceManager cannot not be null."); <add> throw new IllegalStateException("AdInstanceManager cannot be null."); <ide> } else if (adUnitId == null) { <del> throw new IllegalStateException("AdUnitId cannot not be null."); <add> throw new IllegalStateException("AdUnitId cannot be null."); <ide> } else if (adFactory == null) { <del> throw new IllegalStateException("NativeAdFactory cannot not be null."); <add> throw new IllegalStateException("NativeAdFactory cannot be null."); <ide> } else if (request == null && adManagerRequest == null) { <ide> throw new IllegalStateException("adRequest or addManagerRequest must be non-null."); <ide> }
JavaScript
apache-2.0
d3d1d313ab4c325ba6678b906b182a5dda584c7d
0
autoserver-org/autoserver,autoserver-org/autoserver
'use strict'; // Turn a `commandpath` into a `collname`, using schema information const getColl = function ({ commandpath, schema, top: { collname, command: { multiple } }, }) { // Ignore array indices const commandpathA = commandpath.filter(key => typeof key !== 'number'); // This means this is the top-level action if (commandpathA.length === 0) { return { collname, multiple }; } return findColl({ schema, collname, commandpath: commandpathA }); }; // Recurse over `schema.collections`, using `commandpath` const findColl = function ({ schema, schema: { collections }, collname, commandpath, }) { const [attrName, ...childCommandpath] = commandpath; const attr = collections[collname].attributes[attrName]; // Erronous `commandpath` if (attr === undefined) { return; } const { target: childCollname, isArray } = attr; if (childCommandpath.length !== 0) { return findColl({ schema, collname: childCollname, commandpath: childCommandpath, }); } return { collname: childCollname, multiple: isArray }; }; module.exports = { getColl, };
src/middleware/action/get_coll.js
'use strict'; // Turn a `commandpath` into a `collname`, using schema information const getColl = function ({ commandpath, schema, top: { collname, command: { multiple } }, }) { // Ignore array indices const commandpathA = commandpath.filter(key => typeof key !== 'number'); // This means this is the top-level action if (commandpathA.length === 0) { return { collname, multiple }; } return findColl({ schema, collname, commandpath: commandpathA }); }; // Recurse over `schema.collections`, using `commandpath` const findColl = function ({ schema, schema: { collections }, collname, commandpath, }) { const [attrName, ...childCommandpath] = commandpath; const coll = collections[collname].attributes[attrName]; // Erronous `commandpath` if (coll === undefined) { return; } const { target: childCollname, isArray } = coll; if (childCommandpath.length !== 0) { return findColl({ schema, collname: childCollname, commandpath: childCommandpath, }); } return { collname: childCollname, multiple: isArray }; }; module.exports = { getColl, };
Rename variables
src/middleware/action/get_coll.js
Rename variables
<ide><path>rc/middleware/action/get_coll.js <ide> commandpath, <ide> }) { <ide> const [attrName, ...childCommandpath] = commandpath; <del> const coll = collections[collname].attributes[attrName]; <add> const attr = collections[collname].attributes[attrName]; <ide> <ide> // Erronous `commandpath` <del> if (coll === undefined) { return; } <add> if (attr === undefined) { return; } <ide> <del> const { target: childCollname, isArray } = coll; <add> const { target: childCollname, isArray } = attr; <ide> <ide> if (childCommandpath.length !== 0) { <ide> return findColl({
Java
agpl-3.0
eb46887e924cd6c04fb89559f01cc454e18616fb
0
retest/recheck,retest/recheck
package de.retest.recheck; import java.util.Set; import de.retest.recheck.report.ActionReplayResult; import de.retest.recheck.ui.DefaultValueFinder; import de.retest.recheck.ui.descriptors.RootElement; /** * Interface to help recheck transform an arbitrary object into its internal format to allow persistence, state diffing * and ignoring of attributes and elements. */ public interface RecheckAdapter { /** * Returns {@code true} if the given object can be converted by the adapter. * * @param toVerify * the object to verify * @return true if the given object can be converted by the adapter */ boolean canCheck( Object toVerify ); /** * Convert the given object into a {@code RootElement} (respectively into a set of {@code RootElement}s if this is * sensible for this type of object). * * @param toVerify * the object to verify * @return The RootElement(s) for the given object */ Set<RootElement> convert( Object toVerify ); /** * Returns a {@code DefaultValueFinder} for the converted element attributes. Default values of attributes are * omitted in the Golden Master to not bloat it. * * @return The DefaultValueFinder for the converted element attributes */ DefaultValueFinder getDefaultValueFinder(); /** * Notifies about differences in the given {@code ActionReplayResult}. * * @param actionReplayResult * The {@code ActionReplayResult} containing differences to be notified about. */ default void notifyAboutDifferences( final ActionReplayResult actionReplayResult ) {} }
src/main/java/de/retest/recheck/RecheckAdapter.java
package de.retest.recheck; import java.util.Set; import de.retest.recheck.ui.DefaultValueFinder; import de.retest.recheck.ui.descriptors.RootElement; /** * Interface to help recheck transform an arbitrary object into its internal format to allow persistence, state diffing * and ignoring of attributes and elements. */ public interface RecheckAdapter { /** * Returns {@code true} if the given object can be converted by the adapter. * * @param toVerify * the object to verify * @return true if the given object can be converted by the adapter */ boolean canCheck( Object toVerify ); /** * Convert the given object into a {@code RootElement} (respectively into a set of {@code RootElement}s if this is * sensible for this type of object). * * @param toVerify * the object to verify * @return The RootElement(s) for the given object */ Set<RootElement> convert( Object toVerify ); /** * Returns a {@code DefaultValueFinder} for the converted element attributes. Default values of attributes are * omitted in the Golden Master to not bloat it. * * @return The DefaultValueFinder for the converted element attributes */ DefaultValueFinder getDefaultValueFinder(); }
Add possibility to warn adapter
src/main/java/de/retest/recheck/RecheckAdapter.java
Add possibility to warn adapter
<ide><path>rc/main/java/de/retest/recheck/RecheckAdapter.java <ide> <ide> import java.util.Set; <ide> <add>import de.retest.recheck.report.ActionReplayResult; <ide> import de.retest.recheck.ui.DefaultValueFinder; <ide> import de.retest.recheck.ui.descriptors.RootElement; <ide> <ide> */ <ide> DefaultValueFinder getDefaultValueFinder(); <ide> <add> /** <add> * Notifies about differences in the given {@code ActionReplayResult}. <add> * <add> * @param actionReplayResult <add> * The {@code ActionReplayResult} containing differences to be notified about. <add> */ <add> default void notifyAboutDifferences( final ActionReplayResult actionReplayResult ) {} <add> <ide> }
Java
agpl-3.0
08f119faba095e281582bcdbf60406f27a0ca4f7
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
7452f1f2-2e62-11e5-9284-b827eb9e62be
hello.java
744d86d6-2e62-11e5-9284-b827eb9e62be
7452f1f2-2e62-11e5-9284-b827eb9e62be
hello.java
7452f1f2-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>744d86d6-2e62-11e5-9284-b827eb9e62be <add>7452f1f2-2e62-11e5-9284-b827eb9e62be
Java
mit
bf94ea4e64627774c6051f8f534391c69a4a1501
0
sahana/vesuvius,ramdesh/vesuvius_installer,ramdesh/vesuvius_installer,bobrock/vesuvius,bobrock/vesuvius,ramdesh/vesuvius_installer,bobrock/vesuvius,bobrock/vesuvius,sahana/vesuvius,sahana/vesuvius,ramdesh/vesuvius_installer,bobrock/vesuvius,sahana/vesuvius,bobrock/vesuvius,sahana/vesuvius
/* * Created on Dec 30, 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package org.campdb.db; import org.campdb.business.*; import org.campdb.util.LabelValue; import org.sahana.share.db.DBConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * @author Administrator * <p/> * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class DataAccessManager implements DBConstants{ //todo: load @ startup - & reload when ever edit/add/modify public DataAccessManager() { } private String getDistrictCode(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); String sqlString = SQLGenerator.getSQLForDistrictCode(campTO.getDivisionId()); pstmt = connection.prepareStatement(sqlString); resultSet = pstmt.executeQuery(); if (resultSet.next()) { return resultSet.getString(TableColumns.DIST_CODE); } } finally { closeConnections(connection, pstmt, resultSet); } return null; } private String getProvinceCode(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); String sqlString = SQLGenerator.getSQLForProvinceCode(campTO.getDistrictCode()); pstmt = connection.prepareStatement(sqlString); resultSet = pstmt.executeQuery(); if (resultSet.next()) { return resultSet.getString(TableColumns.PROV_CODE); } } finally { closeConnections(connection, pstmt, resultSet); } return null; } //campdb public boolean addCamp(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; boolean returnValue = false; try { connection = DBConnection.createConnection(); connection.setAutoCommit(false); String sqlString = SQLGenerator.getSQLAddCamp(); pstmt = connection.prepareStatement(sqlString); pstmt.setString(1, campTO.getAreaName()); pstmt.setString(2, campTO.getDivisionId()); pstmt.setString(3, getDistrictCode(campTO)); campTO.setDistrictCode(getDistrictCode(campTO)); pstmt.setString(4, getProvinceCode(campTO)); campTO.setProvienceCode(getProvinceCode(campTO)); pstmt.setString(5, campTO.getCampName()); pstmt.setString(6, campTO.getCampAccesability()); pstmt.setString(7, campTO.getCampMen()); pstmt.setString(8, campTO.getCampWomen()); pstmt.setString(9, campTO.getCampChildren()); pstmt.setString(10, campTO.getCampTotal()); pstmt.setString(11, campTO.getCampCapability()); pstmt.setString(12, campTO.getCampContactPerson()); pstmt.setString(13, campTO.getCampContactNumber()); pstmt.setString(14, campTO.getCampComment()); pstmt.setDate(15,new java.sql.Date(campTO.getUpdateDate().getTime())); pstmt.setDate(16,new java.sql.Date(new java.util.Date().getTime())); pstmt.setString(17,campTO.getCampFamily()); pstmt.execute(); connection.commit(); returnValue = true; }catch(Exception e){ returnValue = false; connection.rollback(); } finally { connection.setAutoCommit(true); closeConnections(connection, pstmt, null); } return returnValue; } public List getHistory(CampTO campTO) throws SQLException{ List returnList = new ArrayList(); Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; CampHistoryTO tempHistoryTO = null; try { connection = DBConnection.createConnection(); pstmt = connection.prepareStatement(SQLGenerator.getSQLGetHistory()); pstmt.setString(1, campTO.getCampId()); rs = pstmt.executeQuery(); while(rs.next()){ tempHistoryTO = new CampHistoryTO(); tempHistoryTO.setCampHistoryId(rs.getString(DBConstants.TableColumns.HISTORY_ID)); tempHistoryTO.setCampId(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_ID)); tempHistoryTO.setCampMen(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_MEN)); tempHistoryTO.setCampWomen(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_WOMEN)); tempHistoryTO.setCampTotal(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_TOTAL)); tempHistoryTO.setCampFamily(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_FAMILY)); tempHistoryTO.setUpdateDate(rs.getDate(DBConstants.TableColumns.HISTORY_UPDATED_DATE)); //tempHistoryTO.setUpdateTime(rs.getDate(DBConstants.TableColumns.HISTORY_UPDATED_TIME)); returnList.add(tempHistoryTO); } }catch(Exception e){ e.printStackTrace(); } finally { closeConnections(connection, pstmt, null); } return returnList; } private void addCampHistory(CampTO campTO,Connection connection) throws SQLException{ String sqlString = SQLGenerator.getSQLInsertHistory(); PreparedStatement pstmt = connection.prepareStatement(sqlString); pstmt.setString(1, campTO.getCampId()); pstmt.setString(2, campTO.getCampMen()); pstmt.setString(3, campTO.getCampWomen()); pstmt.setString(4, campTO.getCampChildren()); pstmt.setString(5, campTO.getCampTotal()); pstmt.setString(6, campTO.getCampFamily()); pstmt.setDate(7, new java.sql.Date(campTO.getUpdateDate().getTime())); pstmt.setDate(8, new java.sql.Date(new java.util.Date().getTime())); pstmt.executeUpdate(); } private void editCampRecord(CampTO campTO,Connection connection) throws SQLException,Exception{ String sqlString = SQLGenerator.getSQLEditCamp(); PreparedStatement pstmt = connection.prepareStatement(sqlString); pstmt.setString(1, campTO.getAreaName()); pstmt.setString(2, campTO.getDivisionId()); pstmt.setString(3, getDistrictCode(campTO)); campTO.setDistrictCode(getDistrictCode(campTO)); pstmt.setString(4, getProvinceCode(campTO)); campTO.setProvienceCode(getProvinceCode(campTO)); pstmt.setString(5, campTO.getCampName()); pstmt.setString(6, campTO.getCampAccesability()); pstmt.setString(7, campTO.getCampMen()); pstmt.setString(8, campTO.getCampWomen()); pstmt.setString(9, campTO.getCampChildren()); pstmt.setString(10, campTO.getCampTotal()); pstmt.setString(11, campTO.getCampCapability()); pstmt.setString(12, campTO.getCampContactPerson()); pstmt.setString(13, campTO.getCampContactNumber()); pstmt.setString(14, campTO.getCampComment()); pstmt.setDate(15,new java.sql.Date(campTO.getUpdateDate().getTime())); pstmt.setDate(16,new java.sql.Date(new java.util.Date().getTime())); pstmt.setString(17,campTO.getCampFamily()); pstmt.setString(18,campTO.getCampId()); pstmt.execute(); } public boolean editCamp(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; boolean returnValue = false; try { connection = DBConnection.createConnection(); connection.setAutoCommit(false); //get the original data CampTO tempCampTo = searchCamp(Integer.parseInt(campTO.getCampId())); //put the original in the history table addCampHistory(tempCampTo,connection); //edit the original record editCampRecord(campTO,connection); connection.commit(); returnValue = true; }catch(Exception e){ returnValue = false; e.printStackTrace(); connection.rollback(); } finally { connection.setAutoCommit(true); closeConnections(connection, pstmt, null); } return returnValue; } public boolean deleteCamp(int campId) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; try { connection = DBConnection.createConnection(); String sqlString = SQLGenerator.getSQLDeleteCamp(); pstmt = connection.prepareStatement(sqlString); pstmt.setInt(1, campId); return pstmt.execute(); } finally { closeConnections(connection, pstmt, null); } } public List searchCamps(String campName, String provinceCode, String districtCode, int divisionId) throws SQLException, Exception { Connection connection = null; Connection connection2 = null; Statement stmt = null; Statement stmt2 = null; ResultSet resultSet = null; ResultSet tempRS = null; try { connection = DBConnection.createConnection(); connection2 = DBConnection.createConnection(); connection2.setAutoCommit(false); // Setting the Request Header data. String sqlSearchString = SQLGenerator.getSQLForSearchCriteria(campName, provinceCode, districtCode, divisionId); stmt = connection.createStatement(); stmt2 = connection2.createStatement(); resultSet = stmt.executeQuery(sqlSearchString); List returnSearchTOs = new ArrayList(); CampTO campTo; while (resultSet.next()) { campTo = new CampTO(); campTo.setAreaName(resultSet.getString("AREA_NAME")); campTo.setCampAccesability(resultSet.getString("CAMP_ACCESABILITY")); campTo.setCampCapability(resultSet.getString("CAMP_CAPABILITY")); campTo.setCampChildren(resultSet.getString("CAMP_CHILDREN")); campTo.setCampComment(resultSet.getString("CAMP_COMMENT")); campTo.setCampContactNumber(resultSet.getString("CAMP_CONTACT_NUMBER")); campTo.setCampContactPerson(resultSet.getString("CAMP_CONTACT_PERSON")); campTo.setCampId(resultSet.getString("CAMP_ID")); campTo.setCampMen(resultSet.getString("CAMP_MEN")); campTo.setCampTotal(resultSet.getString("CAMP_TOTAL")); campTo.setCampName(resultSet.getString("CAMP_NAME")); campTo.setCampWomen(resultSet.getString("CAMP_WOMEN")); campTo.setDistrictCode(resultSet.getString("DIST_CODE")); campTo.setDivisionId(resultSet.getString("DIV_ID")); campTo.setProvienceCode(resultSet.getString("PROV_CODE")); sqlSearchString = SQLGenerator.getSQLForDivisionName(Integer.parseInt(campTo.getDivisionId())); tempRS = stmt2.executeQuery(sqlSearchString); if (tempRS.next()) campTo.setDivionName(tempRS.getString("DIV_NAME")); sqlSearchString = SQLGenerator.getSQLForDistrictName(campTo.getDistrictCode()); tempRS = stmt2.executeQuery(sqlSearchString); if (tempRS.next()) campTo.setDistrictName(tempRS.getString("DIST_NAME")); sqlSearchString = SQLGenerator.getSQLForProvienceName(campTo.getProvienceCode()); tempRS = stmt2.executeQuery(sqlSearchString); if (tempRS.next()) campTo.setProvienceName(tempRS.getString("PROV_NAME")); returnSearchTOs.add(campTo); } return returnSearchTOs; } finally { closeConnections(connection, stmt, resultSet); closeConnections(connection2, stmt2, tempRS); } } public CampTO searchCamp(int campId) throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); String sqlString = SQLGenerator.getSQLForSearchCriteria(campId); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); CampTO campTo = null; if (resultSet.next()) { campTo = new CampTO(); campTo.setAreaName(resultSet.getString("AREA_NAME")); campTo.setCampAccesability(resultSet.getString("CAMP_ACCESABILITY")); campTo.setCampCapability(resultSet.getString("CAMP_CAPABILITY")); campTo.setCampChildren(resultSet.getString("CAMP_CHILDREN")); campTo.setCampComment(resultSet.getString("CAMP_COMMENT")); campTo.setCampContactNumber(resultSet.getString("CAMP_CONTACT_NUMBER")); campTo.setCampContactPerson(resultSet.getString("CAMP_CONTACT_PERSON")); campTo.setCampId(resultSet.getString("CAMP_ID")); campTo.setCampMen(resultSet.getString("CAMP_MEN")); campTo.setCampName(resultSet.getString("CAMP_NAME")); campTo.setCampWomen(resultSet.getString("CAMP_WOMEN")); campTo.setCampTotal(resultSet.getString("CAMP_TOTAL")); campTo.setDistrictCode(resultSet.getString("DIST_CODE")); campTo.setDivisionId(resultSet.getString("DIV_ID")); campTo.setProvienceCode(resultSet.getString("PROV_CODE")); } else { return null; } //todo: should use outer joint sqlString = SQLGenerator.getSQLForProvienceName(campTo.getProvienceCode()); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { campTo.setProvienceName(resultSet.getString("PROV_NAME")); } sqlString = SQLGenerator.getSQLForDistrictName(campTo.getDistrictCode()); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { campTo.setDistrictName(resultSet.getString("DIST_NAME")); } sqlString = SQLGenerator.getSQLForDivisionName(Integer.parseInt(campTo.getDivisionId())); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { campTo.setDivionName(resultSet.getString("DIV_NAME")); } return campTo; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listProvicences() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForProvienceList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("PROV_NAME"); String value = resultSet.getString("PROV_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDistricts() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDistrictList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIST_NAME"); String value = resultSet.getString("DIST_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDistrictsOrderbyProvince() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDistrictList(); sqlString = sqlString + " order by PROV_CODE"; preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIST_NAME"); String value = resultSet.getString("DIST_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDistrictwithProvince(String provinceID) throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDistrictListWithProvince(provinceID); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIST_NAME"); String value = resultSet.getString("DIST_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDivisions() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); // Setting the Request Header data. //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDivisionList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIV_NAME"); String value = resultSet.getString("DIV_ID"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDivisionsforDistrcit(String disstrictName) throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); // Setting the Request Header data. //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDivisionListforDistrict(disstrictName); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIV_NAME"); String value = resultSet.getString("DIV_ID"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listAreas() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); // Setting the Request Header data. //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForAreaList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("AREA_NAME"); String value = resultSet.getString("AREA_ID"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } private static void closeResultSet (ResultSet resultSet) { // close the result set if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } } private static void closeConnection (Connection connection) { // close the connection if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * Closes the open connections * * @param connection * @param resultSet */ private static void closeConnections (Connection connection, Statement statement, ResultSet resultSet) { closeStatement(statement); closeResultSet(resultSet); closeConnection(connection); } private static void closeStatement (Statement statement) { // close the statement if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } public User loginSuccess(String userName, String password) throws SQLException, Exception { Connection conn = DBConnection.createConnection(); Statement s = null; ResultSet rs = null; try { String sql = SQLGenerator.getSQLForLogin(userName); s = conn.createStatement(); rs = s.executeQuery(sql); if (rs.next()) { String realpassword = rs.getString(DBConstants.TableColumns.PASSWORD); String organization = rs.getString(DBConstants.TableColumns.ORGANIZATION); User user = new User(userName, organization); if (realpassword.equals(password)) { return user; } } } finally { closeConnections(conn, s, rs); } return null; } public List validateCampTOforInsert(CampTO campTO) throws SQLException, Exception { List result = campTO.validate(); if (!result.isEmpty()) { return result; } Connection connection = null; Statement stmt = null; ResultSet rs = null; String sqlString; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); stmt = connection.createStatement(); String areaId, divisionId, districtCode, provCode; if (campTO.getAreadId() != null) { areaId = campTO.getAreadId(); sqlString = SQLGenerator.getSQLForAreaDivision(areaId); rs = stmt.executeQuery(sqlString); if (rs.next()) { divisionId = rs.getString("DIV_ID"); if (campTO.getDivisionId() != null) { if (!divisionId.equals(campTO.getAreadId())) { result.add("Area doesn't exist in the Division"); return result; } } sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("Division doesn't exist "); return result; } districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("District doesn't exist "); return result; } provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("Division doesn't exist in the District "); return result; } } } else { result.add("Area doesn't exist"); return result; } } else if (campTO.getDivisionId() != null) { divisionId = campTO.getDivisionId(); sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); if (rs.next()) { districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("District doesn't exist "); return result; } provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("Division doesn't exist"); return result; } } else { districtCode = campTO.getDistrictCode(); sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (rs.next()) { provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("District doesn't exist"); return result; } } } //end try finally { closeConnections(connection, stmt, rs); } return result; } public List validateCampTOforEdit(CampTO campTO) throws SQLException, Exception { List result = campTO.validate(); if (!result.isEmpty()) { return result; } Connection connection = null; Statement stmt = null; ResultSet rs = null; String sqlString; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); stmt = connection.createStatement(); String campId = campTO.getCampId(); sqlString = SQLGenerator.getSQLForEditCamp(campId); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("Camp Id doesn't exist in the table"); return result; } String areaId, divisionId, districtCode, provCode; if (campTO.getAreadId() != null) { areaId = campTO.getAreadId(); sqlString = SQLGenerator.getSQLForAreaDivision(areaId); rs = stmt.executeQuery(sqlString); if (rs.next()) { divisionId = rs.getString("DIV_ID"); if (campTO.getDivisionId() != null) { if (!divisionId.equals(campTO.getAreadId())) { result.add("Area doesn't exist in the Division"); return result; } } sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("Area doesn't exist"); return result; } } else if (campTO.getDivisionId() != null) { divisionId = campTO.getDivisionId(); sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); if (rs.next()) { districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("Division doesn't exist"); return result; } } else { districtCode = campTO.getDistrictCode(); sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (rs.next()) { provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("District doesn't exist"); return result; } } } //end try finally { closeConnections(connection, stmt, rs); } return result; } public ArrayList getDivisionRelatedInfo() throws Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDivisionInfo(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); ArrayList arrayList = new ArrayList(100); while (resultSet.next()) { String id = resultSet.getString("DIV_ID"); String districtName = resultSet.getString("DIST_NAME"); String provName = resultSet.getString("PROV_NAME"); arrayList.add(" District : " + districtName + " Province : " + provName); } return arrayList; } finally { closeConnections(connection, preparedStatement, resultSet); } } }
sahana-phase1/campreg/src/org/campdb/db/DataAccessManager.java
/* * Created on Dec 30, 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package org.campdb.db; import org.campdb.business.*; import org.campdb.util.LabelValue; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Collection; /** * @author Administrator * <p/> * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class DataAccessManager implements DBConstants{ //todo: load @ startup - & reload when ever edit/add/modify public DataAccessManager() { } private String getDistrictCode(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); String sqlString = SQLGenerator.getSQLForDistrictCode(campTO.getDivisionId()); pstmt = connection.prepareStatement(sqlString); resultSet = pstmt.executeQuery(); if (resultSet.next()) { return resultSet.getString(TableColumns.DIST_CODE); } } finally { closeConnections(connection, pstmt, resultSet); } return null; } private String getProvinceCode(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); String sqlString = SQLGenerator.getSQLForProvinceCode(campTO.getDistrictCode()); pstmt = connection.prepareStatement(sqlString); resultSet = pstmt.executeQuery(); if (resultSet.next()) { return resultSet.getString(TableColumns.PROV_CODE); } } finally { closeConnections(connection, pstmt, resultSet); } return null; } //campdb public boolean addCamp(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; boolean returnValue = false; try { connection = DBConnection.createConnection(); connection.setAutoCommit(false); String sqlString = SQLGenerator.getSQLAddCamp(); pstmt = connection.prepareStatement(sqlString); pstmt.setString(1, campTO.getAreaName()); pstmt.setString(2, campTO.getDivisionId()); pstmt.setString(3, getDistrictCode(campTO)); campTO.setDistrictCode(getDistrictCode(campTO)); pstmt.setString(4, getProvinceCode(campTO)); campTO.setProvienceCode(getProvinceCode(campTO)); pstmt.setString(5, campTO.getCampName()); pstmt.setString(6, campTO.getCampAccesability()); pstmt.setString(7, campTO.getCampMen()); pstmt.setString(8, campTO.getCampWomen()); pstmt.setString(9, campTO.getCampChildren()); pstmt.setString(10, campTO.getCampTotal()); pstmt.setString(11, campTO.getCampCapability()); pstmt.setString(12, campTO.getCampContactPerson()); pstmt.setString(13, campTO.getCampContactNumber()); pstmt.setString(14, campTO.getCampComment()); pstmt.setDate(15,new java.sql.Date(campTO.getUpdateDate().getTime())); pstmt.setDate(16,new java.sql.Date(new java.util.Date().getTime())); pstmt.setString(17,campTO.getCampFamily()); pstmt.execute(); connection.commit(); returnValue = true; }catch(Exception e){ returnValue = false; connection.rollback(); } finally { connection.setAutoCommit(true); closeConnections(connection, pstmt, null); } return returnValue; } public List getHistory(CampTO campTO) throws SQLException{ List returnList = new ArrayList(); Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; CampHistoryTO tempHistoryTO = null; try { connection = DBConnection.createConnection(); pstmt = connection.prepareStatement(SQLGenerator.getSQLGetHistory()); pstmt.setString(1, campTO.getCampId()); rs = pstmt.executeQuery(); while(rs.next()){ tempHistoryTO = new CampHistoryTO(); tempHistoryTO.setCampHistoryId(rs.getString(DBConstants.TableColumns.HISTORY_ID)); tempHistoryTO.setCampId(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_ID)); tempHistoryTO.setCampMen(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_MEN)); tempHistoryTO.setCampWomen(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_WOMEN)); tempHistoryTO.setCampTotal(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_TOTAL)); tempHistoryTO.setCampFamily(rs.getString(DBConstants.TableColumns.HISTORY_CAMP_FAMILY)); tempHistoryTO.setUpdateDate(rs.getDate(DBConstants.TableColumns.HISTORY_UPDATED_DATE)); //tempHistoryTO.setUpdateTime(rs.getDate(DBConstants.TableColumns.HISTORY_UPDATED_TIME)); returnList.add(tempHistoryTO); } }catch(Exception e){ e.printStackTrace(); } finally { closeConnections(connection, pstmt, null); } return returnList; } private void addCampHistory(CampTO campTO,Connection connection) throws SQLException{ String sqlString = SQLGenerator.getSQLInsertHistory(); PreparedStatement pstmt = connection.prepareStatement(sqlString); pstmt.setString(1, campTO.getCampId()); pstmt.setString(2, campTO.getCampMen()); pstmt.setString(3, campTO.getCampWomen()); pstmt.setString(4, campTO.getCampChildren()); pstmt.setString(5, campTO.getCampTotal()); pstmt.setString(6, campTO.getCampFamily()); pstmt.setDate(7, new java.sql.Date(campTO.getUpdateDate().getTime())); pstmt.setDate(8, new java.sql.Date(new java.util.Date().getTime())); pstmt.executeUpdate(); } private void editCampRecord(CampTO campTO,Connection connection) throws SQLException,Exception{ String sqlString = SQLGenerator.getSQLEditCamp(); PreparedStatement pstmt = connection.prepareStatement(sqlString); pstmt.setString(1, campTO.getAreaName()); pstmt.setString(2, campTO.getDivisionId()); pstmt.setString(3, getDistrictCode(campTO)); campTO.setDistrictCode(getDistrictCode(campTO)); pstmt.setString(4, getProvinceCode(campTO)); campTO.setProvienceCode(getProvinceCode(campTO)); pstmt.setString(5, campTO.getCampName()); pstmt.setString(6, campTO.getCampAccesability()); pstmt.setString(7, campTO.getCampMen()); pstmt.setString(8, campTO.getCampWomen()); pstmt.setString(9, campTO.getCampChildren()); pstmt.setString(10, campTO.getCampTotal()); pstmt.setString(11, campTO.getCampCapability()); pstmt.setString(12, campTO.getCampContactPerson()); pstmt.setString(13, campTO.getCampContactNumber()); pstmt.setString(14, campTO.getCampComment()); pstmt.setDate(15,new java.sql.Date(campTO.getUpdateDate().getTime())); pstmt.setDate(16,new java.sql.Date(new java.util.Date().getTime())); pstmt.setString(17,campTO.getCampFamily()); pstmt.setString(18,campTO.getCampId()); pstmt.execute(); } public boolean editCamp(CampTO campTO) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; boolean returnValue = false; try { connection = DBConnection.createConnection(); connection.setAutoCommit(false); //get the original data CampTO tempCampTo = searchCamp(Integer.parseInt(campTO.getCampId())); //put the original in the history table addCampHistory(tempCampTo,connection); //edit the original record editCampRecord(campTO,connection); connection.commit(); returnValue = true; }catch(Exception e){ returnValue = false; e.printStackTrace(); connection.rollback(); } finally { connection.setAutoCommit(true); closeConnections(connection, pstmt, null); } return returnValue; } public boolean deleteCamp(int campId) throws SQLException, Exception { Connection connection = null; PreparedStatement pstmt = null; try { connection = DBConnection.createConnection(); String sqlString = SQLGenerator.getSQLDeleteCamp(); pstmt = connection.prepareStatement(sqlString); pstmt.setInt(1, campId); return pstmt.execute(); } finally { closeConnections(connection, pstmt, null); } } public List searchCamps(String campName, String provinceCode, String districtCode, int divisionId) throws SQLException, Exception { Connection connection = null; Connection connection2 = null; Statement stmt = null; Statement stmt2 = null; ResultSet resultSet = null; ResultSet tempRS = null; try { connection = DBConnection.createConnection(); connection2 = DBConnection.createConnection(); connection2.setAutoCommit(false); // Setting the Request Header data. String sqlSearchString = SQLGenerator.getSQLForSearchCriteria(campName, provinceCode, districtCode, divisionId); stmt = connection.createStatement(); stmt2 = connection2.createStatement(); resultSet = stmt.executeQuery(sqlSearchString); List returnSearchTOs = new ArrayList(); CampTO campTo; while (resultSet.next()) { campTo = new CampTO(); campTo.setAreaName(resultSet.getString("AREA_NAME")); campTo.setCampAccesability(resultSet.getString("CAMP_ACCESABILITY")); campTo.setCampCapability(resultSet.getString("CAMP_CAPABILITY")); campTo.setCampChildren(resultSet.getString("CAMP_CHILDREN")); campTo.setCampComment(resultSet.getString("CAMP_COMMENT")); campTo.setCampContactNumber(resultSet.getString("CAMP_CONTACT_NUMBER")); campTo.setCampContactPerson(resultSet.getString("CAMP_CONTACT_PERSON")); campTo.setCampId(resultSet.getString("CAMP_ID")); campTo.setCampMen(resultSet.getString("CAMP_MEN")); campTo.setCampTotal(resultSet.getString("CAMP_TOTAL")); campTo.setCampName(resultSet.getString("CAMP_NAME")); campTo.setCampWomen(resultSet.getString("CAMP_WOMEN")); campTo.setDistrictCode(resultSet.getString("DIST_CODE")); campTo.setDivisionId(resultSet.getString("DIV_ID")); campTo.setProvienceCode(resultSet.getString("PROV_CODE")); sqlSearchString = SQLGenerator.getSQLForDivisionName(Integer.parseInt(campTo.getDivisionId())); tempRS = stmt2.executeQuery(sqlSearchString); if (tempRS.next()) campTo.setDivionName(tempRS.getString("DIV_NAME")); sqlSearchString = SQLGenerator.getSQLForDistrictName(campTo.getDistrictCode()); tempRS = stmt2.executeQuery(sqlSearchString); if (tempRS.next()) campTo.setDistrictName(tempRS.getString("DIST_NAME")); sqlSearchString = SQLGenerator.getSQLForProvienceName(campTo.getProvienceCode()); tempRS = stmt2.executeQuery(sqlSearchString); if (tempRS.next()) campTo.setProvienceName(tempRS.getString("PROV_NAME")); returnSearchTOs.add(campTo); } return returnSearchTOs; } finally { closeConnections(connection, stmt, resultSet); closeConnections(connection2, stmt2, tempRS); } } public CampTO searchCamp(int campId) throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); String sqlString = SQLGenerator.getSQLForSearchCriteria(campId); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); CampTO campTo = null; if (resultSet.next()) { campTo = new CampTO(); campTo.setAreaName(resultSet.getString("AREA_NAME")); campTo.setCampAccesability(resultSet.getString("CAMP_ACCESABILITY")); campTo.setCampCapability(resultSet.getString("CAMP_CAPABILITY")); campTo.setCampChildren(resultSet.getString("CAMP_CHILDREN")); campTo.setCampComment(resultSet.getString("CAMP_COMMENT")); campTo.setCampContactNumber(resultSet.getString("CAMP_CONTACT_NUMBER")); campTo.setCampContactPerson(resultSet.getString("CAMP_CONTACT_PERSON")); campTo.setCampId(resultSet.getString("CAMP_ID")); campTo.setCampMen(resultSet.getString("CAMP_MEN")); campTo.setCampName(resultSet.getString("CAMP_NAME")); campTo.setCampWomen(resultSet.getString("CAMP_WOMEN")); campTo.setCampTotal(resultSet.getString("CAMP_TOTAL")); campTo.setDistrictCode(resultSet.getString("DIST_CODE")); campTo.setDivisionId(resultSet.getString("DIV_ID")); campTo.setProvienceCode(resultSet.getString("PROV_CODE")); } else { return null; } //todo: should use outer joint sqlString = SQLGenerator.getSQLForProvienceName(campTo.getProvienceCode()); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { campTo.setProvienceName(resultSet.getString("PROV_NAME")); } sqlString = SQLGenerator.getSQLForDistrictName(campTo.getDistrictCode()); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { campTo.setDistrictName(resultSet.getString("DIST_NAME")); } sqlString = SQLGenerator.getSQLForDivisionName(Integer.parseInt(campTo.getDivisionId())); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { campTo.setDivionName(resultSet.getString("DIV_NAME")); } return campTo; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listProvicences() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForProvienceList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("PROV_NAME"); String value = resultSet.getString("PROV_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDistricts() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDistrictList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIST_NAME"); String value = resultSet.getString("DIST_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDistrictsOrderbyProvince() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDistrictList(); sqlString = sqlString + " order by PROV_CODE"; preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIST_NAME"); String value = resultSet.getString("DIST_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDistrictwithProvince(String provinceID) throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDistrictListWithProvince(provinceID); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIST_NAME"); String value = resultSet.getString("DIST_CODE"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDivisions() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); // Setting the Request Header data. //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDivisionList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIV_NAME"); String value = resultSet.getString("DIV_ID"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listDivisionsforDistrcit(String disstrictName) throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); // Setting the Request Header data. //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDivisionListforDistrict(disstrictName); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("DIV_NAME"); String value = resultSet.getString("DIV_ID"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } public List listAreas() throws SQLException, Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); // Setting the Request Header data. //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForAreaList(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); List list = new ArrayList(); while (resultSet.next()) { String label = resultSet.getString("AREA_NAME"); String value = resultSet.getString("AREA_ID"); list.add(new LabelValue(label, value)); } return list; } finally { closeConnections(connection, preparedStatement, resultSet); } } private static void closeResultSet (ResultSet resultSet) { // close the result set if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } } private static void closeConnection (Connection connection) { // close the connection if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * Closes the open connections * * @param connection * @param resultSet */ private static void closeConnections (Connection connection, Statement statement, ResultSet resultSet) { closeStatement(statement); closeResultSet(resultSet); closeConnection(connection); } private static void closeStatement (Statement statement) { // close the statement if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } public User loginSuccess(String userName, String password) throws SQLException, Exception { Connection conn = DBConnection.createConnection(); Statement s = null; ResultSet rs = null; try { String sql = SQLGenerator.getSQLForLogin(userName); s = conn.createStatement(); rs = s.executeQuery(sql); if (rs.next()) { String realpassword = rs.getString(DBConstants.TableColumns.PASSWORD); String organization = rs.getString(DBConstants.TableColumns.ORGANIZATION); User user = new User(userName, organization); if (realpassword.equals(password)) { return user; } } } finally { closeConnections(conn, s, rs); } return null; } public List validateCampTOforInsert(CampTO campTO) throws SQLException, Exception { List result = campTO.validate(); if (!result.isEmpty()) { return result; } Connection connection = null; Statement stmt = null; ResultSet rs = null; String sqlString; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); stmt = connection.createStatement(); String areaId, divisionId, districtCode, provCode; if (campTO.getAreadId() != null) { areaId = campTO.getAreadId(); sqlString = SQLGenerator.getSQLForAreaDivision(areaId); rs = stmt.executeQuery(sqlString); if (rs.next()) { divisionId = rs.getString("DIV_ID"); if (campTO.getDivisionId() != null) { if (!divisionId.equals(campTO.getAreadId())) { result.add("Area doesn't exist in the Division"); return result; } } sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("Division doesn't exist "); return result; } districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("District doesn't exist "); return result; } provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("Division doesn't exist in the District "); return result; } } } else { result.add("Area doesn't exist"); return result; } } else if (campTO.getDivisionId() != null) { divisionId = campTO.getDivisionId(); sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); if (rs.next()) { districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("District doesn't exist "); return result; } provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("Division doesn't exist"); return result; } } else { districtCode = campTO.getDistrictCode(); sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (rs.next()) { provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("District doesn't exist"); return result; } } } //end try finally { closeConnections(connection, stmt, rs); } return result; } public List validateCampTOforEdit(CampTO campTO) throws SQLException, Exception { List result = campTO.validate(); if (!result.isEmpty()) { return result; } Connection connection = null; Statement stmt = null; ResultSet rs = null; String sqlString; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); stmt = connection.createStatement(); String campId = campTO.getCampId(); sqlString = SQLGenerator.getSQLForEditCamp(campId); rs = stmt.executeQuery(sqlString); if (!rs.next()) { result.add("Camp Id doesn't exist in the table"); return result; } String areaId, divisionId, districtCode, provCode; if (campTO.getAreadId() != null) { areaId = campTO.getAreadId(); sqlString = SQLGenerator.getSQLForAreaDivision(areaId); rs = stmt.executeQuery(sqlString); if (rs.next()) { divisionId = rs.getString("DIV_ID"); if (campTO.getDivisionId() != null) { if (!divisionId.equals(campTO.getAreadId())) { result.add("Area doesn't exist in the Division"); return result; } } sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("Area doesn't exist"); return result; } } else if (campTO.getDivisionId() != null) { divisionId = campTO.getDivisionId(); sqlString = SQLGenerator.getSQLForDivisionDistrict(divisionId); rs = stmt.executeQuery(sqlString); if (rs.next()) { districtCode = rs.getString("DIST_CODE"); if (campTO.getDistrictCode() != null) { if (!districtCode.equals(campTO.getDistrictCode())) { result.add("Division doesn't exist in the District"); return result; } } sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("Division doesn't exist"); return result; } } else { districtCode = campTO.getDistrictCode(); sqlString = SQLGenerator.getSQLForDistrictProvince(districtCode); rs = stmt.executeQuery(sqlString); if (rs.next()) { provCode = rs.getString("PROV_CODE"); if (campTO.getProvienceCode() != null) { if (!provCode.equals(campTO.getProvienceCode())) { result.add("District doesn't exist in the Division"); return result; } } } else { result.add("District doesn't exist"); return result; } } } //end try finally { closeConnections(connection, stmt, rs); } return result; } public ArrayList getDivisionRelatedInfo() throws Exception { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBConnection.createConnection(); //connection.setAutoCommit(false); //todo: modify to optimize preparedStatement String sqlString = SQLGenerator.getSQLForDivisionInfo(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); ArrayList arrayList = new ArrayList(100); while (resultSet.next()) { String id = resultSet.getString("DIV_ID"); String districtName = resultSet.getString("DIST_NAME"); String provName = resultSet.getString("PROV_NAME"); arrayList.add(" District : " + districtName + " Province : " + provName); } return arrayList; } finally { closeConnections(connection, preparedStatement, resultSet); } } }
added the shared DB connection
sahana-phase1/campreg/src/org/campdb/db/DataAccessManager.java
added the shared DB connection
<ide><path>ahana-phase1/campreg/src/org/campdb/db/DataAccessManager.java <ide> <ide> import org.campdb.business.*; <ide> import org.campdb.util.LabelValue; <add>import org.sahana.share.db.DBConnection; <ide> <ide> import java.sql.Connection; <ide> import java.sql.PreparedStatement; <ide> import java.sql.Statement; <ide> import java.util.ArrayList; <ide> import java.util.List; <del>import java.util.Collection; <add> <ide> <ide> /** <ide> * @author Administrator
Java
lgpl-2.1
2b300a2e3264f0cb1716834d072109adf709c350
0
svartika/ccnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,cawka/ndnx,ebollens/ccnmp,svartika/ccnx
/* * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009, 2011 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn.profiles.nameenum; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import org.ccnx.ccn.CCNContentHandler; import org.ccnx.ccn.CCNContentInterest; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.CCNInterestHandler; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentDecodingException; import org.ccnx.ccn.io.content.Link; import org.ccnx.ccn.io.content.Collection.CollectionObject; import org.ccnx.ccn.profiles.CommandMarker; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse.NameEnumerationResponseMessage; import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse.NameEnumerationResponseMessage.NameEnumerationResponseMessageObject; import org.ccnx.ccn.profiles.security.KeyProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Exclude; import org.ccnx.ccn.protocol.Interest; /** * Implements the base Name Enumerator. Applications register name prefixes. * Each prefix is explored until canceled by the application. This version * supports enumeration with multiple responders (repositories and applications). * * An application can have multiple enumerations active at the same time. * For each prefix, the name enumerator will generate an Interest. Responses * to the Interest will be in the form of Collections (by a * NameEnumeratorResponder and repository implementations). Returned Collections * will be parsed for the enumerated names and sent back to the application * using the callback with the applicable prefix and an array of names in * that namespace. The application is expected to handle duplicate names from * multiple responses and should be able to handle names that are returned, but * may not be available at this time (for example, /a.com/b/c.txt might have * been enumerated but a.com content may not be available). * * @see CCNFilterListener * @see CCNInterestListener * @see BasicNameEnumeratorListener * @see NameEnumerationResponse * */ public class CCNNameEnumerator implements CCNInterestHandler, CCNContentHandler { protected CCNHandle _handle = null; //protected ArrayList<ContentName> _registeredPrefixes = new ArrayList<ContentName>(); protected BasicNameEnumeratorListener callback; protected ArrayList<ContentName> _registeredNames = new ArrayList<ContentName>(); protected NEHandler _neHandler; /** * A supporting class for CCNNameEnumerator. NERequest objects hold registered prefixes and * their corresponding active interests. * */ private class NERequest{ ContentName prefix = null; ArrayList<Interest> ongoingInterests = new ArrayList<Interest>(); public NERequest(ContentName n) { prefix = n; } Interest getInterest(ContentName in) { for (Interest i : ongoingInterests) if (i.name().equals(in)) return i; return null; } void removeInterest(Interest i) { ongoingInterests.remove(getInterest(i.name())); } void addInterest(Interest i) { if (getInterest(i.name()) == null) ongoingInterests.add(i); } ArrayList<Interest> getInterests() { return ongoingInterests; } public boolean containsInterest(Interest interest) { for (Interest i : ongoingInterests) { if(i.equals(interest)) return true; } return false; } } /** * A supporting class for CCNNameEnumerator. NEResponse objects hold ContentName responses * for incoming name enumeration requests. Each NEResponse flag additionally has a dirty * flag to determine if a new name enumeration response is needed. If there is not any new * information since the last request, a new response will not be sent. * */ private class NEResponse { ContentName prefix = null; boolean dirty = true; public NEResponse(ContentName n) { prefix = n; } boolean isDirty() { return dirty; } void clean() { dirty = false; } void dirty() { dirty = true; } } /** * Class to handle responses via a separate thread */ protected class NEHandler implements Runnable { protected Queue<CCNContentInterest> _queue = new ConcurrentLinkedQueue<CCNContentInterest>(); protected CCNHandle _handle; protected CCNContentHandler _handler; protected boolean _isRunning = false; protected NEHandler(CCNHandle handle, CCNContentHandler handler) { _handle = handle; _handler = handler; } /** * Add a content object to the queue for processing. If we aren't running a processing * thread right now, start one. * * @param co */ protected void add(CCNContentInterest ci) { _queue.add(ci); synchronized (_queue) { if (!_isRunning) { _isRunning = true; SystemConfiguration._systemThreadpool.execute(this); } } } public void run() { while (true) { CCNContentInterest ci = null; synchronized (_queue) { ci = _queue.poll(); if (null == ci) { _isRunning = false; return; } } Interest interest = ci.getInterest(); ContentObject c = ci.getContent(); synchronized(_currentRequests) { ContentName prefix = interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); NERequest ner = getCurrentRequest(prefix); //need to make sure the prefix is still registered if (ner==null) { //this is no longer registered... no need to keep refreshing the interest use the callback return; } else { ner.removeInterest(interest); } NameEnumerationResponseMessageObject neResponse; ArrayList<ContentName> names = new ArrayList<ContentName>(); LinkedList<Link> links; Interest newInterest = interest; //update: now supports multiple responders! //note: if responseIDs are longer than 1 component, need to revisit interest generation for followups if (c != null) { if (Log.isLoggable(Level.FINE)) { Log.fine("we have a match for: "+interest.name()+" ["+ interest.toString()+"]"); } ArrayList<Interest> newInterests = new ArrayList<Interest>(); //we want to get new versions of this object newInterest = VersioningProfile.firstBlockLatestVersionInterest(c.name(), null); newInterests.add(newInterest); //does this content object have a response id in it? ContentName responseName = getIdFromName(c.name()); if (responseName==null ) { //no response name... this is an error! Log.warning("CCNNameEnumerator received a response without a responseID: {0} matching interest {1}", c.name(), interest.name()); } else { //we have a response name. //supports single component response IDs //if response IDs are hierarchical, we need to avoid exploding the number of Interests we express //if the interest had a responseId in it, we don't need to make a new base interest with an exclude, we would have done this already. if (Log.isLoggable(Level.FINE)) { Log.fine("response id from interest: "+getIdFromName(interest.name())); } if(getIdFromName(interest.name()) != null && getIdFromName(interest.name()).count() > 0) { //the interest has a response ID in it already... skip making new base interest } else { //also need to add this responder to the exclude list to find more responders ContentName prefixWithMarker = new ContentName(prefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); Exclude excludes = interest.exclude(); if(excludes==null) excludes = new Exclude(); excludes.add(new byte[][]{responseName.component(0)}); newInterest = Interest.constructInterest(prefixWithMarker, excludes, null, null, 4, null); //check to make sure the interest isn't already expressed if(!ner.containsInterest(newInterest)) newInterests.add(newInterest); } } try { for(Interest i: newInterests) { _handle.expressInterest(i, _handler); ner.addInterest(i); Log.finest("expressed: {0}", i); } } catch (IOException e1) { // error registering new interest Log.warning("error registering new interest in handleContent"); Log.warningStackTrace(e1); } newInterests.clear(); try { neResponse = new NameEnumerationResponseMessageObject(c, _handle); links = neResponse.contents(); for (Link l: links) { names.add(l.targetName()); } //strip off NEMarker before passing through callback callback.handleNameEnumerator( interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()), names); } catch(ContentDecodingException e) { Log.warning("Error parsing Collection from ContentObject in CCNNameEnumerator"); Log.warningStackTrace(e); } catch(IOException e) { Log.warning("error getting CollectionObject from ContentObject in CCNNameEnumerator.handleContent"); Log.warningStackTrace(e); } } } } } } protected ArrayList<NEResponse> _handledResponses = new ArrayList<NEResponse>(); protected ArrayList<NERequest> _currentRequests = new ArrayList<NERequest>(); /** * CCNNameEnumerator constructor. Creates a CCNNameEnumerator, sets the CCNHandle, * registers the callback and registers a prefix for enumeration. * * @param prefix ContentName to enumerate names under * @param handle CCNHandle for sending and receiving collection objects during enumeration. * @param c BasicNameEnumeratorListener callback to receive enumeration responses. */ public CCNNameEnumerator(ContentName prefix, CCNHandle handle, BasicNameEnumeratorListener c) throws IOException { _handle = handle; _neHandler = new NEHandler(handle, this); callback = c; registerPrefix(prefix); } /** * CCNNameEnumerator constructor. Creates a CCNNameEnumerator, sets the CCNHandle, and * registers the callback. * * @param handle CCNHandle for sending and receiving collection objects during enumeration. * @param c BasicNameEnumeratorListener callback to receive enumeration responses. */ public CCNNameEnumerator(CCNHandle handle, BasicNameEnumeratorListener c) { _handle = handle; callback = c; } public CCNHandle handle() { return _handle; } /** * Method to register a prefix for name enumeration. A NERequest and initial interest is created for new prefixes. * Prefixes that are already registered return and do not impact the already active registration. * * @param prefix ContentName to enumerate * @throws IOException */ public void registerPrefix(ContentName prefix) throws IOException { synchronized (_currentRequests) { NERequest r = getCurrentRequest(prefix); if (r != null) { // this prefix is already registered... Log.fine("prefix {0} is already registered... returning", prefix); return; } else { r = new NERequest(prefix); _currentRequests.add(r); } Log.info("Registered Prefix: {0}", prefix); ContentName prefixMarked = new ContentName(prefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); //we have minSuffixComponents to account for sig, version, seg and digest Interest pi = Interest.constructInterest(prefixMarked, null, null, null, 4, null); r.addInterest(pi); _handle.expressInterest(pi, this); } } /** * Method to cancel active enumerations. The active interests are retrieved from the corresponding * NERequest object for the prefix. Each interest is canceled and the NERequest object is removed * from the list of active enumerations. * * @param prefix ContentName to cancel enumeration * @return boolean Returns if the prefix is successfully canceled. */ public boolean cancelPrefix(ContentName prefix) { Log.info("cancel prefix: {0} ", prefix); synchronized(_currentRequests) { //cancel the behind the scenes interests and remove from the local ArrayList NERequest r = getCurrentRequest(prefix); if (r != null) { ArrayList<Interest> is = r.getInterests(); Log.fine("we have {0} interests to cancel", is.size()); Interest i; while (!r.getInterests().isEmpty()) { i=r.getInterests().remove(0); _handle.cancelInterest(i, this); } _currentRequests.remove(r); return (getCurrentRequest(prefix) == null); } return false; } } /** * Callback for name enumeration responses. The results contain CollectionObjects containing the * names under a prefix. The collection objects are matched to registered prefixes and returned * to the calling applications using their registered callback handlers. Each response can create * a new Interest that is used to further enumerate the namespace. The implementation * explicitly handles multiple name enumeration responders. The method may now create multiple * interests to further enumerate the prefix. Please note that the current implementation will * need to be updated if responseIDs are more than one component long. * * @param c ContentObject containing the ContentNames under a registered prefix * @param interest The interest matching or triggering a name enumeration response * * @return Interest Returns a new Interest to further enumerate or null to cancel the interest * that matched these objects. This implementation returns null since new interests are created and * expressed as the returned CollectionObjects are processed. * * @see CollectionObject * @see CCNInterestHandler */ public Interest handleContent(ContentObject c, Interest interest) { if (interest.name().contains(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes())) { //the NEMarker is in the name... good! } else { //COMMAND_MARKER_BASIC_ENUMERATION missing... we have a problem Log.warning("the name enumeration marker is missing... shouldn't have gotten this callback"); return null; } if (Log.isLoggable(Level.FINE)) { Log.fine("NE: received a response for interest {0}", interest); } _neHandler.add(new CCNContentInterest(c, interest)); return null; } /** * Method for receiving Interests matching the namespace for answering name enumeration requests. Incoming Interests are * verified to have the name enumeration marker. The NEResponse matching the interest is found (if it already exists) and if * new names have been registered under the prefix or if no matching NEResponse object is found, a name enumeration * response is created. * * @param interest Interest object matching the namespace filter. * * @return boolean */ public boolean handleInterest(Interest interest) { boolean result = false; ContentName responseName = null; Link match; NameEnumerationResponseMessage nem; ContentName name = null; NEResponse r = null; if (Log.isLoggable(Level.FINER)) { Log.finer("got an interest: {0}",interest.name()); } name = interest.name().clone(); nem = new NameEnumerationResponseMessage(); //Verify NameEnumeration Marker is in the name if (!name.contains(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes())) { //Skip... we don't handle these } else { name = name.cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); responseName = new ContentName(name, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); boolean skip = false; synchronized (_handledResponses) { //have we handled this response already? r = getHandledResponse(name); if (r != null) { //we have handled this before! if (r.isDirty()) { //this has updates to send back!! } else { //nothing new to send back... go ahead and skip to next interest skip = true; } } else { //this is a new one... r = new NEResponse(name); _handledResponses.add(r); } if (!skip) { for (ContentName n: _registeredNames) { if (name.isPrefixOf(n) && name.count() < n.count()) { ContentName tempName = n.clone(); byte[] tn = n.component(name.count()); byte[][] na = new byte[1][tn.length]; na[0] = tn; tempName = new ContentName(na); match = new Link(tempName); if (!nem.contents().contains(match)) { nem.add(match); } } } } if (nem.size() > 0) { try { ContentName responseNameWithId = KeyProfile.keyName(responseName, _handle.keyManager().getDefaultKeyID()); NameEnumerationResponseMessageObject nemobj = new NameEnumerationResponseMessageObject(responseNameWithId, nem, _handle); nemobj.saveLaterWithClose(interest); result = true; if (Log.isLoggable(Level.FINE)) { Log.fine("Saved collection object in name enumeration: " + nemobj.getVersionedName()); } r.clean(); } catch(IOException e) { Log.warning("error processing an incoming interest.. dropping and returning"); Log.warningStackTrace(e); return false; } } Log.finer("this interest did not have any matching names... not returning anything."); if (r != null) r.clean(); } //end of synchronized } //end of name enumeration marker check return result; } /** * Method to check if a name is already registered to be included in name enumeration responses for incoming Interests. * * @param name ContentName to check for in registered names for responses * @return boolean Returns true if the name is registered and false if not */ public boolean containsRegisteredName(ContentName name) { if (name == null) { Log.warning("trying to check for null registered name"); return false; } synchronized(_handledResponses) { if (_registeredNames.contains(name)) return true; else return false; } } /** * Method to register a namespace for filtering incoming Interests * * @param name ContentName to register for filtering incoming Interests * @throws IOException * * @see CCNFilterListener */ public void registerNameSpace(ContentName name) throws IOException { synchronized(_handledResponses) { if (!_registeredNames.contains(name)) { _registeredNames.add(name); _handle.registerFilter(name, this); } } } /** * Method to register a name to include in incoming name enumeration requests. * * @param name ContentName to register for name enumeration responses */ public void registerNameForResponses(ContentName name) { if (name == null) { Log.warning("The content name for registerNameForResponses was null, ignoring"); return; } //Do not need to register each name as a filter... the namespace should cover it synchronized(_handledResponses) { if (!_registeredNames.contains(name)) { // DKS - if we don't care about order, could use a Set instead of an ArrayList, // then just call add as duplicates suppressed _registeredNames.add(name); } //check prefixes that were handled... if so, mark them dirty updateHandledResponses(name); } } /** * Method to get the NEResponse object for a registered name. Returns null if no matching NEResponse is found. * * @param n ContentName identifying a NEResponse * @return NEResponse Returns the NEResponse matching the name. */ protected NEResponse getHandledResponse(ContentName n) { //Log.info("checking handled responses..."); synchronized (_handledResponses) { for (NEResponse t: _handledResponses) { if (t.prefix.equals(n)) return t; } return null; } } /** * Method to set the dirty flag for NEResponse objects that are updated as new names are registered for responses. * * @param n New ContentName to be included in name enumeration responses */ protected void updateHandledResponses(ContentName n) { synchronized (_handledResponses) { for (NEResponse t: _handledResponses) { if (t.prefix.isPrefixOf(n)) { t.dirty(); } } } } /** * Method to get the corresponding NERequest for a ContentName. Returns null * if no NERequest is found. * * @param n ContentName for the NERequest to be found. * * @return NERequest NERequest instance with the supplied ContentName. * Returns null if no NERequest exists. */ protected NERequest getCurrentRequest(ContentName n) { synchronized (_currentRequests) { for (NERequest r : _currentRequests) { if (r.prefix.equals(n)) return r; } return null; } } /** * Method to cancel more than one prefix at a time. This method will cancel all active Interests * matching the prefix supplied. The matching NERequest objects are removed from the set of active * registered prefixes and the corresponding Interests are canceled. * * @param prefixToCancel */ public void cancelEnumerationsWithPrefix(ContentName prefixToCancel) { Log.info("cancel prefix: {0}",prefixToCancel); synchronized(_currentRequests) { //cancel the behind the scenes interests and remove from the local ArrayList ArrayList<NERequest> toRemove = new ArrayList<NERequest>(); for(NERequest n: _currentRequests){ if(prefixToCancel.isPrefixOf(n.prefix)) toRemove.add(n); } while(!toRemove.isEmpty()){ if(cancelPrefix(toRemove.remove(0).prefix)) Log.info("cancelled prefix: {0}", prefixToCancel); else Log.info("could not cancel prefix: {0}", prefixToCancel); } } } private ContentName getIdFromName(ContentName name) { //get the response id, could be more than one component and have a version in it ContentName responseName = null; try { int index = name.containsWhere(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); ContentName prefix = name.subname(index+1, name.count()); if(VersioningProfile.hasTerminalVersion(prefix)) responseName = VersioningProfile.cutLastVersion(prefix); else responseName = prefix; Log.finest("NameEnumeration response ID: {0}", responseName); } catch(Exception e) { return null; } return responseName; } }
javasrc/src/org/ccnx/ccn/profiles/nameenum/CCNNameEnumerator.java
/* * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009, 2011 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn.profiles.nameenum; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.logging.Level; import org.ccnx.ccn.CCNContentHandler; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.CCNInterestHandler; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentDecodingException; import org.ccnx.ccn.io.content.Link; import org.ccnx.ccn.io.content.Collection.CollectionObject; import org.ccnx.ccn.profiles.CommandMarker; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse.NameEnumerationResponseMessage; import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse.NameEnumerationResponseMessage.NameEnumerationResponseMessageObject; import org.ccnx.ccn.profiles.security.KeyProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Exclude; import org.ccnx.ccn.protocol.Interest; /** * Implements the base Name Enumerator. Applications register name prefixes. * Each prefix is explored until canceled by the application. This version * supports enumeration with multiple responders (repositories and applications). * * An application can have multiple enumerations active at the same time. * For each prefix, the name enumerator will generate an Interest. Responses * to the Interest will be in the form of Collections (by a * NameEnumeratorResponder and repository implementations). Returned Collections * will be parsed for the enumerated names and sent back to the application * using the callback with the applicable prefix and an array of names in * that namespace. The application is expected to handle duplicate names from * multiple responses and should be able to handle names that are returned, but * may not be available at this time (for example, /a.com/b/c.txt might have * been enumerated but a.com content may not be available). * * @see CCNFilterListener * @see CCNInterestListener * @see BasicNameEnumeratorListener * @see NameEnumerationResponse * */ public class CCNNameEnumerator implements CCNInterestHandler, CCNContentHandler { protected CCNHandle _handle = null; //protected ArrayList<ContentName> _registeredPrefixes = new ArrayList<ContentName>(); protected BasicNameEnumeratorListener callback; protected ArrayList<ContentName> _registeredNames = new ArrayList<ContentName>(); /** * A supporting class for CCNNameEnumerator. NERequest objects hold registered prefixes and * their corresponding active interests. * */ private class NERequest{ ContentName prefix = null; ArrayList<Interest> ongoingInterests = new ArrayList<Interest>(); public NERequest(ContentName n) { prefix = n; } Interest getInterest(ContentName in) { for (Interest i : ongoingInterests) if (i.name().equals(in)) return i; return null; } void removeInterest(Interest i) { ongoingInterests.remove(getInterest(i.name())); } void addInterest(Interest i) { if (getInterest(i.name()) == null) ongoingInterests.add(i); } ArrayList<Interest> getInterests() { return ongoingInterests; } public boolean containsInterest(Interest interest) { for (Interest i : ongoingInterests) { if(i.equals(interest)) return true; } return false; } } /** * A supporting class for CCNNameEnumerator. NEResponse objects hold ContentName responses * for incoming name enumeration requests. Each NEResponse flag additionally has a dirty * flag to determine if a new name enumeration response is needed. If there is not any new * information since the last request, a new response will not be sent. * */ private class NEResponse { ContentName prefix = null; boolean dirty = true; public NEResponse(ContentName n) { prefix = n; } boolean isDirty() { return dirty; } void clean() { dirty = false; } void dirty() { dirty = true; } } protected ArrayList<NEResponse> _handledResponses = new ArrayList<NEResponse>(); protected ArrayList<NERequest> _currentRequests = new ArrayList<NERequest>(); /** * CCNNameEnumerator constructor. Creates a CCNNameEnumerator, sets the CCNHandle, * registers the callback and registers a prefix for enumeration. * * @param prefix ContentName to enumerate names under * @param handle CCNHandle for sending and receiving collection objects during enumeration. * @param c BasicNameEnumeratorListener callback to receive enumeration responses. */ public CCNNameEnumerator(ContentName prefix, CCNHandle handle, BasicNameEnumeratorListener c) throws IOException { _handle = handle; callback = c; registerPrefix(prefix); } /** * CCNNameEnumerator constructor. Creates a CCNNameEnumerator, sets the CCNHandle, and * registers the callback. * * @param handle CCNHandle for sending and receiving collection objects during enumeration. * @param c BasicNameEnumeratorListener callback to receive enumeration responses. */ public CCNNameEnumerator(CCNHandle handle, BasicNameEnumeratorListener c) { _handle = handle; callback = c; } public CCNHandle handle() { return _handle; } /** * Method to register a prefix for name enumeration. A NERequest and initial interest is created for new prefixes. * Prefixes that are already registered return and do not impact the already active registration. * * @param prefix ContentName to enumerate * @throws IOException */ public void registerPrefix(ContentName prefix) throws IOException { synchronized (_currentRequests) { NERequest r = getCurrentRequest(prefix); if (r != null) { // this prefix is already registered... Log.fine("prefix {0} is already registered... returning", prefix); return; } else { r = new NERequest(prefix); _currentRequests.add(r); } Log.info("Registered Prefix: {0}", prefix); ContentName prefixMarked = new ContentName(prefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); //we have minSuffixComponents to account for sig, version, seg and digest Interest pi = Interest.constructInterest(prefixMarked, null, null, null, 4, null); r.addInterest(pi); _handle.expressInterest(pi, this); } } /** * Method to cancel active enumerations. The active interests are retrieved from the corresponding * NERequest object for the prefix. Each interest is canceled and the NERequest object is removed * from the list of active enumerations. * * @param prefix ContentName to cancel enumeration * @return boolean Returns if the prefix is successfully canceled. */ public boolean cancelPrefix(ContentName prefix) { Log.info("cancel prefix: {0} ", prefix); synchronized(_currentRequests) { //cancel the behind the scenes interests and remove from the local ArrayList NERequest r = getCurrentRequest(prefix); if (r != null) { ArrayList<Interest> is = r.getInterests(); Log.fine("we have {0} interests to cancel", is.size()); Interest i; while (!r.getInterests().isEmpty()) { i=r.getInterests().remove(0); _handle.cancelInterest(i, this); } _currentRequests.remove(r); return (getCurrentRequest(prefix) == null); } return false; } } /** * Callback for name enumeration responses. The results contain CollectionObjects containing the * names under a prefix. The collection objects are matched to registered prefixes and returned * to the calling applications using their registered callback handlers. Each response can create * a new Interest that is used to further enumerate the namespace. The implementation * explicitly handles multiple name enumeration responders. The method may now create multiple * interests to further enumerate the prefix. Please note that the current implementation will * need to be updated if responseIDs are more than one component long. * * @param c ContentObject containing the ContentNames under a registered prefix * @param interest The interest matching or triggering a name enumeration response * * @return Interest Returns a new Interest to further enumerate or null to cancel the interest * that matched these objects. This implementation returns null since new interests are created and * expressed as the returned CollectionObjects are processed. * * @see CollectionObject * @see CCNInterestHandler */ public Interest handleContent(ContentObject c, Interest interest) { if (interest.name().contains(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes())) { //the NEMarker is in the name... good! } else { //COMMAND_MARKER_BASIC_ENUMERATION missing... we have a problem Log.warning("the name enumeration marker is missing... shouldn't have gotten this callback"); return null; } if (Log.isLoggable(Level.FINE)) { Log.fine("NE: received a response for interest {0}", interest); } synchronized(_currentRequests) { ContentName prefix = interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); NERequest ner = getCurrentRequest(prefix); //need to make sure the prefix is still registered if (ner==null) { //this is no longer registered... no need to keep refreshing the interest use the callback return null; } else { ner.removeInterest(interest); } NameEnumerationResponseMessageObject neResponse; ArrayList<ContentName> names = new ArrayList<ContentName>(); LinkedList<Link> links; Interest newInterest = interest; //update: now supports multiple responders! //note: if responseIDs are longer than 1 component, need to revisit interest generation for followups if (c != null) { if (Log.isLoggable(Level.FINE)) { Log.fine("we have a match for: "+interest.name()+" ["+ interest.toString()+"]"); } ArrayList<Interest> newInterests = new ArrayList<Interest>(); //we want to get new versions of this object newInterest = VersioningProfile.firstBlockLatestVersionInterest(c.name(), null); newInterests.add(newInterest); //does this content object have a response id in it? ContentName responseName = getIdFromName(c.name()); if (responseName==null ) { //no response name... this is an error! Log.warning("CCNNameEnumerator received a response without a responseID: {0} matching interest {1}", c.name(), interest.name()); } else { //we have a response name. //supports single component response IDs //if response IDs are hierarchical, we need to avoid exploding the number of Interests we express //if the interest had a responseId in it, we don't need to make a new base interest with an exclude, we would have done this already. if (Log.isLoggable(Level.FINE)) { Log.fine("response id from interest: "+getIdFromName(interest.name())); } if(getIdFromName(interest.name()) != null && getIdFromName(interest.name()).count() > 0) { //the interest has a response ID in it already... skip making new base interest } else { //also need to add this responder to the exclude list to find more responders ContentName prefixWithMarker = new ContentName(prefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); Exclude excludes = interest.exclude(); if(excludes==null) excludes = new Exclude(); excludes.add(new byte[][]{responseName.component(0)}); newInterest = Interest.constructInterest(prefixWithMarker, excludes, null, null, 4, null); //check to make sure the interest isn't already expressed if(!ner.containsInterest(newInterest)) newInterests.add(newInterest); } } try { for(Interest i: newInterests) { _handle.expressInterest(i, this); ner.addInterest(i); Log.finest("expressed: {0}", i); } } catch (IOException e1) { // error registering new interest Log.warning("error registering new interest in handleContent"); Log.warningStackTrace(e1); } newInterests.clear(); try { neResponse = new NameEnumerationResponseMessageObject(c, _handle); links = neResponse.contents(); for (Link l: links) { names.add(l.targetName()); } //strip off NEMarker before passing through callback callback.handleNameEnumerator( interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()), names); } catch(ContentDecodingException e) { Log.warning("Error parsing Collection from ContentObject in CCNNameEnumerator"); Log.warningStackTrace(e); } catch(IOException e) { Log.warning("error getting CollectionObject from ContentObject in CCNNameEnumerator.handleContent"); Log.warningStackTrace(e); } } } return null; } /** * Method for receiving Interests matching the namespace for answering name enumeration requests. Incoming Interests are * verified to have the name enumeration marker. The NEResponse matching the interest is found (if it already exists) and if * new names have been registered under the prefix or if no matching NEResponse object is found, a name enumeration * response is created. * * @param interest Interest object matching the namespace filter. * * @return boolean */ public boolean handleInterest(Interest interest) { boolean result = false; ContentName responseName = null; Link match; NameEnumerationResponseMessage nem; ContentName name = null; NEResponse r = null; if (Log.isLoggable(Level.FINER)) { Log.finer("got an interest: {0}",interest.name()); } name = interest.name().clone(); nem = new NameEnumerationResponseMessage(); //Verify NameEnumeration Marker is in the name if (!name.contains(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes())) { //Skip... we don't handle these } else { name = name.cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); responseName = new ContentName(name, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); boolean skip = false; synchronized (_handledResponses) { //have we handled this response already? r = getHandledResponse(name); if (r != null) { //we have handled this before! if (r.isDirty()) { //this has updates to send back!! } else { //nothing new to send back... go ahead and skip to next interest skip = true; } } else { //this is a new one... r = new NEResponse(name); _handledResponses.add(r); } if (!skip) { for (ContentName n: _registeredNames) { if (name.isPrefixOf(n) && name.count() < n.count()) { ContentName tempName = n.clone(); byte[] tn = n.component(name.count()); byte[][] na = new byte[1][tn.length]; na[0] = tn; tempName = new ContentName(na); match = new Link(tempName); if (!nem.contents().contains(match)) { nem.add(match); } } } } if (nem.size() > 0) { try { ContentName responseNameWithId = KeyProfile.keyName(responseName, _handle.keyManager().getDefaultKeyID()); NameEnumerationResponseMessageObject nemobj = new NameEnumerationResponseMessageObject(responseNameWithId, nem, _handle); nemobj.saveLaterWithClose(interest); result = true; if (Log.isLoggable(Level.FINE)) { Log.fine("Saved collection object in name enumeration: " + nemobj.getVersionedName()); } r.clean(); } catch(IOException e) { Log.warning("error processing an incoming interest.. dropping and returning"); Log.warningStackTrace(e); return false; } } Log.finer("this interest did not have any matching names... not returning anything."); if (r != null) r.clean(); } //end of synchronized } //end of name enumeration marker check return result; } /** * Method to check if a name is already registered to be included in name enumeration responses for incoming Interests. * * @param name ContentName to check for in registered names for responses * @return boolean Returns true if the name is registered and false if not */ public boolean containsRegisteredName(ContentName name) { if (name == null) { Log.warning("trying to check for null registered name"); return false; } synchronized(_handledResponses) { if (_registeredNames.contains(name)) return true; else return false; } } /** * Method to register a namespace for filtering incoming Interests * * @param name ContentName to register for filtering incoming Interests * @throws IOException * * @see CCNFilterListener */ public void registerNameSpace(ContentName name) throws IOException { synchronized(_handledResponses) { if (!_registeredNames.contains(name)) { _registeredNames.add(name); _handle.registerFilter(name, this); } } } /** * Method to register a name to include in incoming name enumeration requests. * * @param name ContentName to register for name enumeration responses */ public void registerNameForResponses(ContentName name) { if (name == null) { Log.warning("The content name for registerNameForResponses was null, ignoring"); return; } //Do not need to register each name as a filter... the namespace should cover it synchronized(_handledResponses) { if (!_registeredNames.contains(name)) { // DKS - if we don't care about order, could use a Set instead of an ArrayList, // then just call add as duplicates suppressed _registeredNames.add(name); } //check prefixes that were handled... if so, mark them dirty updateHandledResponses(name); } } /** * Method to get the NEResponse object for a registered name. Returns null if no matching NEResponse is found. * * @param n ContentName identifying a NEResponse * @return NEResponse Returns the NEResponse matching the name. */ protected NEResponse getHandledResponse(ContentName n) { //Log.info("checking handled responses..."); synchronized (_handledResponses) { for (NEResponse t: _handledResponses) { if (t.prefix.equals(n)) return t; } return null; } } /** * Method to set the dirty flag for NEResponse objects that are updated as new names are registered for responses. * * @param n New ContentName to be included in name enumeration responses */ protected void updateHandledResponses(ContentName n) { synchronized (_handledResponses) { for (NEResponse t: _handledResponses) { if (t.prefix.isPrefixOf(n)) { t.dirty(); } } } } /** * Method to get the corresponding NERequest for a ContentName. Returns null * if no NERequest is found. * * @param n ContentName for the NERequest to be found. * * @return NERequest NERequest instance with the supplied ContentName. * Returns null if no NERequest exists. */ protected NERequest getCurrentRequest(ContentName n) { synchronized (_currentRequests) { for (NERequest r : _currentRequests) { if (r.prefix.equals(n)) return r; } return null; } } /** * Method to cancel more than one prefix at a time. This method will cancel all active Interests * matching the prefix supplied. The matching NERequest objects are removed from the set of active * registered prefixes and the corresponding Interests are canceled. * * @param prefixToCancel */ public void cancelEnumerationsWithPrefix(ContentName prefixToCancel) { Log.info("cancel prefix: {0}",prefixToCancel); synchronized(_currentRequests) { //cancel the behind the scenes interests and remove from the local ArrayList ArrayList<NERequest> toRemove = new ArrayList<NERequest>(); for(NERequest n: _currentRequests){ if(prefixToCancel.isPrefixOf(n.prefix)) toRemove.add(n); } while(!toRemove.isEmpty()){ if(cancelPrefix(toRemove.remove(0).prefix)) Log.info("cancelled prefix: {0}", prefixToCancel); else Log.info("could not cancel prefix: {0}", prefixToCancel); } } } private ContentName getIdFromName(ContentName name) { //get the response id, could be more than one component and have a version in it ContentName responseName = null; try { int index = name.containsWhere(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); ContentName prefix = name.subname(index+1, name.count()); if(VersioningProfile.hasTerminalVersion(prefix)) responseName = VersioningProfile.cutLastVersion(prefix); else responseName = prefix; Log.finest("NameEnumeration response ID: {0}", responseName); } catch(Exception e) { return null; } return responseName; } }
refs #100555 Fix spanning NE problem by updating in background
javasrc/src/org/ccnx/ccn/profiles/nameenum/CCNNameEnumerator.java
refs #100555 Fix spanning NE problem by updating in background
<ide><path>avasrc/src/org/ccnx/ccn/profiles/nameenum/CCNNameEnumerator.java <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.LinkedList; <add>import java.util.Queue; <add>import java.util.concurrent.ConcurrentLinkedQueue; <ide> import java.util.logging.Level; <ide> <ide> import org.ccnx.ccn.CCNContentHandler; <add>import org.ccnx.ccn.CCNContentInterest; <ide> import org.ccnx.ccn.CCNHandle; <ide> import org.ccnx.ccn.CCNInterestHandler; <add>import org.ccnx.ccn.config.SystemConfiguration; <ide> import org.ccnx.ccn.impl.support.Log; <ide> import org.ccnx.ccn.io.content.ContentDecodingException; <ide> import org.ccnx.ccn.io.content.Link; <ide> import org.ccnx.ccn.protocol.ContentObject; <ide> import org.ccnx.ccn.protocol.Exclude; <ide> import org.ccnx.ccn.protocol.Interest; <del> <ide> <ide> /** <ide> * Implements the base Name Enumerator. Applications register name prefixes. <ide> //protected ArrayList<ContentName> _registeredPrefixes = new ArrayList<ContentName>(); <ide> protected BasicNameEnumeratorListener callback; <ide> protected ArrayList<ContentName> _registeredNames = new ArrayList<ContentName>(); <add> protected NEHandler _neHandler; <ide> <ide> /** <ide> * A supporting class for CCNNameEnumerator. NERequest objects hold registered prefixes and <ide> } <ide> } <ide> <add> /** <add> * Class to handle responses via a separate thread <add> */ <add> protected class NEHandler implements Runnable { <add> protected Queue<CCNContentInterest> _queue = new ConcurrentLinkedQueue<CCNContentInterest>(); <add> protected CCNHandle _handle; <add> protected CCNContentHandler _handler; <add> protected boolean _isRunning = false; <add> <add> protected NEHandler(CCNHandle handle, CCNContentHandler handler) { <add> _handle = handle; <add> _handler = handler; <add> } <add> <add> /** <add> * Add a content object to the queue for processing. If we aren't running a processing <add> * thread right now, start one. <add> * <add> * @param co <add> */ <add> protected void add(CCNContentInterest ci) { <add> _queue.add(ci); <add> synchronized (_queue) { <add> if (!_isRunning) { <add> _isRunning = true; <add> SystemConfiguration._systemThreadpool.execute(this); <add> } <add> } <add> } <add> <add> public void run() { <add> while (true) { <add> <add> CCNContentInterest ci = null; <add> synchronized (_queue) { <add> ci = _queue.poll(); <add> if (null == ci) { <add> _isRunning = false; <add> return; <add> } <add> } <add> <add> Interest interest = ci.getInterest(); <add> ContentObject c = ci.getContent(); <add> synchronized(_currentRequests) { <add> ContentName prefix = interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); <add> NERequest ner = getCurrentRequest(prefix); <add> <add> //need to make sure the prefix is still registered <add> if (ner==null) { <add> //this is no longer registered... no need to keep refreshing the interest use the callback <add> return; <add> } else { <add> ner.removeInterest(interest); <add> } <add> <add> NameEnumerationResponseMessageObject neResponse; <add> ArrayList<ContentName> names = new ArrayList<ContentName>(); <add> LinkedList<Link> links; <add> Interest newInterest = interest; <add> <add> //update: now supports multiple responders! <add> //note: if responseIDs are longer than 1 component, need to revisit interest generation for followups <add> if (c != null) { <add> if (Log.isLoggable(Level.FINE)) { <add> Log.fine("we have a match for: "+interest.name()+" ["+ interest.toString()+"]"); <add> } <add> ArrayList<Interest> newInterests = new ArrayList<Interest>(); <add> <add> //we want to get new versions of this object <add> newInterest = VersioningProfile.firstBlockLatestVersionInterest(c.name(), null); <add> newInterests.add(newInterest); <add> <add> //does this content object have a response id in it? <add> ContentName responseName = getIdFromName(c.name()); <add> <add> if (responseName==null ) { <add> //no response name... this is an error! <add> Log.warning("CCNNameEnumerator received a response without a responseID: {0} matching interest {1}", c.name(), interest.name()); <add> } else { <add> //we have a response name. <add> <add> //supports single component response IDs <add> //if response IDs are hierarchical, we need to avoid exploding the number of Interests we express <add> <add> //if the interest had a responseId in it, we don't need to make a new base interest with an exclude, we would have done this already. <add> if (Log.isLoggable(Level.FINE)) { <add> Log.fine("response id from interest: "+getIdFromName(interest.name())); <add> } <add> <add> if(getIdFromName(interest.name()) != null && getIdFromName(interest.name()).count() > 0) { <add> //the interest has a response ID in it already... skip making new base interest <add> } else { <add> //also need to add this responder to the exclude list to find more responders <add> ContentName prefixWithMarker = <add> new ContentName(prefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); <add> Exclude excludes = interest.exclude(); <add> if(excludes==null) <add> excludes = new Exclude(); <add> excludes.add(new byte[][]{responseName.component(0)}); <add> newInterest = Interest.constructInterest(prefixWithMarker, excludes, null, null, 4, null); <add> <add> //check to make sure the interest isn't already expressed <add> if(!ner.containsInterest(newInterest)) <add> newInterests.add(newInterest); <add> } <add> <add> } <add> <add> try { <add> for(Interest i: newInterests) { <add> _handle.expressInterest(i, _handler); <add> ner.addInterest(i); <add> Log.finest("expressed: {0}", i); <add> } <add> } catch (IOException e1) { <add> // error registering new interest <add> Log.warning("error registering new interest in handleContent"); <add> Log.warningStackTrace(e1); <add> } <add> <add> newInterests.clear(); <add> <add> try { <add> neResponse = new NameEnumerationResponseMessageObject(c, _handle); <add> links = neResponse.contents(); <add> for (Link l: links) { <add> names.add(l.targetName()); <add> } <add> //strip off NEMarker before passing through callback <add> callback.handleNameEnumerator( <add> interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()), names); <add> } catch(ContentDecodingException e) { <add> Log.warning("Error parsing Collection from ContentObject in CCNNameEnumerator"); <add> Log.warningStackTrace(e); <add> } catch(IOException e) { <add> Log.warning("error getting CollectionObject from ContentObject in CCNNameEnumerator.handleContent"); <add> Log.warningStackTrace(e); <add> } <add> } <add> } <add> } <add> } <add> } <add> <ide> protected ArrayList<NEResponse> _handledResponses = new ArrayList<NEResponse>(); <ide> protected ArrayList<NERequest> _currentRequests = new ArrayList<NERequest>(); <ide> <ide> <ide> public CCNNameEnumerator(ContentName prefix, CCNHandle handle, BasicNameEnumeratorListener c) throws IOException { <ide> _handle = handle; <add> _neHandler = new NEHandler(handle, this); <ide> callback = c; <ide> registerPrefix(prefix); <ide> } <ide> <ide> if (Log.isLoggable(Level.FINE)) { <ide> Log.fine("NE: received a response for interest {0}", interest); <del> } <del> <del> synchronized(_currentRequests) { <del> ContentName prefix = interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); <del> NERequest ner = getCurrentRequest(prefix); <del> <del> //need to make sure the prefix is still registered <del> if (ner==null) { <del> //this is no longer registered... no need to keep refreshing the interest use the callback <del> return null; <del> } else { <del> ner.removeInterest(interest); <del> } <del> <del> NameEnumerationResponseMessageObject neResponse; <del> ArrayList<ContentName> names = new ArrayList<ContentName>(); <del> LinkedList<Link> links; <del> Interest newInterest = interest; <del> <del> //update: now supports multiple responders! <del> //note: if responseIDs are longer than 1 component, need to revisit interest generation for followups <del> if (c != null) { <del> if (Log.isLoggable(Level.FINE)) { <del> Log.fine("we have a match for: "+interest.name()+" ["+ interest.toString()+"]"); <del> } <del> ArrayList<Interest> newInterests = new ArrayList<Interest>(); <del> <del> //we want to get new versions of this object <del> newInterest = VersioningProfile.firstBlockLatestVersionInterest(c.name(), null); <del> newInterests.add(newInterest); <del> <del> //does this content object have a response id in it? <del> ContentName responseName = getIdFromName(c.name()); <del> <del> if (responseName==null ) { <del> //no response name... this is an error! <del> Log.warning("CCNNameEnumerator received a response without a responseID: {0} matching interest {1}", c.name(), interest.name()); <del> } else { <del> //we have a response name. <del> <del> //supports single component response IDs <del> //if response IDs are hierarchical, we need to avoid exploding the number of Interests we express <del> <del> //if the interest had a responseId in it, we don't need to make a new base interest with an exclude, we would have done this already. <del> if (Log.isLoggable(Level.FINE)) { <del> Log.fine("response id from interest: "+getIdFromName(interest.name())); <del> } <del> <del> if(getIdFromName(interest.name()) != null && getIdFromName(interest.name()).count() > 0) { <del> //the interest has a response ID in it already... skip making new base interest <del> } else { <del> //also need to add this responder to the exclude list to find more responders <del> ContentName prefixWithMarker = <del> new ContentName(prefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()); <del> Exclude excludes = interest.exclude(); <del> if(excludes==null) <del> excludes = new Exclude(); <del> excludes.add(new byte[][]{responseName.component(0)}); <del> newInterest = Interest.constructInterest(prefixWithMarker, excludes, null, null, 4, null); <del> <del> //check to make sure the interest isn't already expressed <del> if(!ner.containsInterest(newInterest)) <del> newInterests.add(newInterest); <del> } <del> <del> } <del> <del> try { <del> for(Interest i: newInterests) { <del> _handle.expressInterest(i, this); <del> ner.addInterest(i); <del> Log.finest("expressed: {0}", i); <del> } <del> } catch (IOException e1) { <del> // error registering new interest <del> Log.warning("error registering new interest in handleContent"); <del> Log.warningStackTrace(e1); <del> } <del> <del> newInterests.clear(); <del> <del> try { <del> neResponse = new NameEnumerationResponseMessageObject(c, _handle); <del> links = neResponse.contents(); <del> for (Link l: links) { <del> names.add(l.targetName()); <del> } <del> //strip off NEMarker before passing through callback <del> callback.handleNameEnumerator( <del> interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()), names); <del> } catch(ContentDecodingException e) { <del> Log.warning("Error parsing Collection from ContentObject in CCNNameEnumerator"); <del> Log.warningStackTrace(e); <del> } catch(IOException e) { <del> Log.warning("error getting CollectionObject from ContentObject in CCNNameEnumerator.handleContent"); <del> Log.warningStackTrace(e); <del> } <del> } <del> } <del> return null; <del> } <del> <add> } <add> <add> _neHandler.add(new CCNContentInterest(c, interest)); <add> return null; <add> } <ide> <ide> /** <ide> * Method for receiving Interests matching the namespace for answering name enumeration requests. Incoming Interests are <ide> } <ide> } <ide> <del> <ide> private ContentName getIdFromName(ContentName name) { <ide> //get the response id, could be more than one component and have a version in it <ide> ContentName responseName = null;
Java
epl-1.0
70bfd913081c4ec4616aca58d2f34b093e5cea05
0
theanuradha/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,debrief/debrief
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library 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. */ package org.mwc.debrief.track_shift.views; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Paint; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.ValueMarker; import org.jfree.data.time.DateRange; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.TextAnchor; import org.mwc.cmap.core.CorePlugin; import org.mwc.debrief.track_shift.controls.ZoneChart.ColorProvider; import org.mwc.debrief.track_shift.controls.ZoneChart.ZoneSlicer; import org.mwc.debrief.track_shift.freq.DopplerCurveFinMath; import org.mwc.debrief.track_shift.freq.IDopplerCurve; import org.mwc.debrief.track_shift.views.StackedDotHelper.SetBackgroundShade; import Debrief.Wrappers.SensorContactWrapper; import Debrief.Wrappers.SensorWrapper; import MWC.GUI.JFreeChart.ColourStandardXYItemRenderer; import MWC.GUI.JFreeChart.ColouredDataItem; import MWC.GenericData.WatchableList; import MWC.Utilities.TextFormatting.GeneralFormat; public class FrequencyResidualsView extends BaseStackedDotsView { private static final int NUM_DOPPLER_STEPS = 30; private Action calcBaseFreq; public FrequencyResidualsView() { super(false, true); } @Override protected void addToolbarExtras(final IToolBarManager toolBarManager) { super.addToolbarExtras(toolBarManager); toolBarManager.add(calcBaseFreq); } private List<WatchableList> getPotentialSources() { if(_ourLayersSubject != null) { } return null; } @Override protected void addPullDownExtras(IMenuManager manager) { super.addPullDownExtras(manager); System.out.println("in pulldown"); // ok, can we add a combo box? manager.add(new Separator()); final MenuManager newMenu = new MenuManager("Acoustic Source"); newMenu.setRemoveAllWhenShown(true); newMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { List<WatchableList> sources = getPotentialSources(); String date = new Date().toString(); Action deleteAction2 = new Action("Placeholder at: " + date) { public void run() { System.out.println("new date pressed"); } }; newMenu.add(deleteAction2); if (sources != null) { for (WatchableList track : sources) { Action deleteAction = new Action(track.getName() + " " + date) { public void run() { System.out.println("new date pressed"); } }; newMenu.add(deleteAction); } } } }); manager.add(newMenu); // } } @Override protected boolean allowDisplayOfTargetOverview() { return false; } @Override protected boolean allowDisplayOfZoneChart() { return false; } private TimeSeries calcSeries(final IDopplerCurve curve, final DateRange curRange) { final TimeSeries res = new TimeSeries("Fitted curve"); final long start = curRange.getLowerMillis(); final long end = curRange.getUpperMillis(); final long step = (end - start) / NUM_DOPPLER_STEPS; for (long t = start; t <= end; t += step) { res.add(new TimeSeriesDataItem(new FixedMillisecond(t), curve.valueAt( t))); } return res; } protected void calculateBaseFreq() { // get the currently visible data final TimeSeriesCollection lineData = (TimeSeriesCollection) _linePlot .getDataset(); final TimeSeries measured = lineData.getSeries( StackedDotHelper.MEASURED_DATASET); if (measured != null) { final ArrayList<Long> times = new ArrayList<Long>(); final ArrayList<Double> freqs = new ArrayList<Double>(); // get the visible time range final DateRange curRange = (DateRange) _linePlot.getDomainAxis() .getRange(); // put the data into the storage structures final SensorWrapper subjectSensor = collateData(measured, times, freqs, curRange); if (!times.isEmpty()) { // generate the doppler curve object final IDopplerCurve curve = new DopplerCurveFinMath(times, freqs); // plot the curve final TimeSeries calculatedData = calcSeries(curve, curRange); lineData.addSeries(calculatedData); // get the base freq final double baseFreq = curve.inflectionFreq(); // and the marker at the new value final Marker target = createFreqMarker(baseFreq); _linePlot.addRangeMarker(target); // what's the current frequency? final double oldFreq; final String freqTxt = GeneralFormat.formatTwoDecimalPlaces(baseFreq); String message; final String fMessage = "F-Nought is:" + freqTxt; if (subjectSensor != null) { oldFreq = subjectSensor.getBaseFrequency(); message = fMessage + "\n" + "Updating base frequency for " + subjectSensor.getName(); } else { oldFreq = Double.NaN; message = fMessage; } showMessage("Calculate f-nought", message); // update the sensor final boolean freqChanged; if (subjectSensor != null && baseFreq != oldFreq) { subjectSensor.setBaseFrequency(baseFreq); freqChanged = true; } else { freqChanged = false; } // and remove the curves lineData.removeSeries(calculatedData); _linePlot.removeRangeMarker(target); // force recalculation, if we've changed the freq if (freqChanged) { updateData(true); } } } } private SensorWrapper collateData(final TimeSeries measured, final ArrayList<Long> times, final ArrayList<Double> freqs, final DateRange curRange) { SensorWrapper subjectSensor = null; // loop through the measured data final Iterator<?> items = measured.getItems().iterator(); while (items.hasNext()) { final ColouredDataItem next = (ColouredDataItem) items.next(); if (curRange.contains(next.getPeriod().getMiddleMillisecond())) { times.add(next.getPeriod().getMiddleMillisecond()); freqs.add(next.getValue().doubleValue()); if (subjectSensor == null) { final SensorContactWrapper cut = (SensorContactWrapper) next .getPayload(); subjectSensor = cut.getSensor(); } } } return subjectSensor; } private Marker createFreqMarker(final double baseFreq) { final Marker target = new ValueMarker(baseFreq); target.setPaint(Color.DARK_GRAY); target.setStroke(new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {10.0f, 6.0f}, 0.0f)); target.setLabel("Target Price"); target.setLabelAnchor(RectangleAnchor.TOP_RIGHT); target.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT); return target; } @Override protected String formatValue(final double value) { return GeneralFormat.formatTwoDecimalPlaces(value); } @Override protected ZoneSlicer getOwnshipZoneSlicer(final ColorProvider blueProv) { // don't bother, it's for bearing data return null; } @Override protected String getType() { return "Frequency"; } @Override protected String getUnits() { return "Hz"; } @Override protected void makeActions() { super.makeActions(); // now frequency calculator calcBaseFreq = new Action("Calculate base frequency", IAction.AS_PUSH_BUTTON) { @Override public void run() { super.run(); calculateBaseFreq(); } }; calcBaseFreq.setChecked(true); calcBaseFreq.setToolTipText( "Calculate the base frequency of the visible frequency cuts"); calcBaseFreq.setImageDescriptor(CorePlugin.getImageDescriptor( "icons/24/f_nought.png")); } public void showMessage(final String title, final String message) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { MessageDialog.openInformation(null, title, message); } }); } @Override protected void updateData(final boolean updateDoublets) { // note: we now ignore the parent doublets value. // this is because we need to regenerate the target fix each time. // For frequency data the target fix is interpolated - this means // it doesn't update as we drag the solution. We need to // regenerate the interpolated fix, to ensure we're using up-to-date // values final boolean updateDoubletsVal = true; final TimeSeriesCollection errorData = (TimeSeriesCollection) _dotPlot .getDataset(); final TimeSeriesCollection lineData = (TimeSeriesCollection) _linePlot .getDataset(); final SetBackgroundShade backgroundShader = new SetBackgroundShade() { @Override public void setShade(Paint errorColor) { _dotPlot.setBackgroundPaint(errorColor); } }; // have we been created? if (_holder == null || _holder.isDisposed()) { return; } // update the current datasets _myHelper.updateFrequencyData(errorData, lineData, _switchableTrackDataProvider, _onlyVisible.isChecked(), this, updateDoubletsVal, backgroundShader, (ColourStandardXYItemRenderer) _linePlot.getRenderer()); } }
org.mwc.debrief.track_shift/src/org/mwc/debrief/track_shift/views/FrequencyResidualsView.java
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library 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. */ package org.mwc.debrief.track_shift.views; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Paint; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.ValueMarker; import org.jfree.data.time.DateRange; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.TimeSeriesDataItem; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.TextAnchor; import org.mwc.cmap.core.CorePlugin; import org.mwc.debrief.track_shift.controls.ZoneChart.ColorProvider; import org.mwc.debrief.track_shift.controls.ZoneChart.ZoneSlicer; import org.mwc.debrief.track_shift.freq.DopplerCurveFinMath; import org.mwc.debrief.track_shift.freq.IDopplerCurve; import org.mwc.debrief.track_shift.views.StackedDotHelper.SetBackgroundShade; import Debrief.Wrappers.SensorContactWrapper; import Debrief.Wrappers.SensorWrapper; import MWC.GUI.JFreeChart.ColourStandardXYItemRenderer; import MWC.GUI.JFreeChart.ColouredDataItem; import MWC.GenericData.WatchableList; import MWC.Utilities.TextFormatting.GeneralFormat; public class FrequencyResidualsView extends BaseStackedDotsView { private static final int NUM_DOPPLER_STEPS = 30; private Action calcBaseFreq; public FrequencyResidualsView() { super(false, true); } @Override protected void addToolbarExtras(final IToolBarManager toolBarManager) { super.addToolbarExtras(toolBarManager); toolBarManager.add(calcBaseFreq); } private List<WatchableList> getPotentialSources() { return null; } @Override protected void addPullDownExtras(IMenuManager manager) { super.addPullDownExtras(manager); System.out.println("in pulldown"); // ok, can we add a combo box? manager.add(new Separator()); final MenuManager newMenu = new MenuManager("Acoustic Source"); newMenu.setRemoveAllWhenShown(true); newMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { List<WatchableList> sources = getPotentialSources(); String date = new Date().toString(); Action deleteAction2 = new Action("Placeholder at: " + date) { public void run() { System.out.println("new date pressed"); } }; newMenu.add(deleteAction2); if (sources != null) { for (WatchableList track : sources) { Action deleteAction = new Action(track.getName() + " " + date) { public void run() { System.out.println("new date pressed"); } }; newMenu.add(deleteAction); } } } }); manager.add(newMenu); // } } @Override protected boolean allowDisplayOfTargetOverview() { return false; } @Override protected boolean allowDisplayOfZoneChart() { return false; } private TimeSeries calcSeries(final IDopplerCurve curve, final DateRange curRange) { final TimeSeries res = new TimeSeries("Fitted curve"); final long start = curRange.getLowerMillis(); final long end = curRange.getUpperMillis(); final long step = (end - start) / NUM_DOPPLER_STEPS; for (long t = start; t <= end; t += step) { res.add(new TimeSeriesDataItem(new FixedMillisecond(t), curve.valueAt( t))); } return res; } protected void calculateBaseFreq() { // get the currently visible data final TimeSeriesCollection lineData = (TimeSeriesCollection) _linePlot .getDataset(); final TimeSeries measured = lineData.getSeries( StackedDotHelper.MEASURED_DATASET); if (measured != null) { final ArrayList<Long> times = new ArrayList<Long>(); final ArrayList<Double> freqs = new ArrayList<Double>(); // get the visible time range final DateRange curRange = (DateRange) _linePlot.getDomainAxis() .getRange(); // put the data into the storage structures final SensorWrapper subjectSensor = collateData(measured, times, freqs, curRange); if (!times.isEmpty()) { // generate the doppler curve object final IDopplerCurve curve = new DopplerCurveFinMath(times, freqs); // plot the curve final TimeSeries calculatedData = calcSeries(curve, curRange); lineData.addSeries(calculatedData); // get the base freq final double baseFreq = curve.inflectionFreq(); // and the marker at the new value final Marker target = createFreqMarker(baseFreq); _linePlot.addRangeMarker(target); // what's the current frequency? final double oldFreq; final String freqTxt = GeneralFormat.formatTwoDecimalPlaces(baseFreq); String message; final String fMessage = "F-Nought is:" + freqTxt; if (subjectSensor != null) { oldFreq = subjectSensor.getBaseFrequency(); message = fMessage + "\n" + "Updating base frequency for " + subjectSensor.getName(); } else { oldFreq = Double.NaN; message = fMessage; } showMessage("Calculate f-nought", message); // update the sensor final boolean freqChanged; if (subjectSensor != null && baseFreq != oldFreq) { subjectSensor.setBaseFrequency(baseFreq); freqChanged = true; } else { freqChanged = false; } // and remove the curves lineData.removeSeries(calculatedData); _linePlot.removeRangeMarker(target); // force recalculation, if we've changed the freq if (freqChanged) { updateData(true); } } } } private SensorWrapper collateData(final TimeSeries measured, final ArrayList<Long> times, final ArrayList<Double> freqs, final DateRange curRange) { SensorWrapper subjectSensor = null; // loop through the measured data final Iterator<?> items = measured.getItems().iterator(); while (items.hasNext()) { final ColouredDataItem next = (ColouredDataItem) items.next(); if (curRange.contains(next.getPeriod().getMiddleMillisecond())) { times.add(next.getPeriod().getMiddleMillisecond()); freqs.add(next.getValue().doubleValue()); if (subjectSensor == null) { final SensorContactWrapper cut = (SensorContactWrapper) next .getPayload(); subjectSensor = cut.getSensor(); } } } return subjectSensor; } private Marker createFreqMarker(final double baseFreq) { final Marker target = new ValueMarker(baseFreq); target.setPaint(Color.DARK_GRAY); target.setStroke(new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {10.0f, 6.0f}, 0.0f)); target.setLabel("Target Price"); target.setLabelAnchor(RectangleAnchor.TOP_RIGHT); target.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT); return target; } @Override protected String formatValue(final double value) { return GeneralFormat.formatTwoDecimalPlaces(value); } @Override protected ZoneSlicer getOwnshipZoneSlicer(final ColorProvider blueProv) { // don't bother, it's for bearing data return null; } @Override protected String getType() { return "Frequency"; } @Override protected String getUnits() { return "Hz"; } @Override protected void makeActions() { super.makeActions(); // now frequency calculator calcBaseFreq = new Action("Calculate base frequency", IAction.AS_PUSH_BUTTON) { @Override public void run() { super.run(); calculateBaseFreq(); } }; calcBaseFreq.setChecked(true); calcBaseFreq.setToolTipText( "Calculate the base frequency of the visible frequency cuts"); calcBaseFreq.setImageDescriptor(CorePlugin.getImageDescriptor( "icons/24/f_nought.png")); } public void showMessage(final String title, final String message) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { MessageDialog.openInformation(null, title, message); } }); } @Override protected void updateData(final boolean updateDoublets) { // note: we now ignore the parent doublets value. // this is because we need to regenerate the target fix each time. // For frequency data the target fix is interpolated - this means // it doesn't update as we drag the solution. We need to // regenerate the interpolated fix, to ensure we're using up-to-date // values final boolean updateDoubletsVal = true; final TimeSeriesCollection errorData = (TimeSeriesCollection) _dotPlot .getDataset(); final TimeSeriesCollection lineData = (TimeSeriesCollection) _linePlot .getDataset(); final SetBackgroundShade backgroundShader = new SetBackgroundShade() { @Override public void setShade(Paint errorColor) { _dotPlot.setBackgroundPaint(errorColor); } }; // have we been created? if (_holder == null || _holder.isDisposed()) { return; } // update the current datasets _myHelper.updateFrequencyData(errorData, lineData, _switchableTrackDataProvider, _onlyVisible.isChecked(), this, updateDoubletsVal, backgroundShader, (ColourStandardXYItemRenderer) _linePlot.getRenderer()); } }
Prepare to walk data model
org.mwc.debrief.track_shift/src/org/mwc/debrief/track_shift/views/FrequencyResidualsView.java
Prepare to walk data model
<ide><path>rg.mwc.debrief.track_shift/src/org/mwc/debrief/track_shift/views/FrequencyResidualsView.java <ide> <ide> private List<WatchableList> getPotentialSources() <ide> { <add> if(_ourLayersSubject != null) <add> { <add> } <ide> return null; <ide> } <ide>
Java
bsd-3-clause
9ec05f90b9c59bc420936718cd8b4a1f20c27aac
0
magrimes/kryonet,EsotericSoftware/kryonet,bgroenks96/kryonet,hgl888/kryonet,archenroot/kryonet,nfirex/kryonet,yuanyuanlove/kryonet,ISkyLove/kryonet,kidaa/kryonet,freakynit/kryonet
package com.esotericsoftware.kryonet; import java.nio.ByteBuffer; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.ByteBufferInputStream; import com.esotericsoftware.kryo.io.ByteBufferOutputStream; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryonet.FrameworkMessage.DiscoverHost; import com.esotericsoftware.kryonet.FrameworkMessage.KeepAlive; import com.esotericsoftware.kryonet.FrameworkMessage.Ping; import com.esotericsoftware.kryonet.FrameworkMessage.RegisterTCP; import com.esotericsoftware.kryonet.FrameworkMessage.RegisterUDP; public class KryoSerialization implements Serialization { private final Kryo kryo; private final Input input; private final Output output; private final ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(); private final ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(); public KryoSerialization () { this(new Kryo()); kryo.setReferences(false); kryo.setRegistrationRequired(true); } public KryoSerialization (Kryo kryo) { this.kryo = kryo; kryo.register(RegisterTCP.class); kryo.register(RegisterUDP.class); kryo.register(KeepAlive.class); kryo.register(DiscoverHost.class); kryo.register(Ping.class); input = new Input(byteBufferInputStream, 512); output = new Output(byteBufferOutputStream, 512); } public Kryo getKryo () { return kryo; } public synchronized void write (Connection connection, ByteBuffer buffer, Object object) { byteBufferOutputStream.setByteBuffer(buffer); kryo.getContext().put("connection", connection); kryo.writeClassAndObject(output, object); output.flush(); } public synchronized Object read (Connection connection, ByteBuffer buffer) { byteBufferInputStream.setByteBuffer(buffer); input.rewind(); kryo.getContext().put("connection", connection); return kryo.readClassAndObject(input); } public void writeLength (ByteBuffer buffer, int length) { buffer.putInt(length); } public int readLength (ByteBuffer buffer) { return buffer.getInt(); } public int getLengthLength () { return 4; } }
kryonet/src/com/esotericsoftware/kryonet/KryoSerialization.java
package com.esotericsoftware.kryonet; import java.nio.ByteBuffer; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.ByteBufferInputStream; import com.esotericsoftware.kryo.io.ByteBufferOutputStream; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryonet.FrameworkMessage.DiscoverHost; import com.esotericsoftware.kryonet.FrameworkMessage.KeepAlive; import com.esotericsoftware.kryonet.FrameworkMessage.Ping; import com.esotericsoftware.kryonet.FrameworkMessage.RegisterTCP; import com.esotericsoftware.kryonet.FrameworkMessage.RegisterUDP; public class KryoSerialization implements Serialization { private final Kryo kryo; private final Input input; private final Output output; private final ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(); private final ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(); public KryoSerialization () { this(new Kryo()); kryo.setReferences(false); kryo.setRegistrationRequired(true); } public KryoSerialization (Kryo kryo) { this.kryo = kryo; kryo.register(RegisterTCP.class); kryo.register(RegisterUDP.class); kryo.register(KeepAlive.class); kryo.register(DiscoverHost.class); kryo.register(Ping.class); input = new Input(byteBufferInputStream, 512); output = new Output(byteBufferOutputStream, 512); } public Kryo getKryo () { return kryo; } public synchronized void write (Connection connection, ByteBuffer buffer, Object object) { byteBufferOutputStream.setByteBuffer(buffer); kryo.getContext().put("connection", connection); kryo.writeClassAndObject(output, object); output.flush(); } public synchronized Object read (Connection connection, ByteBuffer buffer) { byteBufferInputStream.setByteBuffer(buffer); kryo.getContext().put("connection", connection); return kryo.readClassAndObject(input); } public void writeLength (ByteBuffer buffer, int length) { buffer.putInt(length); } public int readLength (ByteBuffer buffer) { return buffer.getInt(); } public int getLengthLength () { return 4; } }
Reset Input before reading.
kryonet/src/com/esotericsoftware/kryonet/KryoSerialization.java
Reset Input before reading.
<ide><path>ryonet/src/com/esotericsoftware/kryonet/KryoSerialization.java <ide> <ide> public synchronized Object read (Connection connection, ByteBuffer buffer) { <ide> byteBufferInputStream.setByteBuffer(buffer); <add> input.rewind(); <ide> kryo.getContext().put("connection", connection); <ide> return kryo.readClassAndObject(input); <ide> }
Java
mit
f6a33b3061f3721c9c78d34d6195b5c6eef85e61
0
gatzka/android-scan,gatzka/android-scan
/* * Android Scan, an app for scanning and configuring HBM devices. * * The MIT License (MIT) * * Copyright (C) Stephan Gatzka * * 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.hbm.devices.scan.ui.android; import com.hbm.devices.scan.announce.Announce; import com.hbm.devices.scan.announce.AnnounceDeserializer; import com.hbm.devices.scan.ui.android.DisplayNotifier; import com.hbm.devices.scan.ui.android.DisplayUpdateEventGenerator; import java.io.IOException; import java.lang.Override; import java.util.ArrayList; import java.io.InputStream; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Properties; import org.junit.Test; import static org.junit.Assert.*; public class DisplayUpdateEventGeneratorTest implements DisplayNotifier, Observer { private List<Announce> oldList = new ArrayList<Announce>(); private List<Announce> newList = new ArrayList<Announce>(); private List<Announce> oldListClone; private List<DisplayEventAt> events = new ArrayList<DisplayEventAt>(); private boolean fillNewList = false; private static final String DEVICE1; private static final String DEVICE1UPDATE; private static final String DEVICE2; private static final String DEVICE3; private static final String DEVICE4; private static final String DEVICE5; private static final String DEVICE6; @Test public void testCompareLists() throws Exception { AnnounceDeserializer parser = new AnnounceDeserializer(); parser.addObserver(this); parser.update(null, DEVICE1); parser.update(null, DEVICE2); parser.update(null, DEVICE3); parser.update(null, DEVICE4); parser.update(null, DEVICE5); fillNewList = true; parser.update(null, DEVICE1UPDATE); parser.update(null, DEVICE2); parser.update(null, DEVICE6); parser.update(null, DEVICE5); parser.update(null, DEVICE4); assertEquals(oldList.size(), 5); assertEquals(newList.size(), 5); oldListClone = new ArrayList<Announce>(oldList.size()); for (Announce item: oldList) { oldListClone.add(item); } assertEquals("Cloned old list not equals to oldList", oldList, oldListClone); DisplayUpdateEventGenerator eventGenerator = new DisplayUpdateEventGenerator(this); eventGenerator.compareLists(oldList, newList); assertEquals("oldList not the same as newList after compareList", oldList, newList); } @Override public void notifyRemoveAt(int position) { events.add(new DisplayEventAt(DisplayEvents.REMOVE, position)); } @Override public void notifyMoved(int fromPosition, int toPosition) { events.add(new DisplayEventAt(DisplayEvents.MOVE, fromPosition, toPosition)); } @Override public void notifyChangeAt(int position) { events.add(new DisplayEventAt(DisplayEvents.UPDATE, position)); } @Override public void notifyAddAt(int position) { events.add(new DisplayEventAt(DisplayEvents.ADD, position)); } @Override public void update(Observable o, Object arg) { final Announce announce = (Announce)arg; if (fillNewList) { newList.add(announce); } else { oldList.add(announce); } } static { try (final InputStream is = FakeMessageReceiver.class.getResourceAsStream("/devices.properties")) { final Properties props = new Properties(); props.load(is); DEVICE1 = props.getProperty("scan.announce.device1"); DEVICE1UPDATE = props.getProperty("scan.announce.device1update"); DEVICE2 = props.getProperty("scan.announce.device2"); DEVICE3 = props.getProperty("scan.announce.device3"); DEVICE4 = props.getProperty("scan.announce.device4"); DEVICE5 = props.getProperty("scan.announce.device5"); DEVICE6 = props.getProperty("scan.announce.device6"); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } enum DisplayEvents { REMOVE, ADD, MOVE, UPDATE } class DisplayEventAt { DisplayEvents event; int position; int fromPosition; int toPosition; DisplayEventAt(DisplayEvents ev, int pos) { this.event = ev; this.position = pos; } DisplayEventAt(DisplayEvents ev, int from, int to) { this.event = ev; this.fromPosition = from; this.toPosition = to; } } }
src/test/java/com/hbm/devices/scan/ui/android/DisplayUpdateEventGeneratorTest.java
/* * Android Scan, an app for scanning and configuring HBM devices. * * The MIT License (MIT) * * Copyright (C) Stephan Gatzka * * 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.hbm.devices.scan.ui.android; import com.hbm.devices.scan.announce.Announce; import com.hbm.devices.scan.announce.AnnounceDeserializer; import com.hbm.devices.scan.ui.android.DisplayNotifier; import java.io.IOException; import java.lang.Override; import java.util.ArrayList; import java.io.InputStream; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Properties; import org.junit.Test; import static org.junit.Assert.*; public class DisplayUpdateEventGeneratorTest implements DisplayNotifier, Observer { private List<Announce> oldList = new ArrayList<Announce>(); private List<Announce> newList = new ArrayList<Announce>(); private boolean fillNewList = false; private static final String DEVICE1; private static final String DEVICE1UPDATE; private static final String DEVICE2; private static final String DEVICE3; private static final String DEVICE4; private static final String DEVICE5; private static final String DEVICE6; @Test public void testCompareLists() throws Exception { AnnounceDeserializer parser = new AnnounceDeserializer(); parser.addObserver(this); parser.update(null, DEVICE1); parser.update(null, DEVICE2); parser.update(null, DEVICE3); parser.update(null, DEVICE4); parser.update(null, DEVICE5); fillNewList = true; parser.update(null, DEVICE1UPDATE); parser.update(null, DEVICE2); parser.update(null, DEVICE6); parser.update(null, DEVICE5); parser.update(null, DEVICE4); assertEquals(oldList.size(), 5); assertEquals(newList.size(), 5); } @Override public void notifyRemoveAt(int position) { } @Override public void notifyMoved(int fromPosition, int toPosition) { } @Override public void notifyChangeAt(int position) { } @Override public void notifyAddAt(int position) { } @Override public void update(Observable o, Object arg) { final Announce announce = (Announce)arg; if (fillNewList) { newList.add(announce); } else { oldList.add(announce); } } static { try (final InputStream is = FakeMessageReceiver.class.getResourceAsStream("/devices.properties")) { final Properties props = new Properties(); props.load(is); DEVICE1 = props.getProperty("scan.announce.device1"); DEVICE1UPDATE = props.getProperty("scan.announce.device1update"); DEVICE2 = props.getProperty("scan.announce.device2"); DEVICE3 = props.getProperty("scan.announce.device3"); DEVICE4 = props.getProperty("scan.announce.device4"); DEVICE5 = props.getProperty("scan.announce.device5"); DEVICE6 = props.getProperty("scan.announce.device6"); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } }
Ensure that content of oldList is the same as newList after compareLists.
src/test/java/com/hbm/devices/scan/ui/android/DisplayUpdateEventGeneratorTest.java
Ensure that content of oldList is the same as newList after compareLists.
<ide><path>rc/test/java/com/hbm/devices/scan/ui/android/DisplayUpdateEventGeneratorTest.java <ide> import com.hbm.devices.scan.announce.Announce; <ide> import com.hbm.devices.scan.announce.AnnounceDeserializer; <ide> import com.hbm.devices.scan.ui.android.DisplayNotifier; <add>import com.hbm.devices.scan.ui.android.DisplayUpdateEventGenerator; <ide> <ide> <ide> import java.io.IOException; <ide> <ide> private List<Announce> oldList = new ArrayList<Announce>(); <ide> private List<Announce> newList = new ArrayList<Announce>(); <add> private List<Announce> oldListClone; <add> <add> private List<DisplayEventAt> events = new ArrayList<DisplayEventAt>(); <add> <ide> private boolean fillNewList = false; <ide> <ide> private static final String DEVICE1; <ide> <ide> assertEquals(oldList.size(), 5); <ide> assertEquals(newList.size(), 5); <add> oldListClone = new ArrayList<Announce>(oldList.size()); <add> for (Announce item: oldList) { <add> oldListClone.add(item); <add> } <add> assertEquals("Cloned old list not equals to oldList", oldList, oldListClone); <add> DisplayUpdateEventGenerator eventGenerator = new DisplayUpdateEventGenerator(this); <add> eventGenerator.compareLists(oldList, newList); <add> assertEquals("oldList not the same as newList after compareList", oldList, newList); <ide> } <ide> <ide> @Override <ide> public void notifyRemoveAt(int position) { <del> <add> events.add(new DisplayEventAt(DisplayEvents.REMOVE, position)); <ide> } <ide> <ide> @Override <ide> public void notifyMoved(int fromPosition, int toPosition) { <del> <add> events.add(new DisplayEventAt(DisplayEvents.MOVE, fromPosition, toPosition)); <ide> } <ide> <ide> @Override <ide> public void notifyChangeAt(int position) { <del> <add> events.add(new DisplayEventAt(DisplayEvents.UPDATE, position)); <ide> } <ide> <ide> @Override <ide> public void notifyAddAt(int position) { <del> <add> events.add(new DisplayEventAt(DisplayEvents.ADD, position)); <ide> } <ide> <ide> @Override <ide> throw new ExceptionInInitializerError(e); <ide> } <ide> } <add> <add> enum DisplayEvents { <add> REMOVE, ADD, MOVE, UPDATE <add> } <add> <add> class DisplayEventAt { <add> DisplayEvents event; <add> int position; <add> int fromPosition; <add> int toPosition; <add> <add> DisplayEventAt(DisplayEvents ev, int pos) { <add> this.event = ev; <add> this.position = pos; <add> } <add> <add> DisplayEventAt(DisplayEvents ev, int from, int to) { <add> this.event = ev; <add> this.fromPosition = from; <add> this.toPosition = to; <add> } <add> } <ide> }
Java
isc
739eaae5b923ac9d3c9960cdc129b4c546e00c5f
0
TealCube/loot
package info.faceland.loot.tier; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import org.bukkit.ChatColor; import java.util.List; import java.util.Set; public final class LootTierBuilder implements TierBuilder { private boolean built = false; private LootTier tier; public LootTierBuilder(String name) { tier = new LootTier(name); } @Override public boolean isBuilt() { return built; } @Override public Tier build() { if (isBuilt()) { throw new IllegalStateException("already built"); } built = true; return tier; } @Override public TierBuilder withDisplayName(String s) { tier.setDisplayName(s); return this; } @Override public TierBuilder withDisplayColor(ChatColor c) { tier.setDisplayColor(c); return this; } @Override public TierBuilder withIdentificationColor(ChatColor c) { tier.setIdentificationColor(c); return this; } @Override public TierBuilder withSpawnWeight(double d) { tier.setSpawnWeight(d); return this; } @Override public TierBuilder withIdentifyWeight(double d) { tier.setIdentifyWeight(d); return this; } @Override public TierBuilder withMinimumSockets(int i) { tier.setMinimumSockets(i); return this; } @Override public TierBuilder withMaximumSockets(int i) { tier.setMaximumSockets(i); return this; } @Override public TierBuilder withMinimumBonusLore(int i) { tier.setMinimumBonusLore(i); return this; } @Override public TierBuilder withMaximumBonusLore(int i) { tier.setMaximumBonusLore(i); return this; } @Override public TierBuilder withBaseLore(List<String> l) { tier.setBaseLore(l); return this; } @Override public TierBuilder withBonusLore(List<String> l) { tier.setBonusLore(l); return this; } @Override public TierBuilder withItemGroups(Set<ItemGroup> s) { tier.setItemGroups(s); return this; } @Override public TierBuilder withMinimumDurability(double d) { tier.setMinimumDurability(d); return this; } @Override public TierBuilder withMaximumDurability(double d) { tier.setMaximumDurability(d); return this; } @Override public TierBuilder withDistanceWeight(double d) { tier.setDistanceWeight(d); return this; } @Override public TierBuilder withEnchantable(boolean b) { tier.setEnchantable(b); return this; } }
src/main/java/info/faceland/loot/tier/LootTierBuilder.java
package info.faceland.loot.tier; import info.faceland.loot.api.groups.ItemGroup; import info.faceland.loot.api.tier.Tier; import info.faceland.loot.api.tier.TierBuilder; import org.bukkit.ChatColor; import java.util.List; import java.util.Set; public final class LootTierBuilder implements TierBuilder { private boolean built = false; private LootTier tier; public LootTierBuilder(String name) { tier = new LootTier(name); } @Override public boolean isBuilt() { return built; } @Override public Tier build() { if (isBuilt()) { throw new IllegalStateException("already built"); } return tier; } @Override public TierBuilder withDisplayName(String s) { tier.setDisplayName(s); return this; } @Override public TierBuilder withDisplayColor(ChatColor c) { tier.setDisplayColor(c); return this; } @Override public TierBuilder withIdentificationColor(ChatColor c) { tier.setIdentificationColor(c); return this; } @Override public TierBuilder withSpawnWeight(double d) { tier.setSpawnWeight(d); return this; } @Override public TierBuilder withIdentifyWeight(double d) { tier.setIdentifyWeight(d); return this; } @Override public TierBuilder withMinimumSockets(int i) { tier.setMinimumSockets(i); return this; } @Override public TierBuilder withMaximumSockets(int i) { tier.setMaximumSockets(i); return this; } @Override public TierBuilder withMinimumBonusLore(int i) { tier.setMinimumBonusLore(i); return this; } @Override public TierBuilder withMaximumBonusLore(int i) { tier.setMaximumBonusLore(i); return this; } @Override public TierBuilder withBaseLore(List<String> l) { tier.setBaseLore(l); return this; } @Override public TierBuilder withBonusLore(List<String> l) { tier.setBonusLore(l); return this; } @Override public TierBuilder withItemGroups(Set<ItemGroup> s) { tier.setItemGroups(s); return this; } @Override public TierBuilder withMinimumDurability(double d) { tier.setMinimumDurability(d); return this; } @Override public TierBuilder withMaximumDurability(double d) { tier.setMaximumDurability(d); return this; } @Override public TierBuilder withDistanceWeight(double d) { tier.setDistanceWeight(d); return this; } @Override public TierBuilder withEnchantable(boolean b) { tier.setEnchantable(b); return this; } }
actually marking as built
src/main/java/info/faceland/loot/tier/LootTierBuilder.java
actually marking as built
<ide><path>rc/main/java/info/faceland/loot/tier/LootTierBuilder.java <ide> if (isBuilt()) { <ide> throw new IllegalStateException("already built"); <ide> } <add> built = true; <ide> return tier; <ide> } <ide>
Java
apache-2.0
65eb4e96f58edf0f77733955b472e217ea008f6d
0
DTL-FAIRData/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint,DTL-FAIRData/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint,DTL-FAIRData/ODEX-FAIRDataPoint,DTL-FAIRData/ODEX-FAIRDataPoint,NLeSC/ODEX-FAIRDataPoint
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.dtls.fairdatapoint.api.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.ThreadContext; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; /** * * Filter to add mandatory headers to all request * * @author Rajaram Kaliyaperumal * @since 2015-11-19 * @version 0.1 */ @Component public class ApplicationFilter implements Filter { private FilterConfig filterConfig; @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } @Override public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) sr1; HttpServletRequest request = (HttpServletRequest)sr; response.setHeader(HttpHeaders.SERVER, "FAIR data point (JAVA)"); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.setHeader(HttpHeaders.ALLOW, (RequestMethod.GET.name())); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, (HttpHeaders.ACCEPT)); ThreadContext.put("ipAddress", request.getRemoteAddr()); ThreadContext.put("responseStatus", String.valueOf( response.getStatus())); fc.doFilter(sr, sr1); ThreadContext.clearAll(); } @Override public void destroy() {} }
fdp-api/java/FairDataPoint/src/main/java/nl/dtls/fairdatapoint/api/config/ApplicationFilter.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.dtls.fairdatapoint.api.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; /** * * Filter to add mandatory headers to all request * * @author Rajaram Kaliyaperumal * @since 2015-11-19 * @version 0.1 */ @Component public class ApplicationFilter implements Filter { @Override public void init(FilterConfig fc) throws ServletException {} @Override public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) sr1; response.setHeader(HttpHeaders.SERVER, "FAIR data point (JAVA)"); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.setHeader(HttpHeaders.ALLOW, (RequestMethod.GET.name())); response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, (HttpHeaders.ACCEPT)); fc.doFilter(sr, sr1); } @Override public void destroy() {} }
Application filter added to set the mandatory headers
fdp-api/java/FairDataPoint/src/main/java/nl/dtls/fairdatapoint/api/config/ApplicationFilter.java
Application filter added to set the mandatory headers
<ide><path>dp-api/java/FairDataPoint/src/main/java/nl/dtls/fairdatapoint/api/config/ApplicationFilter.java <ide> import javax.servlet.ServletException; <ide> import javax.servlet.ServletRequest; <ide> import javax.servlet.ServletResponse; <add>import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <add>import org.apache.logging.log4j.ThreadContext; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.stereotype.Component; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> */ <ide> @Component <ide> public class ApplicationFilter implements Filter { <del> <add> <add> private FilterConfig filterConfig; <add> <ide> @Override <del> public void init(FilterConfig fc) throws ServletException {} <add> public void init(FilterConfig filterConfig) throws ServletException { <add> this.filterConfig = filterConfig; <add> } <ide> <ide> @Override <ide> public void doFilter(ServletRequest sr, ServletResponse sr1, <del> FilterChain fc) throws IOException, ServletException { <del> HttpServletResponse response = (HttpServletResponse) sr1; <del> response.setHeader(HttpHeaders.SERVER, "FAIR data point (JAVA)"); <del> response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); <del> response.setHeader(HttpHeaders.ALLOW, (RequestMethod.GET.name())); <del> response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, <del> (HttpHeaders.ACCEPT)); <del> fc.doFilter(sr, sr1); <add> FilterChain fc) throws IOException, ServletException { <add> HttpServletResponse response = (HttpServletResponse) sr1; <add> HttpServletRequest request = (HttpServletRequest)sr; <add> response.setHeader(HttpHeaders.SERVER, "FAIR data point (JAVA)"); <add> response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); <add> response.setHeader(HttpHeaders.ALLOW, (RequestMethod.GET.name())); <add> response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, <add> (HttpHeaders.ACCEPT)); <add> ThreadContext.put("ipAddress", request.getRemoteAddr()); <add> ThreadContext.put("responseStatus", String.valueOf( <add> response.getStatus())); <add> fc.doFilter(sr, sr1); <add> ThreadContext.clearAll(); <ide> } <ide> <ide> @Override
JavaScript
apache-2.0
8c0c7ab844c3ffff41fcc8350f9a98cb71d99c92
0
tchibirev/Prebid.js,PWyrembak/Prebid.js,gumgum/Prebid.js,gumgum/Prebid.js,Niksok/Prebid.js,ImproveDigital/Prebid.js,ImproveDigital/Prebid.js,HuddledMasses/Prebid.js,prebid/Prebid.js,HuddledMasses/Prebid.js,prebid/Prebid.js,ImproveDigital/Prebid.js,PWyrembak/Prebid.js,mcallari/Prebid.js,PWyrembak/Prebid.js,passit/Prebid.js,Niksok/Prebid.js,PubWise/Prebid.js,Niksok/Prebid.js,gumgum/Prebid.js,HuddledMasses/Prebid.js,prebid/Prebid.js,mcallari/Prebid.js,tchibirev/Prebid.js,PubWise/Prebid.js,PubWise/Prebid.js,passit/Prebid.js
import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adaptermanager from '../src/adapterManager.js'; import * as utils from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; export const storage = getStorageManager(); /** * Analytics adapter for - https://liveramp.com * Maintainer - [email protected] */ const analyticsType = 'endpoint'; // dev endpoints // const preflightUrl = 'https://analytics-check.publishersite.xyz/check/'; // export const analyticsUrl = 'https://analyticsv2.publishersite.xyz'; const preflightUrl = 'https://check.analytics.rlcdn.com/check/'; export const analyticsUrl = 'https://analytics.rlcdn.com'; let handlerRequest = []; let handlerResponse = []; let atsAnalyticsAdapterVersion = 1; let browsersList = [ /* Googlebot */ { test: /googlebot/i, name: 'Googlebot' }, /* Opera < 13.0 */ { test: /opera/i, name: 'Opera', }, /* Opera > 13.0 */ { test: /opr\/|opios/i, name: 'Opera' }, { test: /SamsungBrowser/i, name: 'Samsung Internet for Android', }, { test: /Whale/i, name: 'NAVER Whale Browser', }, { test: /MZBrowser/i, name: 'MZ Browser' }, { test: /focus/i, name: 'Focus', }, { test: /swing/i, name: 'Swing', }, { test: /coast/i, name: 'Opera Coast', }, { test: /opt\/\d+(?:.?_?\d+)+/i, name: 'Opera Touch', }, { test: /yabrowser/i, name: 'Yandex Browser', }, { test: /ucbrowser/i, name: 'UC Browser', }, { test: /Maxthon|mxios/i, name: 'Maxthon', }, { test: /epiphany/i, name: 'Epiphany', }, { test: /puffin/i, name: 'Puffin', }, { test: /sleipnir/i, name: 'Sleipnir', }, { test: /k-meleon/i, name: 'K-Meleon', }, { test: /micromessenger/i, name: 'WeChat', }, { test: /qqbrowser/i, name: (/qqbrowserlite/i).test(window.navigator.userAgent) ? 'QQ Browser Lite' : 'QQ Browser', }, { test: /msie|trident/i, name: 'Internet Explorer', }, { test: /\sedg\//i, name: 'Microsoft Edge', }, { test: /edg([ea]|ios)/i, name: 'Microsoft Edge', }, { test: /vivaldi/i, name: 'Vivaldi', }, { test: /seamonkey/i, name: 'SeaMonkey', }, { test: /sailfish/i, name: 'Sailfish', }, { test: /silk/i, name: 'Amazon Silk', }, { test: /phantom/i, name: 'PhantomJS', }, { test: /slimerjs/i, name: 'SlimerJS', }, { test: /blackberry|\bbb\d+/i, name: 'BlackBerry', }, { test: /(web|hpw)[o0]s/i, name: 'WebOS Browser', }, { test: /bada/i, name: 'Bada', }, { test: /tizen/i, name: 'Tizen', }, { test: /qupzilla/i, name: 'QupZilla', }, { test: /firefox|iceweasel|fxios/i, name: 'Firefox', }, { test: /electron/i, name: 'Electron', }, { test: /MiuiBrowser/i, name: 'Miui', }, { test: /chromium/i, name: 'Chromium', }, { test: /chrome|crios|crmo/i, name: 'Chrome', }, { test: /GSA/i, name: 'Google Search', }, /* Android Browser */ { test: /android/i, name: 'Android Browser', }, /* PlayStation 4 */ { test: /playstation 4/i, name: 'PlayStation 4', }, /* Safari */ { test: /safari|applewebkit/i, name: 'Safari', }, ]; function setSamplingCookie(samplRate) { let now = new Date(); now.setTime(now.getTime() + 3600000); storage.setCookie('_lr_sampling_rate', samplRate, now.toUTCString()); } let listOfSupportedBrowsers = ['Safari', 'Chrome', 'Firefox', 'Microsoft Edge']; function bidRequestedHandler(args) { let envelopeSourceCookieValue = storage.getCookie('_lr_env_src_ats'); let envelopeSource = envelopeSourceCookieValue === 'true'; let requests; requests = args.bids.map(function(bid) { return { envelope_source: envelopeSource, has_envelope: bid.userId ? !!bid.userId.idl_env : false, bidder: bid.bidder, bid_id: bid.bidId, auction_id: args.auctionId, user_browser: parseBrowser(), user_platform: navigator.platform, auction_start: new Date(args.auctionStart).toJSON(), domain: window.location.hostname, pid: atsAnalyticsAdapter.context.pid, adapter_version: atsAnalyticsAdapterVersion }; }); return requests; } function bidResponseHandler(args) { return { bid_id: args.requestId, response_time_stamp: new Date(args.responseTimestamp).toJSON(), currency: args.currency, cpm: args.cpm, net_revenue: args.netRevenue }; } export function parseBrowser() { let ua = atsAnalyticsAdapter.getUserAgent(); try { let result = browsersList.filter(function(obj) { return obj.test.test(ua); }); let browserName = result && result.length ? result[0].name : ''; return (listOfSupportedBrowsers.indexOf(browserName) >= 0) ? browserName : 'Unknown'; } catch (err) { utils.logError('ATS Analytics - Error while checking user browser!', err); } } function sendDataToAnalytic () { // send data to ats analytic endpoint try { let dataToSend = {'Data': atsAnalyticsAdapter.context.events}; let strJSON = JSON.stringify(dataToSend); utils.logInfo('ATS Analytics - tried to send analytics data!'); ajax(analyticsUrl, function () { }, strJSON, {method: 'POST', contentType: 'application/json'}); } catch (err) { utils.logError('ATS Analytics - request encounter an error: ', err); } } // preflight request, to check did publisher have permission to send data to analytics endpoint function preflightRequest (envelopeSourceCookieValue) { ajax(preflightUrl + atsAnalyticsAdapter.context.pid, function (data) { let samplingRateObject = JSON.parse(data); utils.logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); let samplingRate = samplingRateObject['samplingRate']; setSamplingCookie(samplingRate); let samplingRateNumber = Number(samplingRate); if (data && samplingRate && atsAnalyticsAdapter.shouldFireRequest(samplingRateNumber) && envelopeSourceCookieValue != null) { sendDataToAnalytic(); } }, undefined, { method: 'GET', crossOrigin: true }); } function callHandler(evtype, args) { if (evtype === CONSTANTS.EVENTS.BID_REQUESTED) { handlerRequest = handlerRequest.concat(bidRequestedHandler(args)); } else if (evtype === CONSTANTS.EVENTS.BID_RESPONSE) { handlerResponse.push(bidResponseHandler(args)); } if (evtype === CONSTANTS.EVENTS.AUCTION_END) { if (handlerRequest.length) { let events = []; if (handlerResponse.length) { events = handlerRequest.filter(request => handlerResponse.filter(function(response) { if (request.bid_id === response.bid_id) { Object.assign(request, response); } })); } else { events = handlerRequest; } atsAnalyticsAdapter.context.events = events; } } } let atsAnalyticsAdapter = Object.assign(adapter( { analyticsType }), { track({eventType, args}) { if (typeof args !== 'undefined') { callHandler(eventType, args); } if (eventType === CONSTANTS.EVENTS.AUCTION_END) { let envelopeSourceCookieValue = storage.getCookie('_lr_env_src_ats'); try { utils.logInfo('ATS Analytics - preflight request!'); let samplingRateCookie = storage.getCookie('_lr_sampling_rate'); if (!samplingRateCookie) { preflightRequest(envelopeSourceCookieValue); } else { if (atsAnalyticsAdapter.shouldFireRequest(parseInt(samplingRateCookie)) && envelopeSourceCookieValue != null) { sendDataToAnalytic(); } } } catch (err) { utils.logError('ATS Analytics - preflight request encounter an error: ', err); } } } }); // save the base class function atsAnalyticsAdapter.originEnableAnalytics = atsAnalyticsAdapter.enableAnalytics; // add check to not fire request every time, but instead to send 1/10 events atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) { let shouldFireRequestValue = (Math.floor((Math.random() * samplingRate + 1)) === samplingRate); utils.logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); return shouldFireRequestValue; }; atsAnalyticsAdapter.getUserAgent = function () { return window.navigator.userAgent; }; // override enableAnalytics so we can get access to the config passed in from the page atsAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.pid) { utils.logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); return; } atsAnalyticsAdapter.context = { events: [], pid: config.options.pid }; let initOptions = config.options; atsAnalyticsAdapter.originEnableAnalytics(initOptions); // call the base class function }; adaptermanager.registerAnalyticsAdapter({ adapter: atsAnalyticsAdapter, code: 'atsAnalytics', gvlid: 97 }); export default atsAnalyticsAdapter;
modules/atsAnalyticsAdapter.js
import adapter from '../src/AnalyticsAdapter.js'; import CONSTANTS from '../src/constants.json'; import adaptermanager from '../src/adapterManager.js'; import * as utils from '../src/utils.js'; import {ajax} from '../src/ajax.js'; import {getStorageManager} from '../src/storageManager.js'; export const storage = getStorageManager(); const analyticsType = 'endpoint'; // dev endpoints // const preflightUrl = 'https://analytics-check.publishersite.xyz/check/'; // export const analyticsUrl = 'https://analyticsv2.publishersite.xyz'; const preflightUrl = 'https://check.analytics.rlcdn.com/check/'; export const analyticsUrl = 'https://analytics.rlcdn.com'; let handlerRequest = []; let handlerResponse = []; let atsAnalyticsAdapterVersion = 1; let browsersList = [ /* Googlebot */ { test: /googlebot/i, name: 'Googlebot' }, /* Opera < 13.0 */ { test: /opera/i, name: 'Opera', }, /* Opera > 13.0 */ { test: /opr\/|opios/i, name: 'Opera' }, { test: /SamsungBrowser/i, name: 'Samsung Internet for Android', }, { test: /Whale/i, name: 'NAVER Whale Browser', }, { test: /MZBrowser/i, name: 'MZ Browser' }, { test: /focus/i, name: 'Focus', }, { test: /swing/i, name: 'Swing', }, { test: /coast/i, name: 'Opera Coast', }, { test: /opt\/\d+(?:.?_?\d+)+/i, name: 'Opera Touch', }, { test: /yabrowser/i, name: 'Yandex Browser', }, { test: /ucbrowser/i, name: 'UC Browser', }, { test: /Maxthon|mxios/i, name: 'Maxthon', }, { test: /epiphany/i, name: 'Epiphany', }, { test: /puffin/i, name: 'Puffin', }, { test: /sleipnir/i, name: 'Sleipnir', }, { test: /k-meleon/i, name: 'K-Meleon', }, { test: /micromessenger/i, name: 'WeChat', }, { test: /qqbrowser/i, name: (/qqbrowserlite/i).test(window.navigator.userAgent) ? 'QQ Browser Lite' : 'QQ Browser', }, { test: /msie|trident/i, name: 'Internet Explorer', }, { test: /\sedg\//i, name: 'Microsoft Edge', }, { test: /edg([ea]|ios)/i, name: 'Microsoft Edge', }, { test: /vivaldi/i, name: 'Vivaldi', }, { test: /seamonkey/i, name: 'SeaMonkey', }, { test: /sailfish/i, name: 'Sailfish', }, { test: /silk/i, name: 'Amazon Silk', }, { test: /phantom/i, name: 'PhantomJS', }, { test: /slimerjs/i, name: 'SlimerJS', }, { test: /blackberry|\bbb\d+/i, name: 'BlackBerry', }, { test: /(web|hpw)[o0]s/i, name: 'WebOS Browser', }, { test: /bada/i, name: 'Bada', }, { test: /tizen/i, name: 'Tizen', }, { test: /qupzilla/i, name: 'QupZilla', }, { test: /firefox|iceweasel|fxios/i, name: 'Firefox', }, { test: /electron/i, name: 'Electron', }, { test: /MiuiBrowser/i, name: 'Miui', }, { test: /chromium/i, name: 'Chromium', }, { test: /chrome|crios|crmo/i, name: 'Chrome', }, { test: /GSA/i, name: 'Google Search', }, /* Android Browser */ { test: /android/i, name: 'Android Browser', }, /* PlayStation 4 */ { test: /playstation 4/i, name: 'PlayStation 4', }, /* Safari */ { test: /safari|applewebkit/i, name: 'Safari', }, ]; function setSamplingCookie(samplRate) { let now = new Date(); now.setTime(now.getTime() + 3600000); storage.setCookie('_lr_sampling_rate', samplRate, now.toUTCString()); } let listOfSupportedBrowsers = ['Safari', 'Chrome', 'Firefox', 'Microsoft Edge']; function bidRequestedHandler(args) { let envelopeSourceCookieValue = storage.getCookie('_lr_env_src_ats'); let envelopeSource = envelopeSourceCookieValue === 'true'; let requests; requests = args.bids.map(function(bid) { return { envelope_source: envelopeSource, has_envelope: bid.userId ? !!bid.userId.idl_env : false, bidder: bid.bidder, bid_id: bid.bidId, auction_id: args.auctionId, user_browser: parseBrowser(), user_platform: navigator.platform, auction_start: new Date(args.auctionStart).toJSON(), domain: window.location.hostname, pid: atsAnalyticsAdapter.context.pid, adapter_version: atsAnalyticsAdapterVersion }; }); return requests; } function bidResponseHandler(args) { return { bid_id: args.requestId, response_time_stamp: new Date(args.responseTimestamp).toJSON(), currency: args.currency, cpm: args.cpm, net_revenue: args.netRevenue }; } export function parseBrowser() { let ua = atsAnalyticsAdapter.getUserAgent(); try { let result = browsersList.filter(function(obj) { return obj.test.test(ua); }); let browserName = result && result.length ? result[0].name : ''; return (listOfSupportedBrowsers.indexOf(browserName) >= 0) ? browserName : 'Unknown'; } catch (err) { utils.logError('ATS Analytics - Error while checking user browser!', err); } } function sendDataToAnalytic () { // send data to ats analytic endpoint try { let dataToSend = {'Data': atsAnalyticsAdapter.context.events}; let strJSON = JSON.stringify(dataToSend); utils.logInfo('ATS Analytics - tried to send analytics data!'); ajax(analyticsUrl, function () { }, strJSON, {method: 'POST', contentType: 'application/json'}); } catch (err) { utils.logError('ATS Analytics - request encounter an error: ', err); } } // preflight request, to check did publisher have permission to send data to analytics endpoint function preflightRequest (envelopeSourceCookieValue) { ajax(preflightUrl + atsAnalyticsAdapter.context.pid, function (data) { let samplingRateObject = JSON.parse(data); utils.logInfo('ATS Analytics - Sampling Rate: ', samplingRateObject); let samplingRate = samplingRateObject['samplingRate']; setSamplingCookie(samplingRate); let samplingRateNumber = Number(samplingRate); if (data && samplingRate && atsAnalyticsAdapter.shouldFireRequest(samplingRateNumber) && envelopeSourceCookieValue != null) { sendDataToAnalytic(); } }, undefined, { method: 'GET', crossOrigin: true }); } function callHandler(evtype, args) { if (evtype === CONSTANTS.EVENTS.BID_REQUESTED) { handlerRequest = handlerRequest.concat(bidRequestedHandler(args)); } else if (evtype === CONSTANTS.EVENTS.BID_RESPONSE) { handlerResponse.push(bidResponseHandler(args)); } if (evtype === CONSTANTS.EVENTS.AUCTION_END) { if (handlerRequest.length) { let events = []; if (handlerResponse.length) { events = handlerRequest.filter(request => handlerResponse.filter(function(response) { if (request.bid_id === response.bid_id) { Object.assign(request, response); } })); } else { events = handlerRequest; } atsAnalyticsAdapter.context.events = events; } } } let atsAnalyticsAdapter = Object.assign(adapter( { analyticsType }), { track({eventType, args}) { if (typeof args !== 'undefined') { callHandler(eventType, args); } if (eventType === CONSTANTS.EVENTS.AUCTION_END) { let envelopeSourceCookieValue = storage.getCookie('_lr_env_src_ats'); try { utils.logInfo('ATS Analytics - preflight request!'); let samplingRateCookie = storage.getCookie('_lr_sampling_rate'); if (!samplingRateCookie) { preflightRequest(envelopeSourceCookieValue); } else { if (atsAnalyticsAdapter.shouldFireRequest(parseInt(samplingRateCookie)) && envelopeSourceCookieValue != null) { sendDataToAnalytic(); } } } catch (err) { utils.logError('ATS Analytics - preflight request encounter an error: ', err); } } } }); // save the base class function atsAnalyticsAdapter.originEnableAnalytics = atsAnalyticsAdapter.enableAnalytics; // add check to not fire request every time, but instead to send 1/10 events atsAnalyticsAdapter.shouldFireRequest = function (samplingRate) { let shouldFireRequestValue = (Math.floor((Math.random() * samplingRate + 1)) === samplingRate); utils.logInfo('ATS Analytics - Should Fire Request: ', shouldFireRequestValue); return shouldFireRequestValue; }; atsAnalyticsAdapter.getUserAgent = function () { return window.navigator.userAgent; }; // override enableAnalytics so we can get access to the config passed in from the page atsAnalyticsAdapter.enableAnalytics = function (config) { if (!config.options.pid) { utils.logError('ATS Analytics - Publisher ID (pid) option is not defined. Analytics won\'t work'); return; } atsAnalyticsAdapter.context = { events: [], pid: config.options.pid }; let initOptions = config.options; atsAnalyticsAdapter.originEnableAnalytics(initOptions); // call the base class function }; adaptermanager.registerAnalyticsAdapter({ adapter: atsAnalyticsAdapter, code: 'atsAnalytics', gvlid: 97 }); export default atsAnalyticsAdapter;
ATS-analytics - add comment clarifying ownership of atsAnalytics (#6257)
modules/atsAnalyticsAdapter.js
ATS-analytics - add comment clarifying ownership of atsAnalytics (#6257)
<ide><path>odules/atsAnalyticsAdapter.js <ide> import {getStorageManager} from '../src/storageManager.js'; <ide> <ide> export const storage = getStorageManager(); <add> <add>/** <add> * Analytics adapter for - https://liveramp.com <add> * Maintainer - [email protected] <add> */ <ide> <ide> const analyticsType = 'endpoint'; <ide> // dev endpoints
JavaScript
lgpl-2.1
7157dfff0189bdfab1044e6e1667328861abf758
0
arilivigni/cockpit,larsu/cockpit,michalskrivanek/cockpit,deryni/cockpit,larsu/cockpit,andreasn/cockpit,cockpituous/cockpit,sgallagher/cockpit,SotolitoLabs/cockpit,deryni/cockpit,Scribery/cockpit,stefwalter/cockpit,larsu/cockpit,garrett/cockpit,arilivigni/cockpit,petervo/cockpit,garrett/cockpit,larsu/cockpit,andreasn/cockpit,mvollmer/cockpit,garrett/cockpit,martinpitt/cockpit,cockpituous/cockpit,andreasn/cockpit,arilivigni/cockpit,moraleslazaro/cockpit,michalskrivanek/cockpit,larskarlitski/cockpit,dperpeet/cockpit,larskarlitski/cockpit,mareklibra/cockpit,petervo/cockpit,mvollmer/cockpit,xhad/cockpit,harishanand95/cockpit,sgallagher/cockpit,Scribery/cockpit,SotolitoLabs/cockpit,dperpeet/cockpit,sgallagher/cockpit,deryni/cockpit,stefwalter/cockpit,larskarlitski/cockpit,cockpituous/cockpit,dperpeet/cockpit,stefwalter/cockpit,martinpitt/cockpit,harishanand95/cockpit,larskarlitski/cockpit,dperpeet/cockpit,SotolitoLabs/cockpit,sgallagher/cockpit,martinpitt/cockpit,garrett/cockpit,petervo/cockpit,Scribery/cockpit,vanloswang/cockpit,arilivigni/cockpit,cockpit-project/cockpit,vanloswang/cockpit,cockpit-project/cockpit,petervo/cockpit,mvollmer/cockpit,cockpit-project/cockpit,xhad/cockpit,larsu/cockpit,xhad/cockpit,michalskrivanek/cockpit,cockpit-project/cockpit,andreasn/cockpit,petervo/cockpit,andreasn/cockpit,sgallagher/cockpit,stefwalter/cockpit,larskarlitski/cockpit,sgallagher/cockpit,harishanand95/cockpit,harishanand95/cockpit,Scribery/cockpit,vanloswang/cockpit,mareklibra/cockpit,harishanand95/cockpit,cockpituous/cockpit,mvollmer/cockpit,Scribery/cockpit,mareklibra/cockpit,xhad/cockpit,arilivigni/cockpit,moraleslazaro/cockpit,petervo/cockpit,cockpit-project/cockpit,mareklibra/cockpit,SotolitoLabs/cockpit,Scribery/cockpit,dperpeet/cockpit,michalskrivanek/cockpit,mareklibra/cockpit,deryni/cockpit,andreasn/cockpit,sgallagher/cockpit,cockpituous/cockpit,moraleslazaro/cockpit,SotolitoLabs/cockpit,larsu/cockpit,mvollmer/cockpit,larskarlitski/cockpit,xhad/cockpit,moraleslazaro/cockpit,dperpeet/cockpit,harishanand95/cockpit,vanloswang/cockpit,mareklibra/cockpit,petervo/cockpit,cockpituous/cockpit,andreasn/cockpit,dperpeet/cockpit,vanloswang/cockpit,stefwalter/cockpit,deryni/cockpit,garrett/cockpit,michalskrivanek/cockpit,vanloswang/cockpit,moraleslazaro/cockpit,arilivigni/cockpit,martinpitt/cockpit,harishanand95/cockpit,mareklibra/cockpit,moraleslazaro/cockpit,stefwalter/cockpit,deryni/cockpit,moraleslazaro/cockpit,martinpitt/cockpit,larskarlitski/cockpit,arilivigni/cockpit,stefwalter/cockpit,michalskrivanek/cockpit,xhad/cockpit,michalskrivanek/cockpit,deryni/cockpit,Scribery/cockpit,SotolitoLabs/cockpit,vanloswang/cockpit,xhad/cockpit,SotolitoLabs/cockpit
/* * This file is part of Cockpit. * * Copyright (C) 2015 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ (function() { "use strict"; var $ = require('jquery'); var cockpit = require('cockpit'); var utils = require('./utils'); /* STORAGED CLIENT */ /* HACK: https://github.com/storaged-project/storaged/pull/68 */ var config = { }; if (cockpit.manifests["storage"] && cockpit.manifests["storage"]["config"]) config = cockpit.manifests["storage"]["config"]; var client = { }; /* Metrics */ function instance_sampler(metrics) { var instances; var self = { data: { }, close: close }; function handle_meta(msg) { self.data = { }; instances = [ ]; for (var m = 0; m < msg.metrics.length; m++) { instances[m] = msg.metrics[m].instances; for (var i = 0; i < instances[m].length; i++) self.data[instances[m][i]] = [ ]; } } function handle_data(msg) { var changed = false; for (var s = 0; s < msg.length; s++) { var metrics = msg[s]; for (var m = 0; m < metrics.length; m++) { var inst = metrics[m]; for (var i = 0; i < inst.length; i++) { if (inst[i] !== null) { changed = true; self.data[instances[m][i]][m] = inst[i]; } } } } if (changed) $(self).triggerHandler('changed'); } var channel = cockpit.channel({ payload: "metrics1", source: "internal", metrics: metrics }); $(channel).on("closed", function (event, error) { console.log("closed", error); }); $(channel).on("message", function (event, message) { var msg = JSON.parse(message); if (msg.length) handle_data(msg); else handle_meta(msg); }); function close() { channel.close(); } return self; } /* D-Bus proxies */ var STORAGED_SERVICE; var STORAGED_OPATH_PFX; var STORAGED_IFACE_PFX; client.time_offset = undefined; /* Number of milliseconds that the server is ahead of us. */ client.features = undefined; client.storaged_client = undefined; function proxy(iface, path) { return client.storaged_client.proxy(STORAGED_IFACE_PFX + "." + iface, STORAGED_OPATH_PFX + "/" + path, { watch: true }); } function proxies(iface) { /* We create the proxies here with 'watch' set to false and * establish a general watch for all of them. This is more * efficient since it reduces the number of D-Bus calls done * by the cache. */ return client.storaged_client.proxies(STORAGED_IFACE_PFX + "." + iface, STORAGED_OPATH_PFX, { watch: false }); } function init_proxies () { client.storaged_client.watch({ path_namespace: STORAGED_OPATH_PFX }); client.mdraids = proxies("MDRaid"); client.vgroups = proxies("VolumeGroup"); client.lvols = proxies("LogicalVolume"); client.drives = proxies("Drive"); client.drives_ata = proxies("Drive.Ata"); client.blocks = proxies("Block"); client.blocks_ptable = proxies("PartitionTable"); client.blocks_part = proxies("Partition"); client.blocks_lvm2 = proxies("Block.LVM2"); client.blocks_pvol = proxies("PhysicalVolume"); client.blocks_fsys = proxies("Filesystem"); client.blocks_crypto = proxies("Encrypted"); client.iscsi_sessions = proxies("ISCSI.Session"); client.storaged_jobs = proxies("Job"); if (STORAGED_SERVICE != "org.freedesktop.UDisks2") { client.udisks_client = cockpit.dbus("org.freedesktop.UDisks2"); client.udisks_jobs = client.udisks_client.proxies("org.freedesktop.UDisks2.Job", "/org/freedesktop/UDisks2"); } else { client.udisks_client = null; client.udisks_jobs = { }; } } /* Monitors */ client.fsys_sizes = instance_sampler([ { name: "mount.used" }, { name: "mount.total" } ]); client.blockdev_io = instance_sampler([ { name: "block.device.read", derive: "rate" }, { name: "block.device.written", derive: "rate" } ]); /* Derived indices. */ function is_multipath_master(block) { // The master has "mpath" in its device mapper UUID. In the // future, storaged will hopefully provide this information // directly. if (block.Symlinks && block.Symlinks.length) { for (var i = 0; i < block.Symlinks.length; i++) if (utils.decode_filename(block.Symlinks[i]).indexOf("/dev/disk/by-id/dm-uuid-mpath-") === 0) return true; } return false; } function update_indices() { var path, block, dev, mdraid, vgroup, pvol, lvol, part, i; client.broken_multipath_present = false; client.drives_multipath_blocks = { }; client.drives_block = { }; for (path in client.drives) { client.drives_multipath_blocks[path] = [ ]; } for (path in client.blocks) { block = client.blocks[path]; if (!client.blocks_part[path] && client.drives_multipath_blocks[block.Drive] !== undefined) { if (is_multipath_master(block)) client.drives_block[block.Drive] = block; else client.drives_multipath_blocks[block.Drive].push(block); } } for (path in client.drives_multipath_blocks) { /* If there is no multipath master and only a single * member, then this is actually a normal singlepath * device. */ if (!client.drives_block[path] && client.drives_multipath_blocks[path].length == 1) { client.drives_block[path] = client.drives_multipath_blocks[path][0]; client.drives_multipath_blocks[path] = [ ]; } else { client.drives_multipath_blocks[path].sort(utils.block_cmp); if (!client.drives_block[path]) client.broken_multipath_present = true; } } client.mdraids_block = { }; for (path in client.blocks) { block = client.blocks[path]; if (block.MDRaid != "/") client.mdraids_block[block.MDRaid] = block; } client.mdraids_members = { }; for (path in client.mdraids) { client.mdraids_members[path] = [ ]; } for (path in client.blocks) { block = client.blocks[path]; if (client.mdraids_members[block.MDRaidMember] !== undefined) client.mdraids_members[block.MDRaidMember].push(block); } for (path in client.mdraids_members) { client.mdraids_members[path].sort(utils.block_cmp); } client.slashdevs_block = { }; function enter_slashdev(block, enc) { client.slashdevs_block[utils.decode_filename(enc).replace(/^\/dev\//, "")] = block; } for (path in client.blocks) { block = client.blocks[path]; enter_slashdev(block, block.Device); enter_slashdev(block, block.PreferredDevice); for (i = 0; i < block.Symlinks.length; i++) enter_slashdev(block, block.Symlinks[i]); } client.uuids_mdraid = { }; for (path in client.mdraids) { mdraid = client.mdraids[path]; client.uuids_mdraid[mdraid.UUID] = mdraid; } client.vgnames_vgroup = { }; for (path in client.vgroups) { vgroup = client.vgroups[path]; client.vgnames_vgroup[vgroup.Name] = vgroup; } client.vgroups_pvols = { }; for (path in client.vgroups) { client.vgroups_pvols[path] = [ ]; } for (path in client.blocks_pvol) { pvol = client.blocks_pvol[path]; if (client.vgroups_pvols[pvol.VolumeGroup] !== undefined) client.vgroups_pvols[pvol.VolumeGroup].push(pvol); } function cmp_pvols(a, b) { return utils.block_cmp(client.blocks[a.path], client.blocks[b.path]); } for (path in client.vgroups_pvols) { client.vgroups_pvols[path].sort(cmp_pvols); } client.vgroups_lvols = { }; for (path in client.vgroups) { client.vgroups_lvols[path] = [ ]; } for (path in client.lvols) { lvol = client.lvols[path]; if (client.vgroups_lvols[lvol.VolumeGroup] !== undefined) client.vgroups_lvols[lvol.VolumeGroup].push(lvol); } for (path in client.vgroups_lvols) { client.vgroups_lvols[path].sort(function (a, b) { return a.Name.localeCompare(b.Name); }); } client.lvols_block = { }; for (path in client.blocks_lvm2) { client.lvols_block[client.blocks_lvm2[path].LogicalVolume] = client.blocks[path]; } client.lvols_pool_members = { }; for (path in client.lvols) { if (client.lvols[path].Type == "pool") client.lvols_pool_members[path] = [ ]; } for (path in client.lvols) { lvol = client.lvols[path]; if (client.lvols_pool_members[lvol.ThinPool] !== undefined) client.lvols_pool_members[lvol.ThinPool].push(lvol); } for (path in client.lvols_pool_members) { client.lvols_pool_members[path].sort(function (a, b) { return a.Name.localeCompare(b.Name); }); } client.blocks_cleartext = { }; for (path in client.blocks) { block = client.blocks[path]; if (block.CryptoBackingDevice != "/") client.blocks_cleartext[block.CryptoBackingDevice] = block; } client.blocks_partitions = { }; for (path in client.blocks_ptable) { client.blocks_partitions[path] = [ ]; } for (path in client.blocks_part) { part = client.blocks_part[path]; if (client.blocks_partitions[part.Table] !== undefined) client.blocks_partitions[part.Table].push(part); } for (path in client.blocks_partitions) { client.blocks_partitions[path].sort(function (a, b) { return a.Offset - b.Offset; }); } } function init_model(callback) { function wait_all(objects, callback) { var obj = objects.pop(); if (obj) { obj.wait(function () { wait_all(objects, callback); }); } else { callback(); } } function pull_time() { return cockpit.spawn(["date", "+%s"]) .then(function (now) { client.time_offset = parseInt(now)*1000 - new Date().getTime(); }); } function enable_features() { if (!client.manager.valid) return cockpit.resolve(false); if (!client.manager.EnableModules) return cockpit.resolve({ }); return client.manager.EnableModules(true).then( function() { var defer = cockpit.defer(); client.manager_lvm2 = proxy("Manager.LVM2", "Manager"); client.manager_iscsi = proxy("Manager.ISCSI.Initiator", "Manager"); wait_all([ client.manager_lvm2, client.manager_iscsi], function () { var iscsi = (config.with_storaged_iscsi_sessions != "no" && client.manager_iscsi.valid && client.manager_iscsi.SessionsSupported !== false); defer.resolve({ lvm2: client.manager_lvm2.valid, iscsi: iscsi }); }); return defer.promise; }, function(error) { console.warn("Can't enable storaged modules", error.toString()); return cockpit.resolve({ }); }); } wait_all([ client.manager, client.mdraids, client.vgroups, client.drives, client.blocks, client.blocks_ptable, client.blocks_lvm2, client.blocks_fsys ], function () { pull_time().then(function() { enable_features().then(function(features) { client.features = features; callback(); }); $(client.storaged_client).on('notify', function () { update_indices(); $(client).triggerHandler('changed'); }); $(client.udisks_jobs).on('added removed changed', function () { $(client).triggerHandler('changed'); }); update_indices(); }); }); } client.older_than = function older_than(version) { return utils.compare_versions(this.manager.Version, version) < 0; }; function init_manager() { /* Storaged 2.6 and later uses the UDisks2 API names, but try the * older storaged API first as a fallback. */ var storaged_service = "org.storaged.Storaged"; var storaged_opath_pfx = "/org/storaged/Storaged"; var storaged_iface_pfx = "org.storaged.Storaged"; var storaged = cockpit.dbus(storaged_service); var storaged_manager = storaged.proxy(storaged_iface_pfx + ".Manager", storaged_opath_pfx + "/Manager", { watch: true }); function fallback_udisks() { STORAGED_SERVICE = "org.freedesktop.UDisks2"; STORAGED_OPATH_PFX = "/org/freedesktop/UDisks2"; STORAGED_IFACE_PFX = "org.freedesktop.UDisks2"; var udisks = cockpit.dbus(STORAGED_SERVICE); var udisks_manager = udisks.proxy(STORAGED_IFACE_PFX + ".Manager", STORAGED_OPATH_PFX + "/Manager", { watch: true }); return udisks_manager.wait().then(function () { return udisks_manager; }); } return storaged_manager.wait().then(function() { if (storaged_manager.valid) { console.log("Using older 'storaged' API: " + storaged_service); STORAGED_SERVICE = storaged_service; STORAGED_OPATH_PFX = storaged_opath_pfx; STORAGED_IFACE_PFX = storaged_iface_pfx; return storaged_manager; } else { return fallback_udisks(); } }, fallback_udisks); } client.init = function init_storaged(callback) { init_manager().then(function(manager) { client.storaged_client = manager.client; client.manager = manager; // The first storaged version with the UDisks2 API names was 2.6 client.is_old_udisks2 = (STORAGED_SERVICE == "org.freedesktop.UDisks2" && client.older_than("2.6")); if (client.is_old_udisks2) console.log("Using older 'udisks2' implementation: " + manager.Version); init_proxies(); init_model(callback); }, function() { client.features = false; callback(); }); }; module.exports = client; }());
pkg/storaged/client.js
/* * This file is part of Cockpit. * * Copyright (C) 2015 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ (function() { "use strict"; var $ = require('jquery'); var cockpit = require('cockpit'); var utils = require('./utils'); /* STORAGED CLIENT */ /* HACK: https://github.com/storaged-project/storaged/pull/68 */ var config = { }; if (cockpit.manifests["storage"] && cockpit.manifests["storage"]["config"]) config = cockpit.manifests["storage"]["config"]; var client = { }; /* Metrics */ function instance_sampler(metrics) { var instances; var self = { data: { }, close: close }; function handle_meta(msg) { self.data = { }; instances = [ ]; for (var m = 0; m < msg.metrics.length; m++) { instances[m] = msg.metrics[m].instances; for (var i = 0; i < instances[m].length; i++) self.data[instances[m][i]] = [ ]; } } function handle_data(msg) { var changed = false; for (var s = 0; s < msg.length; s++) { var metrics = msg[s]; for (var m = 0; m < metrics.length; m++) { var inst = metrics[m]; for (var i = 0; i < inst.length; i++) { if (inst[i] !== null) { changed = true; self.data[instances[m][i]][m] = inst[i]; } } } } if (changed) $(self).triggerHandler('changed'); } var channel = cockpit.channel({ payload: "metrics1", source: "internal", metrics: metrics }); $(channel).on("closed", function (event, error) { console.log("closed", error); }); $(channel).on("message", function (event, message) { var msg = JSON.parse(message); if (msg.length) handle_data(msg); else handle_meta(msg); }); function close() { channel.close(); } return self; } /* D-Bus proxies */ var STORAGED_SERVICE; var STORAGED_OPATH_PFX; var STORAGED_IFACE_PFX; client.time_offset = undefined; /* Number of milliseconds that the server is ahead of us. */ client.features = undefined; client.storaged_client = undefined; function proxy(iface, path) { return client.storaged_client.proxy(STORAGED_IFACE_PFX + "." + iface, STORAGED_OPATH_PFX + "/" + path, { watch: true }); } function proxies(iface) { /* We create the proxies here with 'watch' set to false and * establish a general watch for all of them. This is more * efficient since it reduces the number of D-Bus calls done * by the cache. */ return client.storaged_client.proxies(STORAGED_IFACE_PFX + "." + iface, STORAGED_OPATH_PFX, { watch: false }); } function init_proxies () { client.storaged_client.watch({ path_namespace: STORAGED_OPATH_PFX }); client.mdraids = proxies("MDRaid"); client.vgroups = proxies("VolumeGroup"); client.lvols = proxies("LogicalVolume"); client.drives = proxies("Drive"); client.drives_ata = proxies("Drive.Ata"); client.blocks = proxies("Block"); client.blocks_ptable = proxies("PartitionTable"); client.blocks_part = proxies("Partition"); client.blocks_lvm2 = proxies("Block.LVM2"); client.blocks_pvol = proxies("PhysicalVolume"); client.blocks_fsys = proxies("Filesystem"); client.blocks_crypto = proxies("Encrypted"); client.iscsi_sessions = proxies("ISCSI.Session"); client.storaged_jobs = proxies("Job"); if (STORAGED_SERVICE != "org.freedesktop.UDisks2") { client.udisks_client = cockpit.dbus("org.freedesktop.UDisks2"); client.udisks_jobs = client.udisks_client.proxies("org.freedesktop.UDisks2.Job", "/org/freedesktop/UDisks2"); } else { client.udisks_client = null; client.udisks_jobs = { }; } } /* Monitors */ client.fsys_sizes = instance_sampler([ { name: "mount.used" }, { name: "mount.total" } ]); client.blockdev_io = instance_sampler([ { name: "block.device.read", derive: "rate" }, { name: "block.device.written", derive: "rate" } ]); /* Derived indices. */ function is_multipath_master(block) { // The master has "mpath" in its device mapper UUID. In the // future, storaged will hopefully provide this information // directly. if (block.Symlinks && block.Symlinks.length) { for (var i = 0; i < block.Symlinks.length; i++) if (utils.decode_filename(block.Symlinks[i]).indexOf("/dev/disk/by-id/dm-uuid-mpath-") === 0) return true; } return false; } function update_indices() { var path, block, dev, mdraid, vgroup, pvol, lvol, part, i; client.broken_multipath_present = false; client.drives_multipath_blocks = { }; client.drives_block = { }; for (path in client.drives) { client.drives_multipath_blocks[path] = [ ]; } for (path in client.blocks) { block = client.blocks[path]; if (!client.blocks_part[path] && client.drives_multipath_blocks[block.Drive] !== undefined) { if (is_multipath_master(block)) client.drives_block[block.Drive] = block; else client.drives_multipath_blocks[block.Drive].push(block); } } for (path in client.drives_multipath_blocks) { /* If there is no multipath master and only a single * member, then this is actually a normal singlepath * device. */ if (!client.drives_block[path] && client.drives_multipath_blocks[path].length == 1) { client.drives_block[path] = client.drives_multipath_blocks[path][0]; client.drives_multipath_blocks[path] = [ ]; } else { client.drives_multipath_blocks[path].sort(utils.block_cmp); if (!client.drives_block[path]) client.broken_multipath_present = true; } } client.mdraids_block = { }; for (path in client.blocks) { block = client.blocks[path]; if (block.MDRaid != "/") client.mdraids_block[block.MDRaid] = block; } client.mdraids_members = { }; for (path in client.mdraids) { client.mdraids_members[path] = [ ]; } for (path in client.blocks) { block = client.blocks[path]; if (client.mdraids_members[block.MDRaidMember] !== undefined) client.mdraids_members[block.MDRaidMember].push(block); } for (path in client.mdraids_members) { client.mdraids_members[path].sort(utils.block_cmp); } client.slashdevs_block = { }; function enter_slashdev(block, enc) { client.slashdevs_block[utils.decode_filename(enc).replace(/^\/dev\//, "")] = block; } for (path in client.blocks) { block = client.blocks[path]; enter_slashdev(block, block.Device); enter_slashdev(block, block.PreferredDevice); for (i = 0; i < block.Symlinks.length; i++) enter_slashdev(block, block.Symlinks[i]); } client.uuids_mdraid = { }; for (path in client.mdraids) { mdraid = client.mdraids[path]; client.uuids_mdraid[mdraid.UUID] = mdraid; } client.vgnames_vgroup = { }; for (path in client.vgroups) { vgroup = client.vgroups[path]; client.vgnames_vgroup[vgroup.Name] = vgroup; } client.vgroups_pvols = { }; for (path in client.vgroups) { client.vgroups_pvols[path] = [ ]; } for (path in client.blocks_pvol) { pvol = client.blocks_pvol[path]; if (client.vgroups_pvols[pvol.VolumeGroup] !== undefined) client.vgroups_pvols[pvol.VolumeGroup].push(pvol); } function cmp_pvols(a, b) { return utils.block_cmp(client.blocks[a.path], client.blocks[b.path]); } for (path in client.vgroups_pvols) { client.vgroups_pvols[path].sort(cmp_pvols); } client.vgroups_lvols = { }; for (path in client.vgroups) { client.vgroups_lvols[path] = [ ]; } for (path in client.lvols) { lvol = client.lvols[path]; if (client.vgroups_lvols[lvol.VolumeGroup] !== undefined) client.vgroups_lvols[lvol.VolumeGroup].push(lvol); } for (path in client.vgroups_lvols) { client.vgroups_lvols[path].sort(function (a, b) { return a.Name.localeCompare(b.Name); }); } client.lvols_block = { }; for (path in client.blocks_lvm2) { client.lvols_block[client.blocks_lvm2[path].LogicalVolume] = client.blocks[path]; } client.lvols_pool_members = { }; for (path in client.lvols) { if (client.lvols[path].Type == "pool") client.lvols_pool_members[path] = [ ]; } for (path in client.lvols) { lvol = client.lvols[path]; if (client.lvols_pool_members[lvol.ThinPool] !== undefined) client.lvols_pool_members[lvol.ThinPool].push(lvol); } for (path in client.lvols_pool_members) { client.lvols_pool_members[path].sort(function (a, b) { return a.Name.localeCompare(b.Name); }); } client.blocks_cleartext = { }; for (path in client.blocks) { block = client.blocks[path]; if (block.CryptoBackingDevice != "/") client.blocks_cleartext[block.CryptoBackingDevice] = block; } client.blocks_partitions = { }; for (path in client.blocks_ptable) { client.blocks_partitions[path] = [ ]; } for (path in client.blocks_part) { part = client.blocks_part[path]; if (client.blocks_partitions[part.Table] !== undefined) client.blocks_partitions[part.Table].push(part); } for (path in client.blocks_partitions) { client.blocks_partitions[path].sort(function (a, b) { return a.Offset - b.Offset; }); } } function init_model(callback) { function wait_all(objects, callback) { var obj = objects.pop(); if (obj) { obj.wait(function () { wait_all(objects, callback); }); } else callback(); } wait_all([ client.manager, client.mdraids, client.vgroups, client.drives, client.blocks, client.blocks_ptable, client.blocks_lvm2, client.blocks_fsys ], function () { if (!client.manager.valid) { client.features = false; callback(); } else { cockpit.spawn(["date", "+%s"]) .done(function (now) { client.time_offset = parseInt(now)*1000 - new Date().getTime(); }) .always(function () { client.manager.EnableModules(true) .always(function () { client.manager_lvm2 = proxy("Manager.LVM2", "Manager"); client.manager_iscsi = proxy("Manager.ISCSI.Initiator", "Manager"); wait_all([ client.manager_lvm2, client.manager_iscsi], function () { var iscsi = (config.with_storaged_iscsi_sessions != "no" && client.manager_iscsi.valid && client.manager_iscsi.SessionsSupported !== false); client.features = { lvm2: client.manager_lvm2.valid, iscsi: iscsi }; callback(); }); }) .fail(function (error) { console.warn("Can't enable storaged modules", error.toString()); }); $(client.storaged_client).on('notify', function () { update_indices(); $(client).triggerHandler('changed'); }); $(client.udisks_jobs).on('added removed changed', function () { $(client).triggerHandler('changed'); }); update_indices(); }); } }); } function init_storaged(callback) { /* Storaged 2.6 and later uses the UDisks2 API names, so we * try them first. */ STORAGED_SERVICE = "org.freedesktop.UDisks2"; STORAGED_OPATH_PFX = "/org/freedesktop/UDisks2"; STORAGED_IFACE_PFX = "org.freedesktop.UDisks2"; client.storaged_client = cockpit.dbus(STORAGED_SERVICE); client.manager = proxy("Manager", "Manager"); client.manager.wait(function () { if (!client.manager.valid || client.manager.EnableModules === undefined) { STORAGED_SERVICE = "org.storaged.Storaged"; STORAGED_OPATH_PFX = "/org/storaged/Storaged"; STORAGED_IFACE_PFX = "org.storaged.Storaged"; client.storaged_client = cockpit.dbus(STORAGED_SERVICE); client.manager = proxy("Manager", "Manager"); } init_proxies(); init_model(callback); }); } client.init = init_storaged; module.exports = client; }());
storaged: Fall back to UDisks2 if Storaged isn't available Reviewed-by: Stef Walter <[email protected]>
pkg/storaged/client.js
storaged: Fall back to UDisks2 if Storaged isn't available
<ide><path>kg/storaged/client.js <ide> obj.wait(function () { <ide> wait_all(objects, callback); <ide> }); <del> } else <add> } else { <ide> callback(); <add> } <add> } <add> <add> function pull_time() { <add> return cockpit.spawn(["date", "+%s"]) <add> .then(function (now) { <add> client.time_offset = parseInt(now)*1000 - new Date().getTime(); <add> }); <add> } <add> <add> function enable_features() { <add> if (!client.manager.valid) <add> return cockpit.resolve(false); <add> if (!client.manager.EnableModules) <add> return cockpit.resolve({ }); <add> return client.manager.EnableModules(true).then( <add> function() { <add> var defer = cockpit.defer(); <add> client.manager_lvm2 = proxy("Manager.LVM2", "Manager"); <add> client.manager_iscsi = proxy("Manager.ISCSI.Initiator", "Manager"); <add> wait_all([ client.manager_lvm2, client.manager_iscsi], <add> function () { <add> var iscsi = (config.with_storaged_iscsi_sessions != "no" && <add> client.manager_iscsi.valid && <add> client.manager_iscsi.SessionsSupported !== false); <add> defer.resolve({ lvm2: client.manager_lvm2.valid, iscsi: iscsi }); <add> }); <add> return defer.promise; <add> }, function(error) { <add> console.warn("Can't enable storaged modules", error.toString()); <add> return cockpit.resolve({ }); <add> }); <ide> } <ide> <ide> wait_all([ client.manager, <ide> client.mdraids, client.vgroups, client.drives, <ide> client.blocks, client.blocks_ptable, client.blocks_lvm2, client.blocks_fsys <del> ], <del> function () { <del> if (!client.manager.valid) { <del> client.features = false; <del> callback(); <del> } else { <del> cockpit.spawn(["date", "+%s"]) <del> .done(function (now) { <del> client.time_offset = parseInt(now)*1000 - new Date().getTime(); <del> }) <del> .always(function () { <del> client.manager.EnableModules(true) <del> .always(function () { <del> client.manager_lvm2 = proxy("Manager.LVM2", "Manager"); <del> client.manager_iscsi = proxy("Manager.ISCSI.Initiator", "Manager"); <del> wait_all([ client.manager_lvm2, client.manager_iscsi], <del> function () { <del> var iscsi = (config.with_storaged_iscsi_sessions != "no" && <del> client.manager_iscsi.valid && <del> client.manager_iscsi.SessionsSupported !== false); <del> client.features = { lvm2: client.manager_lvm2.valid, <del> iscsi: iscsi <del> }; <del> callback(); <del> }); <del> }) <del> .fail(function (error) { <del> console.warn("Can't enable storaged modules", error.toString()); <del> }); <del> $(client.storaged_client).on('notify', function () { <del> update_indices(); <del> $(client).triggerHandler('changed'); <del> }); <del> $(client.udisks_jobs).on('added removed changed', function () { <del> $(client).triggerHandler('changed'); <del> }); <del> update_indices(); <del> }); <del> } <del> }); <del> } <del> <del> function init_storaged(callback) { <del> /* Storaged 2.6 and later uses the UDisks2 API names, so we <del> * try them first. <add> ], function () { <add> pull_time().then(function() { <add> enable_features().then(function(features) { <add> client.features = features; <add> callback(); <add> }); <add> <add> $(client.storaged_client).on('notify', function () { <add> update_indices(); <add> $(client).triggerHandler('changed'); <add> }); <add> $(client.udisks_jobs).on('added removed changed', function () { <add> $(client).triggerHandler('changed'); <add> }); <add> update_indices(); <add> }); <add> }); <add> } <add> <add> client.older_than = function older_than(version) { <add> return utils.compare_versions(this.manager.Version, version) < 0; <add> }; <add> <add> function init_manager() { <add> /* Storaged 2.6 and later uses the UDisks2 API names, but try the <add> * older storaged API first as a fallback. <ide> */ <ide> <del> STORAGED_SERVICE = "org.freedesktop.UDisks2"; <del> STORAGED_OPATH_PFX = "/org/freedesktop/UDisks2"; <del> STORAGED_IFACE_PFX = "org.freedesktop.UDisks2"; <del> <del> client.storaged_client = cockpit.dbus(STORAGED_SERVICE); <del> client.manager = proxy("Manager", "Manager"); <del> <del> client.manager.wait(function () { <del> if (!client.manager.valid || client.manager.EnableModules === undefined) { <del> STORAGED_SERVICE = "org.storaged.Storaged"; <del> STORAGED_OPATH_PFX = "/org/storaged/Storaged"; <del> STORAGED_IFACE_PFX = "org.storaged.Storaged"; <del> <del> client.storaged_client = cockpit.dbus(STORAGED_SERVICE); <del> client.manager = proxy("Manager", "Manager"); <del> } <add> var storaged_service = "org.storaged.Storaged"; <add> var storaged_opath_pfx = "/org/storaged/Storaged"; <add> var storaged_iface_pfx = "org.storaged.Storaged"; <add> <add> var storaged = cockpit.dbus(storaged_service); <add> var storaged_manager = storaged.proxy(storaged_iface_pfx + ".Manager", <add> storaged_opath_pfx + "/Manager", { watch: true }); <add> <add> function fallback_udisks() { <add> STORAGED_SERVICE = "org.freedesktop.UDisks2"; <add> STORAGED_OPATH_PFX = "/org/freedesktop/UDisks2"; <add> STORAGED_IFACE_PFX = "org.freedesktop.UDisks2"; <add> <add> var udisks = cockpit.dbus(STORAGED_SERVICE); <add> var udisks_manager = udisks.proxy(STORAGED_IFACE_PFX + ".Manager", <add> STORAGED_OPATH_PFX + "/Manager", { watch: true }); <add> <add> return udisks_manager.wait().then(function () { <add> return udisks_manager; <add> }); <add> } <add> <add> return storaged_manager.wait().then(function() { <add> if (storaged_manager.valid) { <add> console.log("Using older 'storaged' API: " + storaged_service); <add> STORAGED_SERVICE = storaged_service; <add> STORAGED_OPATH_PFX = storaged_opath_pfx; <add> STORAGED_IFACE_PFX = storaged_iface_pfx; <add> return storaged_manager; <add> } else { <add> return fallback_udisks(); <add> } <add> }, fallback_udisks); <add> } <add> <add> client.init = function init_storaged(callback) { <add> init_manager().then(function(manager) { <add> client.storaged_client = manager.client; <add> client.manager = manager; <add> <add> // The first storaged version with the UDisks2 API names was 2.6 <add> client.is_old_udisks2 = (STORAGED_SERVICE == "org.freedesktop.UDisks2" && client.older_than("2.6")); <add> if (client.is_old_udisks2) <add> console.log("Using older 'udisks2' implementation: " + manager.Version); <ide> <ide> init_proxies(); <ide> init_model(callback); <add> }, function() { <add> client.features = false; <add> callback(); <ide> }); <del> } <del> <del> client.init = init_storaged; <add> }; <ide> <ide> module.exports = client; <ide> }());
Java
apache-2.0
38d5882f89172a6cf1af94e6ee0ec63b3efdfb28
0
robovm/robovm-studio,ibinti/intellij-community,jexp/idea2,signed/intellij-community,kool79/intellij-community,dslomov/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,signed/intellij-community,samthor/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,da1z/intellij-community,ernestp/consulo,suncycheng/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,da1z/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,supersven/intellij-community,asedunov/intellij-community,consulo/consulo,dslomov/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,ryano144/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ibinti/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,caot/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,retomerz/intellij-community,caot/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,blademainer/intellij-community,hurricup/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,vvv1559/intellij-community,samthor/intellij-community,kool79/intellij-community,joewalnes/idea-community,adedayo/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,fitermay/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,izonder/intellij-community,da1z/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,samthor/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,robovm/robovm-studio,xfournet/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,jexp/idea2,kool79/intellij-community,slisson/intellij-community,retomerz/intellij-community,fnouama/intellij-community,supersven/intellij-community,asedunov/intellij-community,ibinti/intellij-community,jexp/idea2,semonte/intellij-community,retomerz/intellij-community,petteyg/intellij-community,allotria/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,caot/intellij-community,da1z/intellij-community,FHannes/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,vladmm/intellij-community,holmes/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,holmes/intellij-community,retomerz/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,caot/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,vladmm/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,youdonghai/intellij-community,slisson/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,signed/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,adedayo/intellij-community,caot/intellij-community,holmes/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,allotria/intellij-community,apixandru/intellij-community,robovm/robovm-studio,jagguli/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,caot/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,FHannes/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,amith01994/intellij-community,slisson/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ernestp/consulo,slisson/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,semonte/intellij-community,vladmm/intellij-community,signed/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,caot/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,caot/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ibinti/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,diorcety/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,slisson/intellij-community,retomerz/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ernestp/consulo,adedayo/intellij-community,wreckJ/intellij-community,consulo/consulo,ernestp/consulo,clumsy/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,xfournet/intellij-community,samthor/intellij-community,consulo/consulo,gnuhub/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,samthor/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,holmes/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,consulo/consulo,jexp/idea2,gnuhub/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,petteyg/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,holmes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,asedunov/intellij-community,allotria/intellij-community,diorcety/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ahb0327/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,FHannes/intellij-community,holmes/intellij-community,consulo/consulo,kool79/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,samthor/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,samthor/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,da1z/intellij-community,izonder/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,samthor/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,allotria/intellij-community,fnouama/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,allotria/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,kool79/intellij-community,signed/intellij-community,jexp/idea2,clumsy/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,holmes/intellij-community,petteyg/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,supersven/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,izonder/intellij-community,supersven/intellij-community,supersven/intellij-community,amith01994/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,kdwink/intellij-community,asedunov/intellij-community,izonder/intellij-community,ernestp/consulo,fnouama/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,signed/intellij-community,kdwink/intellij-community,jexp/idea2,samthor/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,kool79/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,semonte/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,dslomov/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,signed/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,caot/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,diorcety/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,slisson/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,slisson/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,kool79/intellij-community,joewalnes/idea-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,allotria/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,izonder/intellij-community,semonte/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,petteyg/intellij-community,caot/intellij-community,apixandru/intellij-community,holmes/intellij-community,semonte/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,ol-loginov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,caot/intellij-community,robovm/robovm-studio,holmes/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,fnouama/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,jagguli/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ernestp/consulo,petteyg/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,semonte/intellij-community,hurricup/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,robovm/robovm-studio,clumsy/intellij-community,fitermay/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,blademainer/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,izonder/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,allotria/intellij-community,diorcety/intellij-community,petteyg/intellij-community,consulo/consulo,TangHao1987/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,kool79/intellij-community,joewalnes/idea-community,retomerz/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,FHannes/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,da1z/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,supersven/intellij-community,amith01994/intellij-community,dslomov/intellij-community,xfournet/intellij-community,FHannes/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,signed/intellij-community,gnuhub/intellij-community,signed/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,izonder/intellij-community,Distrotech/intellij-community,signed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,Lekanich/intellij-community
package com.intellij.lang.ant.config.execution; import com.intellij.concurrency.JobScheduler; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.CommandLineBuilder; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.junit.JUnitProcessHandler; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.util.ExecutionErrorDialog; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryConfiguration; import com.intellij.ide.macro.Macro; import com.intellij.lang.ant.AntBundle; import com.intellij.lang.ant.config.AntBuildFile; import com.intellij.lang.ant.config.AntBuildFileBase; import com.intellij.lang.ant.config.AntBuildListener; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.Date; import java.util.concurrent.TimeUnit; public final class ExecutionHandler { private static final Logger LOG = Logger.getInstance("#com.intellij.ant.execution.ExecutionHandler"); @NonNls public static final String PARSER_JAR = "xerces1.jar"; private ExecutionHandler() { } /** * @param antBuildListener should not be null. Use {@link AntBuildListener#NULL} */ public static void runBuild(final AntBuildFileBase buildFile, String[] targets, final AntBuildMessageView buildMessageViewToReuse, final DataContext dataContext, final AntBuildListener antBuildListener) { FileDocumentManager.getInstance().saveAllDocuments(); LOG.assertTrue(antBuildListener != null); final AntCommandLineBuilder builder = new AntCommandLineBuilder(); final AntBuildMessageView messageView; final GeneralCommandLine commandLine; synchronized (builder) { Project project = buildFile.getProject(); try { builder.setBuildFile(buildFile.getAllOptions(), VfsUtil.virtualToIoFile(buildFile.getVirtualFile())); builder.calculateProperties(dataContext); builder.addTargets(targets); messageView = prepareMessageView(buildMessageViewToReuse, buildFile, targets); commandLine = CommandLineBuilder.createFromJavaParameters(builder.getCommandLine()); messageView.setBuildCommandLine(commandLine.getCommandLineString()); } catch (RunCanceledException e) { e.showMessage(project, AntBundle.message("run.ant.erorr.dialog.title")); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return; } catch (CantRunException e) { ExecutionErrorDialog.show(e, AntBundle.message("cant.run.ant.erorr.dialog.title"), project); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return; } catch (Macro.ExecutionCancelledException e) { antBuildListener.buildFinished(AntBuildListener.ABORTED, 0); return; } catch (Throwable e) { antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); LOG.error(e); return; } } final boolean startInBackground = buildFile.isRunInBackground(); new Task.Backgroundable(null, AntBundle.message("ant.build.progress.dialog.title"), true) { public boolean shouldStartInBackground() { return startInBackground; } public void run(@NotNull final ProgressIndicator indicator) { try { runBuild(indicator, messageView, buildFile, antBuildListener, commandLine); } catch (Throwable e) { LOG.error(e); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); } } }.queue(); } private static void runBuild(final ProgressIndicator progress, final AntBuildMessageView errorView, final AntBuildFile buildFile, final AntBuildListener antBuildListener, GeneralCommandLine commandLine) { LOG.assertTrue(antBuildListener != null); LOG.assertTrue(errorView != null); LOG.assertTrue(commandLine != null); LOG.assertTrue(buildFile != null); final Project project = buildFile.getProject(); final long startTime = new Date().getTime(); JUnitProcessHandler handler; if (LocalHistoryConfiguration.getInstance().ADD_LABEL_ON_RUNNING) { LocalHistory.putSystemLabel(project, AntBundle.message("ant.build.local.history.label", buildFile.getName())); } try { handler = JUnitProcessHandler.runCommandLine(commandLine); } catch (final ExecutionException e) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ExecutionErrorDialog.show(e, AntBundle.message("could.not.start.process.erorr.dialog.title"), project); } }); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return; } processRunningAnt(progress, handler, errorView, buildFile, startTime, antBuildListener); handler.waitFor(); } private static void processRunningAnt(final ProgressIndicator progress, JUnitProcessHandler handler, final AntBuildMessageView errorView, final AntBuildFile buildFile, final long startTime, final AntBuildListener antBuildListener) { final Project project = buildFile.getProject(); WindowManager.getInstance().getStatusBar(project).setInfo(AntBundle.message("ant.build.started.status.message")); final CheckCancelTask checkCancelTask = new CheckCancelTask(progress, handler); checkCancelTask.start(0); final OutputParser parser = OutputParser2.attachParser(project, handler, errorView, progress, buildFile); handler.addProcessListener(new ProcessAdapter() { public void processTerminated(ProcessEvent event) { checkCancelTask.cancel(); parser.setStopped(true); errorView.stopScrollerThread(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (project.isDisposed()) return; errorView.removeProgressPanel(); ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW); if (toolWindow != null) { // can be null if project is closed toolWindow.activate(null, false); long buildTime = new Date().getTime() - startTime; errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener); } } }, ModalityState.NON_MODAL); } }); handler.startNotify(); errorView.startScrollerThread(); } static final class CheckCancelTask implements Runnable { private final ProgressIndicator myProgressIndicator; private final OSProcessHandler myProcessHandler; private volatile boolean myCanceled; public CheckCancelTask(ProgressIndicator progressIndicator, OSProcessHandler process) { myProgressIndicator = progressIndicator; myProcessHandler = process; } public void cancel() { myCanceled = true; } public void run() { if (!myCanceled) { try { myProgressIndicator.checkCanceled(); start(50); } catch (ProcessCanceledException e) { myProcessHandler.destroyProcess(); } } } public void start(final long delay) { JobScheduler.getScheduler().schedule(this, delay, TimeUnit.MILLISECONDS); } } private static AntBuildMessageView prepareMessageView(AntBuildMessageView buildMessageViewToReuse, AntBuildFileBase buildFile, String[] targets) throws RunCanceledException { AntBuildMessageView messageView; if (buildMessageViewToReuse != null) { messageView = buildMessageViewToReuse; messageView.emptyAll(); } else { messageView = AntBuildMessageView.openBuildMessageView(buildFile.getProject(), buildFile, targets); if (messageView == null) { throw new RunCanceledException(AntBundle.message("canceled.by.user.error.message")); } } return messageView; } }
plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java
package com.intellij.lang.ant.config.execution; import com.intellij.concurrency.JobScheduler; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.CommandLineBuilder; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.junit.JUnitProcessHandler; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.util.ExecutionErrorDialog; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryConfiguration; import com.intellij.ide.macro.Macro; import com.intellij.lang.ant.AntBundle; import com.intellij.lang.ant.config.AntBuildFile; import com.intellij.lang.ant.config.AntBuildFileBase; import com.intellij.lang.ant.config.AntBuildListener; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.Date; import java.util.concurrent.TimeUnit; public final class ExecutionHandler { private static final Logger LOG = Logger.getInstance("#com.intellij.ant.execution.ExecutionHandler"); @NonNls public static final String PARSER_JAR = "xerces1.jar"; private ExecutionHandler() { } /** * @param antBuildListener should not be null. Use {@link AntBuildListener#NULL} */ public static void runBuild(final AntBuildFileBase buildFile, String[] targets, final AntBuildMessageView buildMessageViewToReuse, final DataContext dataContext, final AntBuildListener antBuildListener) { FileDocumentManager.getInstance().saveAllDocuments(); LOG.assertTrue(antBuildListener != null); final AntCommandLineBuilder builder = new AntCommandLineBuilder(); final AntBuildMessageView messageView; final GeneralCommandLine commandLine; synchronized (builder) { Project project = buildFile.getProject(); try { builder.setBuildFile(buildFile.getAllOptions(), VfsUtil.virtualToIoFile(buildFile.getVirtualFile())); builder.calculateProperties(dataContext); builder.addTargets(targets); messageView = prepareMessageView(buildMessageViewToReuse, buildFile, targets); commandLine = CommandLineBuilder.createFromJavaParameters(builder.getCommandLine()); messageView.setBuildCommandLine(commandLine.getCommandLineString()); } catch (RunCanceledException e) { e.showMessage(project, AntBundle.message("run.ant.erorr.dialog.title")); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return; } catch (CantRunException e) { ExecutionErrorDialog.show(e, AntBundle.message("cant.run.ant.erorr.dialog.title"), project); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return; } catch (Macro.ExecutionCancelledException e) { antBuildListener.buildFinished(AntBuildListener.ABORTED, 0); return; } catch (Throwable e) { antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); LOG.error(e); return; } } final boolean startInBackground = buildFile.isRunInBackground(); new Task.Backgroundable(null, AntBundle.message("ant.build.progress.dialog.title"), true) { public boolean shouldStartInBackground() { return startInBackground; } public void run(@NotNull final ProgressIndicator indicator) { try { runBuild(indicator, messageView, buildFile, antBuildListener, commandLine); } catch (Throwable e) { LOG.error(e); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); } } }.queue(); } private static void runBuild(final ProgressIndicator progress, final AntBuildMessageView errorView, final AntBuildFile buildFile, final AntBuildListener antBuildListener, GeneralCommandLine commandLine) { LOG.assertTrue(antBuildListener != null); LOG.assertTrue(errorView != null); LOG.assertTrue(commandLine != null); LOG.assertTrue(buildFile != null); final Project project = buildFile.getProject(); final long startTime = new Date().getTime(); JUnitProcessHandler handler; if (LocalHistoryConfiguration.getInstance().ADD_LABEL_ON_RUNNING) { LocalHistory.putSystemLabel(project, AntBundle.message("ant.build.local.history.label", buildFile.getName())); } try { handler = JUnitProcessHandler.runCommandLine(commandLine); } catch (final ExecutionException e) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ExecutionErrorDialog.show(e, AntBundle.message("could.not.start.process.erorr.dialog.title"), project); } }); antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0); return; } processRunningAnt(progress, handler, errorView, buildFile, startTime, antBuildListener); handler.waitFor(); } private static void processRunningAnt(final ProgressIndicator progress, JUnitProcessHandler handler, final AntBuildMessageView errorView, final AntBuildFile buildFile, final long startTime, final AntBuildListener antBuildListener) { final Project project = buildFile.getProject(); WindowManager.getInstance().getStatusBar(project).setInfo(AntBundle.message("ant.build.started.status.message")); final CheckCancelTask checkCancelTask = new CheckCancelTask(progress, handler); checkCancelTask.start(0); final OutputParser parser = OutputParser2.attachParser(project, handler, errorView, progress, buildFile); handler.addProcessListener(new ProcessAdapter() { public void processTerminated(ProcessEvent event) { checkCancelTask.cancel(); parser.setStopped(true); errorView.stopScrollerThread(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (project.isDisposed()) return; errorView.removeProgressPanel(); ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW); if (toolWindow != null) { // can be null if project is closed toolWindow.activate(null); long buildTime = new Date().getTime() - startTime; errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener); } } }, ModalityState.NON_MODAL); } }); handler.startNotify(); errorView.startScrollerThread(); } static final class CheckCancelTask implements Runnable { private final ProgressIndicator myProgressIndicator; private final OSProcessHandler myProcessHandler; private volatile boolean myCanceled; public CheckCancelTask(ProgressIndicator progressIndicator, OSProcessHandler process) { myProgressIndicator = progressIndicator; myProcessHandler = process; } public void cancel() { myCanceled = true; } public void run() { if (!myCanceled) { try { myProgressIndicator.checkCanceled(); start(50); } catch (ProcessCanceledException e) { myProcessHandler.destroyProcess(); } } } public void start(final long delay) { JobScheduler.getScheduler().schedule(this, delay, TimeUnit.MILLISECONDS); } } private static AntBuildMessageView prepareMessageView(AntBuildMessageView buildMessageViewToReuse, AntBuildFileBase buildFile, String[] targets) throws RunCanceledException { AntBuildMessageView messageView; if (buildMessageViewToReuse != null) { messageView = buildMessageViewToReuse; messageView.emptyAll(); } else { messageView = AntBuildMessageView.openBuildMessageView(buildFile.getProject(), buildFile, targets); if (messageView == null) { throw new RunCanceledException(AntBundle.message("canceled.by.user.error.message")); } } return messageView; } }
IDEADEV-12818: don't grab focus to ant messages upon build completion
plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java
IDEADEV-12818: don't grab focus to ant messages upon build completion
<ide><path>lugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java <ide> errorView.removeProgressPanel(); <ide> ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW); <ide> if (toolWindow != null) { // can be null if project is closed <del> toolWindow.activate(null); <add> toolWindow.activate(null, false); <ide> long buildTime = new Date().getTime() - startTime; <ide> errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener); <ide> }
Java
mit
f87fb42bbe19edda4c9853de79f7599a624215ff
0
agilemobiledev/trackr-backend,hongyang070/trackr-backend,ashwinrayaprolu1984/trackr-backend,techdev-solutions/trackr-backend,ashwinrayaprolu1984/trackr-backend,agilemobiledev/trackr-backend,hongyang070/trackr-backend,techdev-solutions/trackr-backend
package de.techdev.trackr.domain.employee; import de.techdev.trackr.domain.employee.login.Credential; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.core.RepositoryConstraintViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * A controller for special operations on Employees not exportable by spring-data-rest * * @author Moritz Schulze */ @Controller @RequestMapping(value = "/employees") public class EmployeeController { @Autowired private EmployeeRepository employeeRepository; /** * This method allows an employee to change some values of his entity on his own, namely the one * in SelfEmployee. * * @param employeeId The id of the employee. Only if the principal has the same id access is allowed. * @param selfEmployee The request body, i.e. the data to change * @return The updated data. */ @PreAuthorize("isAuthenticated() and #employeeId == principal.id") @ResponseBody @RequestMapping(value = "/{employee}/self", method = {RequestMethod.PUT, RequestMethod.PATCH}, consumes = MediaType.APPLICATION_JSON_VALUE) public SelfEmployee updateSelf(@PathVariable("employee") Long employeeId, @RequestBody SelfEmployee selfEmployee) { Employee employee = employeeRepository.findOne(employeeId); //Since patch is allowed all fields can be null and shouldn't be overwritten in that case. if (selfEmployee.getFirstName() != null) { employee.setFirstName(selfEmployee.getFirstName()); } if (selfEmployee.getLastName() != null) { employee.setLastName(selfEmployee.getLastName()); } if (selfEmployee.getPhoneNumber() != null) { employee.setPhoneNumber(selfEmployee.getPhoneNumber()); } employeeRepository.save(employee); return SelfEmployee.valueOf(employee); } @RequestMapping(value = "/{employee}/self", method = {RequestMethod.GET}) @ResponseBody public SelfEmployee get(@PathVariable("employee") Long employeeId) { Employee employee = employeeRepository.findOne(employeeId); return SelfEmployee.valueOf(employee); } /** * Create a new employee along with his/her credentials. Used so binding errors for both entities are displayed at the same time. * @param createEmployee Wrapper for an employee and a credential entity. * @param bindingResult Spring binding result. * @return The newly created employee */ @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/createWithCredential", method = {RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @ResponseStatus(HttpStatus.CREATED) public Employee createWithCredential(@RequestBody @Valid CreateEmployee createEmployee, BindingResult bindingResult) { if(bindingResult.hasErrors()) { throw new RepositoryConstraintViolationException(bindingResult); } createEmployee.getEmployee().setCredential(createEmployee.getCredential()); createEmployee.getCredential().setEmployee(createEmployee.getEmployee()); return employeeRepository.save(createEmployee.getEmployee()); } /** * Wrapper DTO for an employee and a credential. * <p> * This class <b>must</b> be static, otherwise the binding errors will not work correctly. */ @Data protected static class CreateEmployee { @Valid private Employee employee; @Valid private Credential credential; } }
src/main/java/de/techdev/trackr/domain/employee/EmployeeController.java
package de.techdev.trackr.domain.employee; import de.techdev.trackr.domain.employee.login.Credential; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.core.RepositoryConstraintViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * A controller for special operations on Employees not exportable by spring-data-rest * * @author Moritz Schulze */ @Controller @RequestMapping(value = "/employees") public class EmployeeController { @Autowired private EmployeeRepository employeeRepository; /** * This method allows an employee to change some values of his entity on his own, namely the one * in SelfEmployee. * * @param employeeId The id of the employee. Only if the principal has the same id access is allowed. * @param selfEmployee The request body, i.e. the data to change * @return The updated data. */ @PreAuthorize("isAuthenticated() and #employeeId == principal.id") @ResponseBody @RequestMapping(value = "/{employee}/self", method = {RequestMethod.PUT, RequestMethod.PATCH}, consumes = MediaType.APPLICATION_JSON_VALUE) public SelfEmployee updateSelf(@PathVariable("employee") Long employeeId, @RequestBody SelfEmployee selfEmployee) { Employee employee = employeeRepository.findOne(employeeId); //Since patch is allowed all fields can be null and shouldn't be overwritten in that case. if (selfEmployee.getFirstName() != null) { employee.setFirstName(selfEmployee.getFirstName()); } if (selfEmployee.getLastName() != null) { employee.setLastName(selfEmployee.getLastName()); } if (selfEmployee.getPhoneNumber() != null) { employee.setPhoneNumber(selfEmployee.getPhoneNumber()); } employeeRepository.save(employee); return SelfEmployee.valueOf(employee); } @RequestMapping(value = "/{employee}/self", method = {RequestMethod.GET}) @ResponseBody public SelfEmployee get(@PathVariable("employee") Long employeeId) { Employee employee = employeeRepository.findOne(employeeId); return SelfEmployee.valueOf(employee); } /** * Create a new employee along with his/her credentials. Used so binding errors for both entities are displayed at the same time. * @param createEmployee Wrapper for an employee and a credential entity. * @param bindingResult Spring binding result. * @return The newly created employee * @throws BindException If the bindingResult had errors. */ @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/createWithCredential", method = {RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @ResponseStatus(HttpStatus.CREATED) public Employee createWithCredential(@RequestBody @Valid CreateEmployee createEmployee, BindingResult bindingResult) { if(bindingResult.hasErrors()) { throw new RepositoryConstraintViolationException(bindingResult); } createEmployee.getEmployee().setCredential(createEmployee.getCredential()); createEmployee.getCredential().setEmployee(createEmployee.getEmployee()); return employeeRepository.save(createEmployee.getEmployee()); } /** * Wrapper DTO for an employee and a credential. * <p> * This class <b>must</b> be static, otherwise the binding errors will not work correctly. */ @Data protected static class CreateEmployee { @Valid private Employee employee; @Valid private Credential credential; } }
TRACKR-91 - New employees are not creatable Added default locale to employee creation.
src/main/java/de/techdev/trackr/domain/employee/EmployeeController.java
TRACKR-91 - New employees are not creatable Added default locale to employee creation.
<ide><path>rc/main/java/de/techdev/trackr/domain/employee/EmployeeController.java <ide> * @param createEmployee Wrapper for an employee and a credential entity. <ide> * @param bindingResult Spring binding result. <ide> * @return The newly created employee <del> * @throws BindException If the bindingResult had errors. <ide> */ <ide> @PreAuthorize("hasRole('ROLE_ADMIN')") <ide> @RequestMapping(value = "/createWithCredential", method = {RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
Java
agpl-3.0
eb41a2ee1088b766e520259f68492ee3fa6a2138
0
kuali/kc,iu-uits-es/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,jwillia/kc-old1,geothomasp/kcmit,iu-uits-es/kc,mukadder/kc,UniversityOfHawaiiORS/kc,kuali/kc,mukadder/kc,ColostateResearchServices/kc,ColostateResearchServices/kc,kuali/kc,geothomasp/kcmit,jwillia/kc-old1,jwillia/kc-old1,jwillia/kc-old1,iu-uits-es/kc,geothomasp/kcmit,UniversityOfHawaiiORS/kc,geothomasp/kcmit,ColostateResearchServices/kc,mukadder/kc
/* * Copyright 2006-2008 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.proposaldevelopment.hierarchy.service.impl; import static org.apache.commons.lang.StringUtils.replace; import static org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyKeyConstants.*; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.kra.budget.BudgetDecimal; import org.kuali.kra.budget.calculator.BudgetCalculationService; import org.kuali.kra.budget.core.Budget; import org.kuali.kra.budget.core.BudgetAssociate; import org.kuali.kra.budget.core.BudgetService; import org.kuali.kra.budget.core.CostElement; import org.kuali.kra.budget.document.BudgetDocument; import org.kuali.kra.budget.nonpersonnel.BudgetLineItem; import org.kuali.kra.budget.parameters.BudgetPeriod; import org.kuali.kra.budget.personnel.BudgetPerson; import org.kuali.kra.budget.personnel.BudgetPersonnelBudgetService; import org.kuali.kra.budget.personnel.BudgetPersonnelDetails; import org.kuali.kra.budget.versions.BudgetDocumentVersion; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.PermissionConstants; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.proposaldevelopment.bo.CongressionalDistrict; import org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal; import org.kuali.kra.proposaldevelopment.bo.Narrative; import org.kuali.kra.proposaldevelopment.bo.NarrativeAttachment; import org.kuali.kra.proposaldevelopment.bo.PropScienceKeyword; import org.kuali.kra.proposaldevelopment.bo.ProposalBudgetStatus; import org.kuali.kra.proposaldevelopment.bo.ProposalPerson; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonBiography; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonBiographyAttachment; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonUnit; import org.kuali.kra.proposaldevelopment.bo.ProposalSite; import org.kuali.kra.proposaldevelopment.bo.ProposalSpecialReview; import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwardAttachment; import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwardFiles; import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwards; import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument; import org.kuali.kra.proposaldevelopment.hierarchy.HierarchyBudgetTypeConstants; import org.kuali.kra.proposaldevelopment.hierarchy.HierarchyStatusConstants; import org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyErrorDto; import org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyException; import org.kuali.kra.proposaldevelopment.hierarchy.bo.HierarchyProposalSummary; import org.kuali.kra.proposaldevelopment.hierarchy.dao.ProposalHierarchyDao; import org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService; import org.kuali.kra.proposaldevelopment.service.NarrativeService; import org.kuali.kra.proposaldevelopment.service.ProposalPersonBiographyService; import org.kuali.kra.proposaldevelopment.service.ProposalStateService; import org.kuali.kra.service.DeepCopyPostProcessor; import org.kuali.kra.service.KraAuthorizationService; import org.kuali.rice.kew.doctype.service.DocumentTypeService; import org.kuali.rice.kew.dto.DocumentRouteStatusChangeDTO; import org.kuali.rice.kew.dto.DocumentTypeDTO; import org.kuali.rice.kew.dto.ProcessDTO; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.service.WorkflowDocument; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kim.service.IdentityManagementService; import org.kuali.rice.kns.bo.DocumentHeader; import org.kuali.rice.kns.document.Document; import org.kuali.rice.kns.service.BusinessObjectService; import org.kuali.rice.kns.service.DocumentService; import org.kuali.rice.kns.service.KualiConfigurationService; import org.kuali.rice.kns.service.ParameterService; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.KNSConstants; import org.kuali.rice.kns.util.ObjectUtils; import org.kuali.rice.kns.web.struts.form.KualiForm; import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument; import org.kuali.rice.kns.workflow.service.WorkflowDocumentService; import org.springframework.transaction.annotation.Transactional; /** * This class... */ @Transactional public class ProposalHierarchyServiceImpl implements ProposalHierarchyService { private static final Log LOG = LogFactory.getLog(ProposalHierarchyServiceImpl.class); private BusinessObjectService businessObjectService; private DocumentService documentService; private KraAuthorizationService kraAuthorizationService; private ProposalHierarchyDao proposalHierarchyDao; private NarrativeService narrativeService; private BudgetService budgetService; private ProposalPersonBiographyService propPersonBioService; private ParameterService parameterService; private IdentityManagementService identityManagementService; private ProposalStateService proposalStateService; private KualiConfigurationService configurationService; /** * Sets the proposalStateService attribute value. * @param proposalStateService The ProposalStateService to set. */ public void setProposalStateService(ProposalStateService proposalStateService) { this.proposalStateService = proposalStateService; } /** * Sets the identityManagerService attribute value. * @param identityManagerService The IdentityManagerService to set. */ public void setIdentityManagementService(IdentityManagementService identityManagerService) { this.identityManagementService = identityManagerService; } /** * Sets the businessObjectService attribute value. * @param businessObjectService The businessObjectService to set. */ public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } /** * Sets the documentService attribute value. * @param documentService The documentService to set. */ public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } /** * Sets the kraAuthorizationService attribute value. * @param kraAuthorizationService The kraAuthorizationService to set. */ public void setKraAuthorizationService(KraAuthorizationService kraAuthorizationService) { this.kraAuthorizationService = kraAuthorizationService; } /** * Sets the proposalHierarchyDao attribute value. * @param proposalHierarchyDao The proposalHierarchyDao to set. */ public void setProposalHierarchyDao(ProposalHierarchyDao proposalHierarchyDao) { this.proposalHierarchyDao = proposalHierarchyDao; } /** * Sets the narrativeService attribute value. * @param narrativeService The narrativeService to set. */ public void setNarrativeService(NarrativeService narrativeService) { this.narrativeService = narrativeService; } /** * Sets the budgetService attribute value. * @param budgetService The budgetService to set. */ public void setBudgetService(BudgetService budgetService) { this.budgetService = budgetService; } /** * Sets the propPersonBioService attribute value. * @param propPersonBioService The propPersonBioService to set. */ public void setPropPersonBioService(ProposalPersonBiographyService propPersonBioService) { this.propPersonBioService = propPersonBioService; } /** * Sets the parameterService attribute value. * @param parameterService The parameterService to set. */ public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#createHierarchy(java.lang.String) */ public String createHierarchy(DevelopmentProposal initialChild) throws ProposalHierarchyException { LOG.info(String.format("***Create Hierarchy using Proposal #%s", initialChild.getProposalNumber())); if (initialChild.isInHierarchy()) { throw new ProposalHierarchyException("Cannot create hierarchy: proposal " + initialChild.getProposalNumber() + " is already a member of a hierarchy."); } // create a new proposal document ProposalDevelopmentDocument newDoc; // manually assembling a new PDDoc here because the DocumentService will deny initiator permission without context // since a person with MAINTAIN_PROPOSAL_HIERARCHY permission is allowed to initiate IF they are creating a parent // we circumvent the initiator step altogether. try { KualiWorkflowDocument workflowDocument = KraServiceLocator.getService(WorkflowDocumentService.class).createWorkflowDocument("ProposalDevelopmentDocument", GlobalVariables.getUserSession().getPerson()); GlobalVariables.getUserSession().setWorkflowDocument(workflowDocument); DocumentHeader documentHeader = new DocumentHeader(); documentHeader.setWorkflowDocument(workflowDocument); documentHeader.setDocumentNumber(workflowDocument.getRouteHeaderId().toString()); newDoc = new ProposalDevelopmentDocument(); newDoc.setDocumentHeader(documentHeader); newDoc.setDocumentNumber(documentHeader.getDocumentNumber()); } catch (WorkflowException x) { throw new ProposalHierarchyException("Error creating new document: " + x); } // copy the initial information to the new parent proposal DevelopmentProposal hierarchy = newDoc.getDevelopmentProposal(); copyInitialData(hierarchy, initialChild); hierarchy.setHierarchyStatus(HierarchyStatusConstants.Parent.code()); String docDescription = initialChild.getProposalDocument().getDocumentHeader() .getDocumentDescription(); newDoc.getDocumentHeader().setDocumentDescription(docDescription); // persist the document and add a budget try { documentService.saveDocument(newDoc); budgetService.addBudgetVersion(newDoc, "Hierarchy Budget"); } catch (WorkflowException x) { throw new ProposalHierarchyException("Error saving new document: " + x); } LOG.info(String.format("***New Hierarchy Parent (#%s) budget created", hierarchy.getProposalNumber())); // add aggregator to the document String userId = GlobalVariables.getUserSession().getPrincipalId(); kraAuthorizationService.addRole(userId, RoleConstants.AGGREGATOR, newDoc); initializeBudget(hierarchy, initialChild); prepareHierarchySync(hierarchy); // link the child to the parent linkChild(hierarchy, initialChild, HierarchyBudgetTypeConstants.SubBudget.code()); setInitialPi(hierarchy, initialChild); copyInitialAttachments(initialChild, hierarchy); aggregateHierarchy(hierarchy); LOG.info(String.format("***Initial Child (#%s) linked to Parent (#%s)", initialChild.getProposalNumber(), hierarchy.getProposalNumber())); finalizeHierarchySync(hierarchy); // return the parent id LOG.info(String.format("***Hierarchy creation (#%s) complete", hierarchy.getProposalNumber())); return hierarchy.getProposalNumber(); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#linkToHierarchy(org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal, org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal, java.lang.String) */ public void linkToHierarchy(DevelopmentProposal hierarchyProposal, DevelopmentProposal newChildProposal, String hierarchyBudgetTypeCode) throws ProposalHierarchyException { LOG.info(String.format("***Linking Child (#%s) linked to Parent (#%s)", newChildProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); if (!hierarchyProposal.isParent()) { throw new ProposalHierarchyException("Proposal " + hierarchyProposal.getProposalNumber() + " is not a hierarchy parent"); } if (newChildProposal.isInHierarchy()) { throw new ProposalHierarchyException("Proposal " + newChildProposal.getProposalNumber() + " is already a member of a hierarchy"); } prepareHierarchySync(hierarchyProposal); linkChild(hierarchyProposal, newChildProposal, hierarchyBudgetTypeCode); finalizeHierarchySync(hierarchyProposal); LOG.info(String.format("***Linking Child (#%s) linked to Parent (#%s) complete", newChildProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#removeFromHierarchy(java.lang.String) */ public void removeFromHierarchy(DevelopmentProposal childProposal) throws ProposalHierarchyException { String hierarchyProposalNumber = childProposal.getHierarchyParentProposalNumber(); DevelopmentProposal hierarchyProposal = getHierarchy(hierarchyProposalNumber); BudgetDocument<DevelopmentProposal> hierarchyBudgetDoc = getHierarchyBudget(hierarchyProposal); Budget hierarchyBudget = hierarchyBudgetDoc.getBudget(); LOG.info(String.format("***Removing Child (#%s) from Parent (#%s)", childProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); boolean isLast = proposalHierarchyDao.getHierarchyChildProposalNumbers(hierarchyProposalNumber).size()==1; childProposal.setHierarchyStatus(HierarchyStatusConstants.None.code()); childProposal.setHierarchyParentProposalNumber(null); removeChildElements(hierarchyProposal, hierarchyBudget, childProposal.getProposalNumber()); try { documentService.saveDocument(hierarchyBudgetDoc); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } if (isLast) { try { LOG.info(String.format("***Child (#%s) was last child, cancelling Parent (#%s)", childProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); businessObjectService.save(childProposal); Document doc = documentService.getByDocumentHeaderId(hierarchyProposal.getProposalDocument().getDocumentNumber()); documentService.cancelDocument(doc, "Removed last child from Proposal Hierarchy"); } catch (WorkflowException e) { throw new ProposalHierarchyException("Error cancelling empty parent proposal"); } } else { businessObjectService.save(childProposal); synchronizeAllChildren(hierarchyProposal); } LOG.info(String.format("***Removing Child (#%s) from Parent (#%s) complete", childProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchySyncService#synchronizeAllChildren(java.lang.String) */ public void synchronizeAllChildren(ProposalDevelopmentDocument pdDoc) throws ProposalHierarchyException { prepareHierarchySync(pdDoc); synchronizeAll(pdDoc.getDevelopmentProposal()); finalizeHierarchySync(pdDoc); } private void synchronizeAllChildren(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { prepareHierarchySync(hierarchyProposal); synchronizeAll(hierarchyProposal); finalizeHierarchySync(hierarchyProposal); } private void synchronizeAll(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { boolean changed = false; DevelopmentProposal childProposal; LOG.info(String.format("***Synchronizing all Children of Parent (#%s)", hierarchyProposal.getProposalNumber())); if (!hierarchyProposal.isParent()) { throw new ProposalHierarchyException("Proposal " + hierarchyProposal.getProposalNumber() + " is not a hierarchy parent"); } for (String childProposalNumber : proposalHierarchyDao.getHierarchyChildProposalNumbers(hierarchyProposal.getProposalNumber())) { childProposal = getDevelopmentProposal(childProposalNumber); changed |= synchronizeChild(hierarchyProposal, childProposal); } if (changed) { aggregateHierarchy(hierarchyProposal); } LOG.info(String.format("***Synchronizing all Children of Parent (#%s) complete", hierarchyProposal.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchySyncService#synchronizeChild(java.lang.String) */ public void synchronizeChild(DevelopmentProposal childProposal) throws ProposalHierarchyException { DevelopmentProposal hierarchy = getHierarchy(childProposal.getHierarchyParentProposalNumber()); LOG.info(String.format("***Synchronizing Child (#%s) of Parent (#%s)", childProposal.getProposalNumber(), hierarchy.getProposalNumber())); prepareHierarchySync(hierarchy); boolean changed = synchronizeChild(hierarchy, childProposal); if (changed) { aggregateHierarchy(hierarchy); } finalizeHierarchySync(hierarchy); LOG.info(String.format("***Synchronizing Child (#%s) of Parent (#%s) complete", childProposal.getProposalNumber(), hierarchy.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#lookupParent(org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal) */ public DevelopmentProposal lookupParent(DevelopmentProposal childProposal) throws ProposalHierarchyException { return getHierarchy(childProposal.getHierarchyParentProposalNumber()); } private void linkChild(DevelopmentProposal hierarchyProposal, DevelopmentProposal newChildProposal, String hierarchyBudgetTypeCode) throws ProposalHierarchyException { // set child to child status newChildProposal.setHierarchyStatus(HierarchyStatusConstants.Child.code()); newChildProposal.setHierarchyParentProposalNumber(hierarchyProposal.getProposalNumber()); newChildProposal.setHierarchyBudgetType(hierarchyBudgetTypeCode); // call synchronize synchronizeChild(hierarchyProposal, newChildProposal); // call aggregate aggregateHierarchy(hierarchyProposal); } private void copyInitialData(DevelopmentProposal hierarchyProposal, DevelopmentProposal srcProposal) throws ProposalHierarchyException { // Required fields for saving document hierarchyProposal.setSponsor(srcProposal.getSponsor()); hierarchyProposal.setSponsorCode(srcProposal.getSponsorCode()); hierarchyProposal.setProposalTypeCode(srcProposal.getProposalTypeCode()); hierarchyProposal.setRequestedStartDateInitial(srcProposal.getRequestedStartDateInitial()); hierarchyProposal.setRequestedEndDateInitial(srcProposal.getRequestedEndDateInitial()); hierarchyProposal.setOwnedByUnit(srcProposal.getOwnedByUnit()); hierarchyProposal.setOwnedByUnitNumber(srcProposal.getOwnedByUnitNumber()); hierarchyProposal.setActivityType(srcProposal.getActivityType()); hierarchyProposal.setActivityTypeCode(srcProposal.getActivityTypeCode()); hierarchyProposal.setTitle(srcProposal.getTitle()); // Sponsor & program information hierarchyProposal.setDeadlineDate(srcProposal.getDeadlineDate()); hierarchyProposal.setDeadlineType(srcProposal.getDeadlineType()); hierarchyProposal.setNoticeOfOpportunityCode(srcProposal.getNoticeOfOpportunityCode()); hierarchyProposal.setCfdaNumber(srcProposal.getCfdaNumber()); hierarchyProposal.setPrimeSponsorCode(srcProposal.getPrimeSponsorCode()); hierarchyProposal.setNsfCode(srcProposal.getNsfCode()); hierarchyProposal.setSponsorProposalNumber(srcProposal.getSponsorProposalNumber()); hierarchyProposal.setAgencyDivisionCode(srcProposal.getAgencyDivisionCode()); hierarchyProposal.setAgencyProgramCode(srcProposal.getAgencyProgramCode()); hierarchyProposal.setSubcontracts(srcProposal.getSubcontracts()); hierarchyProposal.setProgramAnnouncementNumber(srcProposal.getProgramAnnouncementNumber()); hierarchyProposal.setProgramAnnouncementTitle(srcProposal.getProgramAnnouncementTitle()); // Organization/location ProposalSite newSite; hierarchyProposal.getProposalSites().clear(); for (ProposalSite site : srcProposal.getProposalSites()) { newSite = (ProposalSite)ObjectUtils.deepCopy(site); newSite.setProposalNumber(null); newSite.setVersionNumber(null); for (CongressionalDistrict cd : newSite.getCongressionalDistricts()) { cd.setProposalNumber(null); cd.setCongressionalDistrictId(null); cd.setVersionNumber(null); } hierarchyProposal.addProposalSite(newSite); } // Delivery info hierarchyProposal.setMailBy(srcProposal.getMailBy()); hierarchyProposal.setMailType(srcProposal.getMailType()); hierarchyProposal.setMailAccountNumber(srcProposal.getMailAccountNumber()); hierarchyProposal.setNumberOfCopies(srcProposal.getNumberOfCopies()); hierarchyProposal.setMailingAddressId(srcProposal.getMailingAddressId()); hierarchyProposal.setMailDescription(srcProposal.getMailDescription()); } private boolean synchronizeChild(DevelopmentProposal hierarchyProposal, DevelopmentProposal childProposal) throws ProposalHierarchyException { String instituteNarrativeTypeGroup = parameterService.getParameterValue(ProposalDevelopmentDocument.class, PARAMETER_NAME_INSTITUTE_NARRATIVE_TYPE_GROUP); /* TODO restore code below after testing if (isSynchronized(childProposal.getProposalNumber())) { return false; } */ ProposalPerson pi = hierarchyProposal.getPrincipalInvestigator(); List<PropScienceKeyword> oldKeywords = new ArrayList<PropScienceKeyword>(); for (PropScienceKeyword keyword : hierarchyProposal.getPropScienceKeywords()) { if (StringUtils.equals(childProposal.getProposalNumber(), keyword.getHierarchyProposalNumber())) { oldKeywords.add(keyword); } } BudgetDocument<DevelopmentProposal> hierarchyBudgetDocument = getHierarchyBudget(hierarchyProposal); Budget hierarchyBudget = hierarchyBudgetDocument.getBudget(); BudgetDocument<DevelopmentProposal> childBudgetDocument = getFinalOrLatestChildBudget(childProposal); Budget childBudget = childBudgetDocument.getBudget(); ObjectUtils.materializeAllSubObjects(hierarchyBudget); ObjectUtils.materializeAllSubObjects(childBudget); childProposal.setHierarchyLastSyncHashCode(computeHierarchyHashCode(childProposal, childBudget)); removeChildElements(hierarchyProposal, hierarchyBudget, childProposal.getProposalNumber()); // copy PropScienceKeywords for (PropScienceKeyword keyword : childProposal.getPropScienceKeywords()) { PropScienceKeyword newKeyword = new PropScienceKeyword(hierarchyProposal.getProposalNumber(), keyword.getScienceKeyword()); int index = oldKeywords.indexOf(newKeyword); if (index > -1) { newKeyword = oldKeywords.get(index); } newKeyword.setHierarchyProposalNumber(childProposal.getProposalNumber()); hierarchyProposal.addPropScienceKeyword(newKeyword); } // copy PropSpecialReviews for(ProposalSpecialReview review : childProposal.getPropSpecialReviews()) { ProposalSpecialReview newReview = (ProposalSpecialReview)ObjectUtils.deepCopy(review); newReview.setProposalNumber(hierarchyProposal.getProposalNumber()); newReview.setSpecialReviewNumber(hierarchyProposal.getProposalDocument().getDocumentNextValue(Constants.PROPOSAL_SPECIALREVIEW_NUMBER)); newReview.setVersionNumber(null); newReview.setHierarchyProposalNumber(childProposal.getProposalNumber()); hierarchyProposal.getPropSpecialReviews().add(newReview); } // copy Narratives for (Narrative narrative : childProposal.getNarratives()) { if (!StringUtils.equalsIgnoreCase(narrative.getNarrativeType().getAllowMultiple(), "N") && !StringUtils.equalsIgnoreCase(narrative.getNarrativeType().getNarrativeTypeGroup(), instituteNarrativeTypeGroup)) { Map<String,String> primaryKey = new HashMap<String,String>(); primaryKey.put("proposalNumber", narrative.getProposalNumber()); primaryKey.put("moduleNumber", narrative.getModuleNumber()+""); NarrativeAttachment attachment = (NarrativeAttachment)businessObjectService.findByPrimaryKey(NarrativeAttachment.class, primaryKey); narrative.getNarrativeAttachmentList().clear(); narrative.getNarrativeAttachmentList().add(attachment); Narrative newNarrative = (Narrative)ObjectUtils.deepCopy(narrative); newNarrative.setVersionNumber(null); newNarrative.setHierarchyProposalNumber(childProposal.getProposalNumber()); narrativeService.addNarrative(hierarchyProposal.getProposalDocument(), newNarrative); } } // copy ProposalPersons int firstIndex, lastIndex; ProposalPerson firstInstance; for (ProposalPerson person : childProposal.getProposalPersons()) { firstIndex = hierarchyProposal.getProposalPersons().indexOf(person); lastIndex = hierarchyProposal.getProposalPersons().lastIndexOf(person); firstInstance = (firstIndex == -1) ? null : hierarchyProposal.getProposalPersons().get(firstIndex); if (firstIndex == -1 || (firstIndex == lastIndex && !rolesAreSimilar(person, firstInstance))) { ProposalPerson newPerson; newPerson = (ProposalPerson)ObjectUtils.deepCopy(person); newPerson.setProposalNumber(hierarchyProposal.getProposalNumber()); newPerson.getProposalPersonYnqs().clear(); newPerson.getCreditSplits().clear(); for (ProposalPersonUnit unit : newPerson.getUnits()) { unit.getCreditSplits().clear(); } newPerson.setProposalPersonNumber(null); newPerson.setVersionNumber(null); newPerson.setHierarchyProposalNumber(childProposal.getProposalNumber()); if (StringUtils.equalsIgnoreCase(person.getProposalPersonRoleId(), Constants.PRINCIPAL_INVESTIGATOR_ROLE)) { newPerson.setProposalPersonRoleId(Constants.CO_INVESTIGATOR_ROLE); } if (newPerson.equals(pi) && (firstIndex == -1 || !firstInstance.isInvestigator())) { newPerson.setProposalPersonRoleId(Constants.PRINCIPAL_INVESTIGATOR_ROLE); } hierarchyProposal.addProposalPerson(newPerson); } } businessObjectService.save(childProposal); LOG.info(String.format("***Beginning Hierarchy Budget Sync for Parent %s and Child %s", hierarchyProposal.getProposalNumber(), childProposal.getProposalNumber())); synchronizeChildBudget(hierarchyBudget, childBudget, childProposal.getProposalNumber(), childProposal.getHierarchyBudgetType()); if (hierarchyBudget.getEndDate().after(hierarchyProposal.getRequestedEndDateInitial())) { hierarchyProposal.setRequestedEndDateInitial(hierarchyBudget.getEndDate()); } if (childProposal.getRequestedEndDateInitial().after(hierarchyProposal.getRequestedEndDateInitial())) { hierarchyProposal.setRequestedEndDateInitial(childProposal.getRequestedEndDateInitial()); } try { documentService.saveDocument(hierarchyBudgetDocument); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } LOG.info(String.format("***Completed Hierarchy Budget Sync for Parent %s and Child %s", hierarchyProposal.getProposalNumber(), childProposal.getProposalNumber())); return true; } private void synchronizeChildBudget(Budget parentBudget, Budget childBudget, String childProposalNumber, String hierarchyBudgetTypeCode) throws ProposalHierarchyException { try { BudgetPerson newPerson; Map<Integer, BudgetPerson> personMap = new HashMap<Integer, BudgetPerson>(); for (BudgetPerson person : childBudget.getBudgetPersons()) { newPerson = (BudgetPerson) ObjectUtils.deepCopy(person); newPerson.setPersonSequenceNumber(parentBudget.getBudgetDocument().getHackedDocumentNextValue( Constants.PERSON_SEQUENCE_NUMBER)); // newPerson.setBudget(parentBudget); newPerson.setBudgetId(parentBudget.getBudgetId()); newPerson.setHierarchyProposalNumber(childProposalNumber); newPerson.setVersionNumber(null); parentBudget.addBudgetPerson(newPerson); personMap.put(person.getPersonSequenceNumber(), newPerson); } BudgetSubAwards newSubAwards; for (BudgetSubAwards childSubAwards : childBudget.getBudgetSubAwards()) { childSubAwards.refreshReferenceObject("budgetSubAwardAttachments"); childSubAwards.refreshReferenceObject("budgetSubAwardFiles"); newSubAwards = (BudgetSubAwards) ObjectUtils.deepCopy(childSubAwards); newSubAwards.setBudgetId(parentBudget.getBudgetId()); // newSubAwards.setBudget(parentBudget); newSubAwards.setBudgetVersionNumber(parentBudget.getBudgetVersionNumber()); newSubAwards.setSubAwardNumber(parentBudget.getBudgetDocument().getHackedDocumentNextValue("subAwardNumber") != null ? parentBudget.getBudgetDocument().getHackedDocumentNextValue("subAwardNumber") : 1); newSubAwards.setVersionNumber(null); newSubAwards.setHierarchyProposalNumber(childProposalNumber); for (BudgetSubAwardAttachment attachment : newSubAwards.getBudgetSubAwardAttachments()) { attachment.setSubAwardNumber(newSubAwards.getSubAwardNumber()); // attachment.setBudget(parentBudget); attachment.setBudgetId(parentBudget.getBudgetId()); attachment.setBudgetSubawardAttachmentId(null); attachment.setVersionNumber(null); } for (BudgetSubAwardFiles files : newSubAwards.getBudgetSubAwardFiles()) { files.setSubAwardNumber(newSubAwards.getSubAwardNumber()); // files.setBudget(parentBudget); files.setBudgetId(parentBudget.getBudgetId()); files.setVersionNumber(null); } List<BudgetAssociate> listToBeSaved = new ArrayList<BudgetAssociate>(); listToBeSaved.add(newSubAwards); listToBeSaved.addAll(newSubAwards.getBudgetSubAwardFiles()); listToBeSaved.addAll(newSubAwards.getBudgetSubAwardAttachments()); businessObjectService.save(listToBeSaved); parentBudget.getBudgetSubAwards().add(newSubAwards); } int parentStartPeriod = getCorrespondingParentPeriod(parentBudget, childBudget); if (parentStartPeriod == -1) { throw new ProposalHierarchyException("Cannot find a parent budget period that corresponds to the child period."); } List<BudgetPeriod> parentPeriods = parentBudget.getBudgetPeriods(); List<BudgetPeriod> childPeriods = childBudget.getBudgetPeriods(); BudgetPeriod parentPeriod, childPeriod; Long budgetId = parentBudget.getBudgetId(); Long budgetPeriodId; Integer budgetPeriod; for (int i = 0, j = parentStartPeriod; i < childPeriods.size(); i++, j++) { childPeriod = childPeriods.get(i); if (j >= parentPeriods.size()) { parentPeriod = parentBudget.getNewBudgetPeriod(); parentPeriod.setBudgetPeriod(j + 1); parentPeriod.setBudget(parentBudget); parentPeriod.setStartDate(childPeriod.getStartDate()); parentPeriod.setEndDate(childPeriod.getEndDate()); parentPeriod.setBudgetId(budgetId); parentBudget.add(parentPeriod); } else { parentPeriod = parentPeriods.get(j); } budgetPeriodId = parentPeriod.getBudgetPeriodId(); budgetPeriod = parentPeriod.getBudgetPeriod(); BudgetLineItem parentLineItem; Integer lineItemNumber; if (StringUtils.equals(hierarchyBudgetTypeCode, HierarchyBudgetTypeConstants.SubBudget.code())) { for (BudgetLineItem childLineItem : childPeriod.getBudgetLineItems()) { ObjectUtils.materializeSubObjectsToDepth(childLineItem, 5); parentLineItem = (BudgetLineItem) (KraServiceLocator.getService(DeepCopyPostProcessor.class).processDeepCopyWithDeepCopyIgnore(childLineItem)); parentLineItem.setBudgetId(budgetId); parentLineItem.setBudgetPeriodId(budgetPeriodId); parentLineItem.setBudgetPeriod(budgetPeriod); parentLineItem.setVersionNumber(null); lineItemNumber = parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_LINEITEM_NUMBER); parentLineItem.setLineItemNumber(lineItemNumber); parentLineItem.setHierarchyProposalNumber(childProposalNumber); //parentLineItem.setUnderrecoveryAmount(childLineItem.getUnderrecoveryAmount()); BudgetPerson budgetPerson; for (BudgetPersonnelDetails details : parentLineItem.getBudgetPersonnelDetailsList()) { budgetPerson = personMap.get(details.getPersonSequenceNumber()); details.setBudgetPersonnelLineItemId(null); details.setBudgetId(budgetId); details.setBudgetPeriodId(budgetPeriodId); details.setBudgetPeriod(budgetPeriod); details.setBudgetPerson(budgetPerson); details.setJobCode(budgetPerson.getJobCode()); details.setPersonId(budgetPerson.getPersonRolodexTbnId()); details.setPersonSequenceNumber(budgetPerson.getPersonSequenceNumber()); details.setPersonNumber(parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_PERSON_LINE_NUMBER)); details.setLineItemNumber(lineItemNumber); details.setVersionNumber(null); } parentPeriod.getBudgetLineItems().add(parentLineItem); } } else { // subproject budget Map<String, String> primaryKeys; CostElement costElement; String directCostElement = parameterService.getParameterValue(BudgetDocument.class, PARAMETER_NAME_DIRECT_COST_ELEMENT); String indirectCostElement = parameterService.getParameterValue(BudgetDocument.class, PARAMETER_NAME_INDIRECT_COST_ELEMENT); if (childPeriod.getTotalIndirectCost().isNonZero()) { primaryKeys = new HashMap<String, String>(); primaryKeys.put("costElement", indirectCostElement); costElement = (CostElement)businessObjectService.findByPrimaryKey(CostElement.class, primaryKeys); parentLineItem = parentBudget.getNewBudgetLineItem(); parentLineItem.setLineItemDescription(childProposalNumber); parentLineItem.setStartDate(parentPeriod.getStartDate()); parentLineItem.setEndDate(parentPeriod.getEndDate()); parentLineItem.setBudgetId(budgetId); parentLineItem.setBudgetPeriodId(budgetPeriodId); parentLineItem.setBudgetPeriod(budgetPeriod); parentLineItem.setVersionNumber(null); lineItemNumber = parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_LINEITEM_NUMBER); parentLineItem.setLineItemNumber(lineItemNumber); parentLineItem.setHierarchyProposalNumber(childProposalNumber); parentLineItem.setLineItemCost(childPeriod.getTotalIndirectCost()); parentLineItem.setIndirectCost(childPeriod.getTotalIndirectCost()); parentLineItem.setCostElementBO(costElement); parentLineItem.setCostElement(costElement.getCostElement()); parentLineItem.setBudgetCategoryCode(costElement.getBudgetCategoryCode()); parentLineItem.setOnOffCampusFlag(costElement.getOnOffCampusFlag()); parentLineItem.setApplyInRateFlag(true); parentPeriod.getBudgetLineItems().add(parentLineItem); } if (childPeriod.getTotalDirectCost().isNonZero()) { primaryKeys = new HashMap<String, String>(); primaryKeys.put("costElement", directCostElement); costElement = (CostElement)businessObjectService.findByPrimaryKey(CostElement.class, primaryKeys); parentLineItem = parentBudget.getNewBudgetLineItem(); parentLineItem.setLineItemDescription(childProposalNumber); parentLineItem.setStartDate(parentPeriod.getStartDate()); parentLineItem.setEndDate(parentPeriod.getEndDate()); parentLineItem.setBudgetId(budgetId); parentLineItem.setBudgetPeriodId(budgetPeriodId); parentLineItem.setBudgetPeriod(budgetPeriod); parentLineItem.setVersionNumber(null); lineItemNumber = parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_LINEITEM_NUMBER); parentLineItem.setLineItemNumber(lineItemNumber); parentLineItem.setHierarchyProposalNumber(childProposalNumber); parentLineItem.setLineItemCost(childPeriod.getTotalDirectCost()); parentLineItem.setDirectCost(childPeriod.getTotalDirectCost()); parentLineItem.setCostElementBO(costElement); parentLineItem.setCostElement(costElement.getCostElement()); parentLineItem.setBudgetCategoryCode(costElement.getBudgetCategoryCode()); parentLineItem.setOnOffCampusFlag(costElement.getOnOffCampusFlag()); parentLineItem.setApplyInRateFlag(true); parentPeriod.getBudgetLineItems().add(parentLineItem); } } } parentBudget.setStartDate(parentBudget.getBudgetPeriod(0).getStartDate()); parentBudget.setEndDate(parentBudget.getBudgetPeriod(parentBudget.getBudgetPeriods().size()-1).getEndDate()); } catch (Exception e) { LOG.error("Problem copying line items to parent", e); throw new ProposalHierarchyException("Problem copying line items to parent", e); } } private void aggregateHierarchy(DevelopmentProposal hierarchy) throws ProposalHierarchyException { LOG.info(String.format("***Aggregating Proposal Hierarchy #%s", hierarchy.getProposalNumber())); List<ProposalPersonBiography> biosToRemove = new ArrayList<ProposalPersonBiography>(); for (ProposalPersonBiography bio : hierarchy.getPropPersonBios()) { String bioPersonId = bio.getPersonId(); Integer bioRolodexId = bio.getRolodexId(); boolean keep = false; for (ProposalPerson person : hierarchy.getProposalPersons()) { if ((bioPersonId != null && bioPersonId.equals(person.getPersonId())) || (bioRolodexId != null && bioRolodexId.equals(person.getRolodexId()))) { bio.setProposalPersonNumber(person.getProposalPersonNumber()); keep = true; break; } } if (!keep) { biosToRemove.add(bio); } } if (!biosToRemove.isEmpty()) { hierarchy.getPropPersonBios().removeAll(biosToRemove); } BudgetDocument<DevelopmentProposal> hierarchyBudgetDocument = getHierarchyBudget(hierarchy); Budget hierarchyBudget = hierarchyBudgetDocument.getBudget(); KualiForm oldForm = GlobalVariables.getKualiForm(); GlobalVariables.setKualiForm(null); KraServiceLocator.getService(BudgetCalculationService.class).calculateBudget(hierarchyBudget); KraServiceLocator.getService(BudgetCalculationService.class).calculateBudgetSummaryTotals(hierarchyBudget); GlobalVariables.setKualiForm(oldForm); try { documentService.saveDocument(hierarchyBudgetDocument); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } } private DevelopmentProposal getHierarchy(String hierarchyProposalNumber) throws ProposalHierarchyException { DevelopmentProposal hierarchy = getDevelopmentProposal(hierarchyProposalNumber); if (hierarchy == null || !hierarchy.isParent()) throw new ProposalHierarchyException("Proposal " + hierarchyProposalNumber + " is not a hierarchy"); return hierarchy; } public DevelopmentProposal getDevelopmentProposal(String proposalNumber) { Map<String, String> pk = new HashMap<String, String>(); pk.put("proposalNumber", proposalNumber); return (DevelopmentProposal) (businessObjectService.findByPrimaryKey(DevelopmentProposal.class, pk)); } private boolean isSynchronized(String childProposalNumber) throws ProposalHierarchyException { DevelopmentProposal childProposal = getDevelopmentProposal(childProposalNumber); Budget childBudget = getFinalOrLatestChildBudget(childProposal).getBudget(); ObjectUtils.materializeAllSubObjects(childBudget); int hc1 = computeHierarchyHashCode(childProposal, childBudget); int hc2 = childProposal.getHierarchyLastSyncHashCode(); return hc1 == hc2; } private void setInitialPi(DevelopmentProposal hierarchy, DevelopmentProposal child) { ProposalPerson pi = child.getPrincipalInvestigator(); if (pi != null) { int index = hierarchy.getProposalPersons().indexOf(pi); if (index > -1) { hierarchy.getProposalPerson(index).setProposalPersonRoleId(Constants.PRINCIPAL_INVESTIGATOR_ROLE); hierarchy.getProposalPerson(index).setHierarchyProposalNumber(null); } } } private BudgetDocument<DevelopmentProposal> getHierarchyBudget(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { String budgetDocumentNumber = hierarchyProposal.getProposalDocument().getBudgetDocumentVersions().get(0).getBudgetVersionOverview().getDocumentNumber(); BudgetDocument<DevelopmentProposal> budgetDocument = null; try { budgetDocument = (BudgetDocument<DevelopmentProposal>) documentService.getByDocumentHeaderId(budgetDocumentNumber); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } return budgetDocument;//.getBudget(); } private BudgetDocument<DevelopmentProposal> getFinalOrLatestChildBudget(DevelopmentProposal childProposal) throws ProposalHierarchyException { String budgetDocumentNumber = null; for (BudgetDocumentVersion version : childProposal.getProposalDocument().getBudgetDocumentVersions()) { budgetDocumentNumber = version.getDocumentNumber(); if (version.getBudgetVersionOverview().isFinalVersionFlag()) { break; } } BudgetDocument<DevelopmentProposal> budgetDocument = null; try { budgetDocument = (BudgetDocument<DevelopmentProposal>) documentService.getByDocumentHeaderId(budgetDocumentNumber); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } return budgetDocument;//.getBudget(); } private void initializeBudget (DevelopmentProposal hierarchyProposal, DevelopmentProposal childProposal) throws ProposalHierarchyException { BudgetDocument<DevelopmentProposal> parentBudgetDoc = getHierarchyBudget(hierarchyProposal); Budget parentBudget = parentBudgetDoc.getBudget(); BudgetDocument<DevelopmentProposal> childBudgetDocument = getFinalOrLatestChildBudget(childProposal); Budget childBudget = childBudgetDocument.getBudget(); BudgetPeriod parentPeriod, childPeriod; for (int i=0; i < childBudget.getBudgetPeriods().size(); i++) { parentPeriod = parentBudget.getBudgetPeriod(i); childPeriod = childBudget.getBudgetPeriod(i); parentPeriod.setStartDate(childPeriod.getStartDate()); parentPeriod.setEndDate(childPeriod.getEndDate()); parentPeriod.setBudgetPeriod(childPeriod.getBudgetPeriod()); } parentBudget.setCostSharingAmount(new BudgetDecimal(0)); parentBudget.setTotalCost(new BudgetDecimal(0)); parentBudget.setTotalDirectCost(new BudgetDecimal(0)); parentBudget.setTotalIndirectCost(new BudgetDecimal(0)); parentBudget.setUnderrecoveryAmount(new BudgetDecimal(0)); parentBudget.setOhRateClassCode(childBudget.getOhRateClassCode()); parentBudget.setOhRateTypeCode(childBudget.getOhRateTypeCode()); parentBudget.setUrRateClassCode(childBudget.getUrRateClassCode()); try { documentService.saveDocument(parentBudgetDoc); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } } public ProposalHierarchyErrorDto validateChildBudgetPeriods(DevelopmentProposal hierarchyProposal, DevelopmentProposal childProposal, boolean allowEndDateChange) throws ProposalHierarchyException { BudgetDocument<DevelopmentProposal> parentBudgetDoc = getHierarchyBudget(hierarchyProposal); Budget parentBudget = parentBudgetDoc.getBudget(); BudgetDocument<DevelopmentProposal> childBudgetDocument = getFinalOrLatestChildBudget(childProposal); Budget childBudget = childBudgetDocument.getBudget(); ProposalHierarchyErrorDto retval = null; // check that child budget starts on one of the budget period starts int correspondingStart = getCorrespondingParentPeriod(parentBudget, childBudget); if (correspondingStart == -1) { retval = new ProposalHierarchyErrorDto(ERROR_BUDGET_START_DATE_INCONSISTENT, childProposal.getProposalNumber()); } // check that child budget periods map to parent periods else { List<BudgetPeriod> parentPeriods = parentBudget.getBudgetPeriods(); List<BudgetPeriod> childPeriods = childBudget.getBudgetPeriods(); BudgetPeriod parentPeriod, childPeriod; int i; int j; for (i = correspondingStart, j = 0; i < parentPeriods.size() && j < childPeriods.size(); i++, j++) { parentPeriod = parentPeriods.get(i); childPeriod = childPeriods.get(j); if (!parentPeriod.getStartDate().equals(childPeriod.getStartDate()) || !parentPeriod.getEndDate().equals(childPeriod.getEndDate())) { retval = new ProposalHierarchyErrorDto(ERROR_BUDGET_PERIOD_DURATION_INCONSISTENT, childProposal.getProposalNumber()); break; } } if (retval == null && !allowEndDateChange && (j < childPeriods.size() || childProposal.getRequestedEndDateInitial().after(hierarchyProposal.getRequestedEndDateInitial()))) { retval = new ProposalHierarchyErrorDto(QUESTION_EXTEND_PROJECT_DATE_CONFIRM, childProposal.getProposalNumber()); } } return retval; } private int getCorrespondingParentPeriod(Budget parentBudget, Budget childBudget) { int correspondingStart = -1; // using start date of first period as start date and end date of last period // as end because budget start and end are not particularly reliable Date childStart = childBudget.getBudgetPeriod(0).getStartDate(); Date parentStart = parentBudget.getBudgetPeriod(0).getStartDate(); Date parentEnd = parentBudget.getBudgetPeriod(parentBudget.getBudgetPeriods().size()-1).getEndDate(); // check that child budget starts somewhere during parent budget if (childStart.compareTo(parentStart) >= 0 && childStart.compareTo(parentEnd) < 0) { // check that child budget starts on one of the budget period starts List<BudgetPeriod> parentPeriods = parentBudget.getBudgetPeriods(); for (int i=0; i<parentPeriods.size(); i++) { if (childStart.equals(parentPeriods.get(i).getStartDate())) { correspondingStart = i; break; } } } return correspondingStart; } private void removeChildElements(DevelopmentProposal parentProposal, Budget parentBudget, String childProposalNumber) { List<PropScienceKeyword> keywords = parentProposal.getPropScienceKeywords(); for (int i=keywords.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, keywords.get(i).getHierarchyProposalNumber())) { keywords.remove(i); } } List<ProposalSpecialReview> reviews = parentProposal.getPropSpecialReviews(); for (int i=reviews.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, reviews.get(i).getHierarchyProposalNumber())) { reviews.remove(i); } } List<Narrative> narratives = parentProposal.getNarratives(); for (int i=narratives.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, narratives.get(i).getHierarchyProposalNumber())) { narratives.remove(i); } } List<ProposalPerson> persons = parentProposal.getProposalPersons(); for (int i=persons.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, persons.get(i).getHierarchyProposalNumber())) { persons.remove(i); } } List<BudgetSubAwards> subAwards = parentBudget.getBudgetSubAwards(); for (int i=subAwards.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, subAwards.get(i).getHierarchyProposalNumber())) { subAwards.remove(i); } } BudgetPersonnelBudgetService budgetPersonnelBudgetService = KraServiceLocator.getService(BudgetPersonnelBudgetService.class); List<BudgetPeriod> periods = parentBudget.getBudgetPeriods(); List<BudgetLineItem> lineItems; List<BudgetPersonnelDetails> personnelDetailsList; BudgetPeriod period = null; BudgetLineItem lineItem = null; for (int i = periods.size()-1; i>=0; i--) { period = periods.get(i); lineItems = period.getBudgetLineItems(); for (int j = lineItems.size()-1; j>=0; j--) { lineItem = lineItems.get(j); if (StringUtils.equals(childProposalNumber, lineItem.getHierarchyProposalNumber())) { personnelDetailsList = lineItem.getBudgetPersonnelDetailsList(); for (int k = personnelDetailsList.size()-1; k>=0; k--) { budgetPersonnelBudgetService.deleteBudgetPersonnelDetails(parentBudget, i, j, k); } lineItems.remove(j); parentBudget.setBudgetLineItemDeleted(true); } } if (lineItems.isEmpty()) { periods.remove(period); } } List<BudgetPerson> budgetPersons = parentBudget.getBudgetPersons(); for (int i=budgetPersons.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, budgetPersons.get(i).getHierarchyProposalNumber())) { budgetPersonnelBudgetService.deleteBudgetPersonnelDetailsForPerson(parentBudget, budgetPersons.get(i)); budgetPersons.remove(i); } } } private void prepareHierarchySync(DevelopmentProposal hierarchyProposal) { prepareHierarchySync(hierarchyProposal.getProposalDocument()); } private void prepareHierarchySync(ProposalDevelopmentDocument pdDoc) { pdDoc.refreshReferenceObject("documentNextvalues"); } private void finalizeHierarchySync(ProposalDevelopmentDocument pdDoc) throws ProposalHierarchyException { pdDoc.refreshReferenceObject("budgetDocumentVersions"); try { documentService.saveDocument(pdDoc); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } } private void finalizeHierarchySync(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { businessObjectService.save(hierarchyProposal.getProposalDocument().getDocumentNextvalues()); businessObjectService.save(hierarchyProposal); } private void copyInitialAttachments(DevelopmentProposal srcProposal, DevelopmentProposal destProposal) { String instituteNarrativeTypeGroup = parameterService.getParameterValue(ProposalDevelopmentDocument.class, PARAMETER_NAME_INSTITUTE_NARRATIVE_TYPE_GROUP); ProposalPersonBiography destPropPersonBio; ProposalPerson srcPerson = null; ProposalPerson destPerson = null; for (ProposalPersonBiography srcPropPersonBio : srcProposal.getPropPersonBios()) { for (ProposalPerson person : srcProposal.getProposalPersons()) { if (person.getProposalPersonNumber().equals(srcPropPersonBio.getProposalPersonNumber())) { srcPerson = person; break; } } for (ProposalPerson person : destProposal.getProposalPersons()) { if (person.equals(srcPerson)) { destPerson = person; break; } } loadBioContent(srcPropPersonBio); destPropPersonBio = (ProposalPersonBiography)ObjectUtils.deepCopy(srcPropPersonBio); destPropPersonBio.setProposalPersonNumber(destPerson.getProposalPersonNumber()); destPropPersonBio.setPersonId(destPerson.getPersonId()); destPropPersonBio.setRolodexId(destPerson.getRolodexId()); propPersonBioService.addProposalPersonBiography(destProposal.getProposalDocument(), destPropPersonBio); } Narrative destNarrative; for (Narrative srcNarrative : srcProposal.getNarratives()) { if (StringUtils.equalsIgnoreCase(srcNarrative.getNarrativeType().getAllowMultiple(), "N") && !srcProposal.getInstituteAttachments().contains(srcNarrative) && !StringUtils.equalsIgnoreCase(srcNarrative.getNarrativeType().getNarrativeTypeGroup(), instituteNarrativeTypeGroup)) { loadAttachmentContent(srcNarrative); destNarrative = (Narrative)ObjectUtils.deepCopy(srcNarrative); destNarrative.setModuleStatusCode("I"); narrativeService.addNarrative(destProposal.getProposalDocument(), destNarrative); } } } private void loadAttachmentContent(Narrative narrative){ Map<String,String> primaryKey = new HashMap<String,String>(); primaryKey.put("proposalNumber", narrative.getProposalNumber()); primaryKey.put("moduleNumber", narrative.getModuleNumber()+""); NarrativeAttachment attachment = (NarrativeAttachment)businessObjectService.findByPrimaryKey(NarrativeAttachment.class, primaryKey); narrative.getNarrativeAttachmentList().clear(); narrative.getNarrativeAttachmentList().add(attachment); } private void loadBioContent(ProposalPersonBiography bio){ Map<String,String> primaryKey = new HashMap<String,String>(); primaryKey.put("proposalNumber", bio.getProposalNumber()); primaryKey.put("biographyNumber", bio.getBiographyNumber()+""); primaryKey.put("proposalPersonNumber", bio.getProposalPersonNumber()+""); ProposalPersonBiographyAttachment attachment = (ProposalPersonBiographyAttachment)businessObjectService.findByPrimaryKey(ProposalPersonBiographyAttachment.class, primaryKey); bio.getPersonnelAttachmentList().clear(); bio.getPersonnelAttachmentList().add(attachment); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getHierarchyChildRouteStatus(java.lang.String, java.lang.String) */ public String getHierarchyChildRouteStatus( String oldStatus, String newStatus) { LOG.info( String.format( "Route status change %s:%s",oldStatus,newStatus)); String retCd = null; if( StringUtils.equals(newStatus,KEWConstants.ROUTE_HEADER_ENROUTE_CD) && ( StringUtils.equals( oldStatus, KEWConstants.ROUTE_HEADER_INITIATED_CD) || StringUtils.equals(oldStatus, KEWConstants.ROUTE_HEADER_SAVED_CD) || StringUtils.equals(KEWConstants.ROUTE_HEADER_ENROUTE_CD, oldStatus)) ) { retCd = renderMessage( HIERARCHY_CHILD_ENROUTE_APPSTATUS ); } else if ( StringUtils.equals(newStatus, KEWConstants.ROUTE_HEADER_FINAL_CD)) { retCd = renderMessage( HIERARCHY_CHILD_FINAL_APPSTATUS ); } else if( StringUtils.equals( newStatus, KEWConstants.ROUTE_HEADER_DISAPPROVED_CD )) { retCd = renderMessage( HIERARCHY_CHILD_DISAPPROVE_APPSTATUS ); } else if( StringUtils.equals( newStatus, KEWConstants.ROUTE_HEADER_CANCEL_CD ) ) { retCd = renderMessage( HIERARCHY_CHILD_CANCEL_APPSTATUS ); } else { LOG.warn(String.format("Do not know how to calculate hierarchy child status for %s to %s",oldStatus,newStatus) ); } if( LOG.isDebugEnabled() ) LOG.debug(String.format("Route status for children:%s",retCd )); return retCd; } /** * Creates a hash of the data pertinent to a hierarchy for comparison during hierarchy syncing. */ private int computeHierarchyHashCode(DevelopmentProposal proposal, Budget budget) { int prime = 31; int result = 1; KraServiceLocator.getService(BudgetCalculationService.class).calculateBudget(budget); KraServiceLocator.getService(BudgetCalculationService.class).calculateBudgetSummaryTotals(budget); for (ProposalPerson person : proposal.getProposalPersons()) { result = prime * result + person.hashCode(); } for (Narrative narrative : proposal.getNarratives()) { result = prime * result + narrative.hierarchyHashCode(); } for (PropScienceKeyword keyword : proposal.getPropScienceKeywords()) { result = prime * result + keyword.getScienceKeywordCode().hashCode(); } for (ProposalSpecialReview review : proposal.getPropSpecialReviews()) { result = prime * result + review.hierarchyHashCode(); } result = prime * result + budget.getBudgetSummaryTotals().hashCode(); return result; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getChildProposalDevelopmentDocuments(java.lang.String) */ public List<ProposalDevelopmentDocument> getChildProposalDevelopmentDocuments(String parentProposalNumber) throws ProposalHierarchyException { List<ProposalDevelopmentDocument> outList = new ArrayList<ProposalDevelopmentDocument>(); for( DevelopmentProposal child : getHierarchyChildren(parentProposalNumber)) { try { outList.add( (ProposalDevelopmentDocument)documentService.getByDocumentHeaderId( child.getProposalDocument().getDocumentNumber() ) ); } catch (WorkflowException e) { LOG.error( String.format( "Could not find document for child proposal number %s", parentProposalNumber, child.getProposalNumber() ), e); throw new ProposalHierarchyException( String.format( "Could not find document for child proposal number %s", parentProposalNumber, child.getProposalNumber() ), e ); } } return outList; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getHierarchyChildren(java.lang.String) */ public List<DevelopmentProposal> getHierarchyChildren(String parentProposalNumber) { List<DevelopmentProposal> children = new ArrayList<DevelopmentProposal>(); for( String childProposalNumber : proposalHierarchyDao.getHierarchyChildProposalNumbers(parentProposalNumber)) { children.add(getDevelopmentProposal(childProposalNumber)); } return children; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getParentWorkflowStatus(org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal) */ public KualiWorkflowDocument getParentWorkflowDocument(ProposalDevelopmentDocument child) throws ProposalHierarchyException { return getParentDocument( child ).getDocumentHeader().getWorkflowDocument(); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getParentDocument(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument) */ public ProposalDevelopmentDocument getParentDocument(ProposalDevelopmentDocument child) throws ProposalHierarchyException { try { DevelopmentProposal parentProposal = getHierarchy(child.getDevelopmentProposal().getHierarchyParentProposalNumber()); String parentDocumentNumber = parentProposal.getProposalDocument().getDocumentNumber(); return (ProposalDevelopmentDocument)documentService.getByDocumentHeaderId(parentDocumentNumber); } catch (WorkflowException e) { LOG.error( "Workflow exception thrown getting hierarchy routing status.", e ); throw new ProposalHierarchyException( String.format("Could not lookup hierarchy workflow status for child:%s",child.getDocumentHeader().getDocumentNumber()),e); } } /** * Reject a proposal by sending it to the first node ( as named by PROPOSALDEVELOPMENTDOCUMENT_KEW_INITIAL_NODE_NAME ) * @param proposalDoc The ProposalDevelopmentDocument that should be rejected. * @param appDocStatus the application status to set in the workflow document. * @param principalName the principal name we are rejecting the document as. * @param appDocStatus the application document status to apply ( does not apply if null ) * @throws WorkflowException */ private void rejectProposal( ProposalDevelopmentDocument proposalDoc, String reason, String principalName, String appDocStatus ) throws WorkflowException { WorkflowDocument workflowDocument = new WorkflowDocument(identityManagementService.getPrincipalByPrincipalName(principalName).getPrincipalId(), proposalDoc.getDocumentHeader().getWorkflowDocument().getRouteHeaderId()); workflowDocument.returnToPreviousNode(reason, getProposalDevelopmentInitialNodeName() ); workflowDocument.updateAppDocStatus( appDocStatus ); } /** * Reject an entire proposal hierarchy. This works by first rejecting each child, and then rejecting the parent. * @param hierarchyParent The hierarchy to reject * @param reason the reason to be applied to the annotation field. The reason will be pre-pended with static text indicating if it was a child or the parent. * @param principalName the name of the principal that is rejecting the document. * @throws ProposalHierarchyException If hierarchyParent is not a hierarchy, or there was a problem rejecting one of the documents. */ private void rejectProposalHierarchy(ProposalDevelopmentDocument hierarchyParent, String reason, String principalName ) throws ProposalHierarchyException { //1. reject the parent. try { rejectProposal( hierarchyParent, renderMessage( PROPOSAL_ROUTING_REJECTED_ANNOTATION, reason ), principalName, renderMessage( HIERARCHY_REJECTED_APPSTATUS ) ); } catch (WorkflowException e) { throw new ProposalHierarchyException( String.format( "WorkflowException encountered rejecting proposal hierarchy parent %s", hierarchyParent.getDevelopmentProposal().getProposalNumber() ),e); } //2. Try to reject all of the children. for( ProposalDevelopmentDocument child : getChildProposalDevelopmentDocuments(hierarchyParent.getDevelopmentProposal().getProposalNumber())) { try { rejectProposal( child, renderMessage( HIERARCHY_ROUTING_PARENT_REJECTED_ANNOTATION, reason ), KEWConstants.SYSTEM_USER, renderMessage( HIERARCHY_CHILD_REJECTED_APPSTATUS ) ); } catch (WorkflowException e) { throw new ProposalHierarchyException( String.format( "WorkflowException encountered rejecting child document %s", child.getDevelopmentProposal().getProposalNumber()), e ); } } } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#rejectProposalDevelopmentDocument(java.lang.String, java.lang.String) */ public void rejectProposalDevelopmentDocument( String proposalNumber, String reason, String principalName ) throws WorkflowException, ProposalHierarchyException { DevelopmentProposal pbo = getDevelopmentProposal(proposalNumber); ProposalDevelopmentDocument pDoc = (ProposalDevelopmentDocument)documentService.getByDocumentHeaderId(getDevelopmentProposal(proposalNumber).getProposalDocument().getDocumentNumber()); if( !pbo.isInHierarchy() ) { rejectProposal( pDoc, renderMessage( PROPOSAL_ROUTING_REJECTED_ANNOTATION, reason ), principalName, renderMessage( HIERARCHY_REJECTED_APPSTATUS ) ); } else if ( pbo.isParent() ) { rejectProposalHierarchy( pDoc, reason, principalName ); } else { //it is a child or in some unknown state, either way we do not support rejecting it. throw new UnsupportedOperationException( String.format( "Cannot reject proposal %s it is a hierarchy child or ", proposalNumber )); } } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getProposalDevelopmentInitialNodeName() */ public String getProposalDevelopmentInitialNodeName() { DocumentTypeService dService = KEWServiceLocator.getDocumentTypeService(); DocumentTypeDTO proposalDevDocType = dService.getDocumentTypeVO("ProposalDevelopmentDocument"); ProcessDTO p = proposalDevDocType.getRoutePath().getPrimaryProcess(); return p.getInitialRouteNode().getRouteNodeName(); } /** * * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#isProposalOnInitialRouteNode(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument) */ public boolean isProposalOnInitialRouteNode( ProposalDevelopmentDocument document ) { boolean ret = false; try { if( ArrayUtils.contains(document.getDocumentHeader().getWorkflowDocument().getNodeNames(), getProposalDevelopmentInitialNodeName())) ret = true; } catch ( WorkflowException we ) { throw new RuntimeException( String.format( "Could not get node names for document: %s", document.getDocumentNumber()), we ); } return ret; } /** * Based on the hierarchy, and route status change of the parent, calculate what route action should be taken on the children. * @param hierarchy the heirarchy being routed * @param dto the route status change information. * @return The route action to take on the children. */ private String calculateChildRouteStatus( ProposalDevelopmentDocument hierarchy, DocumentRouteStatusChangeDTO dto ) { String parentOldStatus = dto.getOldRouteStatus(); String parentNewStatus = dto.getNewRouteStatus(); String newChildStatusTarget = ""; if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_INITIATED_CD)) { // nothing to do here. } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_SAVED_CD)) { // previous status was saved newChildStatusTarget = parentNewStatus; if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_ENROUTE_CD)) { // nothing to do } else if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_CANCEL_CD)) { // nothing to do. } else { throw new UnsupportedOperationException(String.format( "Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus, parentNewStatus)); } } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_ENROUTE_CD)) { // we are moving from enroute to some other state. if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_CANCEL_CD) || StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_DISAPPROVED_CD)) { newChildStatusTarget = parentNewStatus; } else if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_APPROVED_CD)) { // nothing to do here, wait for the document to go final. } else if( StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_ENROUTE_CD)) { //special case, document has been rejected and being approved again to simulate entry into workflow. //this value will trigger an approve. newChildStatusTarget = KEWConstants.ROUTE_HEADER_ENROUTE_CD; } else { throw new UnsupportedOperationException(String.format("Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus,parentNewStatus)); } } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_APPROVED_CD)) { // nothing to do here. } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_PROCESSED_CD)) { if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_FINAL_CD)) { newChildStatusTarget = parentNewStatus; } else { throw new UnsupportedOperationException(String.format("Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus,parentNewStatus)); } } else { throw new UnsupportedOperationException(String.format( "Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus,parentNewStatus)); } return newChildStatusTarget; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#routeHierarchyChildren(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument, org.kuali.rice.kew.dto.DocumentRouteStatusChangeDTO, java.lang.String) */ public void routeHierarchyChildren(ProposalDevelopmentDocument proposalDevelopmentDocument, DocumentRouteStatusChangeDTO dto ) throws ProposalHierarchyException { String childStatusTarget = calculateChildRouteStatus(proposalDevelopmentDocument, dto ); WorkflowDocument workdoc; ProposalDevelopmentDocument child = null; try { LOG.info( IdentityManagementService.class ); for (ProposalDevelopmentDocument c : getChildProposalDevelopmentDocuments(proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber() )) { child = c; if (!StringUtils.equals("", childStatusTarget)) { if (StringUtils.equals(KEWConstants.ROUTE_HEADER_ENROUTE_CD, childStatusTarget)) { //The user currently must initially route the child documents in order for them to hold in the system users action list. workdoc = new WorkflowDocument(child.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId(), child.getDocumentHeader().getWorkflowDocument().getRouteHeaderId() ); workdoc.updateAppDocStatus(getHierarchyChildRouteStatus( dto.getOldRouteStatus(), dto.getNewRouteStatus() )); if( !workdoc.stateIsEnroute() ) { workdoc.routeDocument(renderMessage( HIERARCHY_ROUTING_PARENT_SUBMITTED_ANNOTATION )); } else { //this means the status change is actually in the form of an approve action on a document that was moved back to the initial node. //we need to do an approval. workdoc.approve(renderMessage( HIERARCHY_ROUTING_PARENT_RESUBMITTED_ANNOTATION )); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_ENROUTE_APPSTATUS ) ); } } else { workdoc = new WorkflowDocument( identityManagementService.getPrincipalByPrincipalName(KNSConstants.SYSTEM_USER ).getPrincipalId(),child.getDocumentHeader().getWorkflowDocument().getRouteHeaderId() ); workdoc.updateAppDocStatus(getHierarchyChildRouteStatus( dto.getOldRouteStatus(), dto.getNewRouteStatus() )); if (StringUtils.equals(KEWConstants.ROUTE_HEADER_CANCEL_CD,childStatusTarget)) { workdoc.cancel(renderMessage( HIERARCHY_ROUTING_PARENT_CANCELLED_ANNOTATION)); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_CANCEL_APPSTATUS )); } else if (StringUtils.equals(KEWConstants.ROUTE_HEADER_FINAL_CD, childStatusTarget)) { workdoc.approve(renderMessage( HIERARCHY_ROUTING_PARENT_APPROVED_ANNOTATION )); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_FINAL_APPSTATUS )); } else if (StringUtils.equals(KEWConstants.ROUTE_HEADER_DISAPPROVED_CD, childStatusTarget)) { workdoc.disapprove(renderMessage( HIERARCHY_ROUTING_PARENT_DISAPPROVED_ANNOTATION )); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_DISAPPROVE_APPSTATUS )); } else { throw new UnsupportedOperationException(String.format("Do not know how to handle new child status of %s", childStatusTarget)); } } } } } catch ( WorkflowException we ) { throw new ProposalHierarchyException( String.format( "WorkflowException encountrered while attempting to route child proposal %s ( document #%s ) of proposal hierarchy %s ( document #%s )", child.getDevelopmentProposal().getProposalNumber(), child.getDocumentNumber(), proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber(), proposalDevelopmentDocument.getDocumentNumber() ), we); } } public void calculateAndSetProposalAppDocStatus( ProposalDevelopmentDocument doc, DocumentRouteStatusChangeDTO dto ) throws ProposalHierarchyException { String principalId = GlobalVariables.getUserSession().getPrincipalId(); if( StringUtils.equals( dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_ENROUTE_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_ENROUTE_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_CANCEL_CD)) { updateAppDocStatus( doc, principalId, HIERARCHY_CANCEL_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_DISAPPROVED_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_DISAPPROVE_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_FINAL_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_FINAL_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_PROCESSED_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_PROCESSED_APPSTATUS ) ; } } public void updateAppDocStatus( ProposalDevelopmentDocument doc, String principalId, String newStatus ) throws ProposalHierarchyException { try { WorkflowDocument wdoc = new WorkflowDocument(principalId, doc.getDocumentHeader().getWorkflowDocument().getRouteHeaderId() ); wdoc.updateAppDocStatus(renderMessage( newStatus )); } catch (WorkflowException e) { throw new ProposalHierarchyException( String.format( "WorkflowException encountrered while attempting to update App Doc Status of proposal %s ( document #%s )", doc.getDevelopmentProposal().getProposalNumber(), doc.getDocumentNumber() ), e); } } public boolean allChildBudgetsAreComplete(String parentProposalNumber) { boolean retval = true; String completeCode = parameterService.getParameterValue(BudgetDocument.class, Constants.BUDGET_STATUS_COMPLETE_CODE); for (ProposalBudgetStatus status : proposalHierarchyDao.getHierarchyChildProposalBudgetStatuses(parentProposalNumber)) { if (!StringUtils.equalsIgnoreCase(completeCode, status.getBudgetStatusCode())) { retval = false; break; } } return retval; } private boolean rolesAreSimilar(ProposalPerson person1, ProposalPerson person2) { boolean isInvestigator1 = StringUtils.equals(person1.getProposalPersonRoleId(), Constants.PRINCIPAL_INVESTIGATOR_ROLE) || StringUtils.equals(person1.getProposalPersonRoleId(), Constants.CO_INVESTIGATOR_ROLE); boolean isInvestigator2 = StringUtils.equals(person2.getProposalPersonRoleId(), Constants.PRINCIPAL_INVESTIGATOR_ROLE) || StringUtils.equals(person2.getProposalPersonRoleId(), Constants.CO_INVESTIGATOR_ROLE); return isInvestigator1 == isInvestigator2; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getHierarchyProposalSummaries(java.lang.String) */ public List<HierarchyProposalSummary> getHierarchyProposalSummaries(String proposalNumber) throws ProposalHierarchyException { DevelopmentProposal proposal = getDevelopmentProposal(proposalNumber); List<HierarchyProposalSummary> summaries = new ArrayList<HierarchyProposalSummary>(); List<String> proposalNumbers = new ArrayList<String>(); if (proposal.isParent()) { proposalNumbers.add(proposalNumber); } else if (proposal.isChild()) { proposalNumbers.add(proposal.getHierarchyParentProposalNumber()); } else { throw new ProposalHierarchyException("Proposal " + proposalNumber + " is not a member of a hierarchy."); } proposalNumbers.addAll(proposalHierarchyDao.getHierarchyChildProposalNumbers(proposalNumbers.get(0))); HierarchyProposalSummary summary; for (String number : proposalNumbers) { summary = new HierarchyProposalSummary(); summary.setProposalNumber(number); if (!StringUtils.equals(number, proposalNumbers.get(0))) { summary.setSynced(isSynchronized(number)); } summaries.add(summary); } return summaries; } public boolean validateRemovePermissions(DevelopmentProposal childProposal, String principalId) { boolean valid = true; valid &= kraAuthorizationService.hasPermission(principalId, childProposal.getProposalDocument(), PermissionConstants.MAINTAIN_PROPOSAL_HIERARCHY); try { valid &= kraAuthorizationService.hasPermission(principalId, getHierarchy(childProposal.getHierarchyParentProposalNumber()).getProposalDocument(), PermissionConstants.MAINTAIN_PROPOSAL_HIERARCHY); } catch (ProposalHierarchyException e) { valid = false; } return valid; } /** * Gets the configurationService attribute. * @return Returns the configurationService. */ public KualiConfigurationService getConfigurationService() { return configurationService; } /** * Sets the configurationService attribute value. * @param configurationService The configurationService to set. */ public void setConfigurationService(KualiConfigurationService configurationService) { this.configurationService = configurationService; } private String renderMessage( String key, String... params ) { String msg = configurationService.getPropertyString(key); for (int i = 0; i < params.length; i++) { msg = replace(msg, "{" + i + "}", params[i]); } return msg; } }
src/main/java/org/kuali/kra/proposaldevelopment/hierarchy/service/impl/ProposalHierarchyServiceImpl.java
/* * Copyright 2006-2008 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.proposaldevelopment.hierarchy.service.impl; import static org.apache.commons.lang.StringUtils.replace; import static org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyKeyConstants.*; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kuali.kra.budget.BudgetDecimal; import org.kuali.kra.budget.calculator.BudgetCalculationService; import org.kuali.kra.budget.core.Budget; import org.kuali.kra.budget.core.BudgetAssociate; import org.kuali.kra.budget.core.BudgetService; import org.kuali.kra.budget.core.CostElement; import org.kuali.kra.budget.document.BudgetDocument; import org.kuali.kra.budget.nonpersonnel.BudgetLineItem; import org.kuali.kra.budget.parameters.BudgetPeriod; import org.kuali.kra.budget.personnel.BudgetPerson; import org.kuali.kra.budget.personnel.BudgetPersonnelBudgetService; import org.kuali.kra.budget.personnel.BudgetPersonnelDetails; import org.kuali.kra.budget.versions.BudgetDocumentVersion; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.PermissionConstants; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.proposaldevelopment.bo.CongressionalDistrict; import org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal; import org.kuali.kra.proposaldevelopment.bo.Narrative; import org.kuali.kra.proposaldevelopment.bo.NarrativeAttachment; import org.kuali.kra.proposaldevelopment.bo.PropScienceKeyword; import org.kuali.kra.proposaldevelopment.bo.ProposalBudgetStatus; import org.kuali.kra.proposaldevelopment.bo.ProposalPerson; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonBiography; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonBiographyAttachment; import org.kuali.kra.proposaldevelopment.bo.ProposalPersonUnit; import org.kuali.kra.proposaldevelopment.bo.ProposalSite; import org.kuali.kra.proposaldevelopment.bo.ProposalSpecialReview; import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwardAttachment; import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwardFiles; import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwards; import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument; import org.kuali.kra.proposaldevelopment.hierarchy.HierarchyBudgetTypeConstants; import org.kuali.kra.proposaldevelopment.hierarchy.HierarchyStatusConstants; import org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyErrorDto; import org.kuali.kra.proposaldevelopment.hierarchy.ProposalHierarchyException; import org.kuali.kra.proposaldevelopment.hierarchy.bo.HierarchyProposalSummary; import org.kuali.kra.proposaldevelopment.hierarchy.dao.ProposalHierarchyDao; import org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService; import org.kuali.kra.proposaldevelopment.service.NarrativeService; import org.kuali.kra.proposaldevelopment.service.ProposalPersonBiographyService; import org.kuali.kra.proposaldevelopment.service.ProposalStateService; import org.kuali.kra.service.DeepCopyPostProcessor; import org.kuali.kra.service.KraAuthorizationService; import org.kuali.rice.kew.doctype.service.DocumentTypeService; import org.kuali.rice.kew.dto.DocumentRouteStatusChangeDTO; import org.kuali.rice.kew.dto.DocumentTypeDTO; import org.kuali.rice.kew.dto.ProcessDTO; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.service.WorkflowDocument; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kim.service.IdentityManagementService; import org.kuali.rice.kns.bo.DocumentHeader; import org.kuali.rice.kns.document.Document; import org.kuali.rice.kns.service.BusinessObjectService; import org.kuali.rice.kns.service.DocumentService; import org.kuali.rice.kns.service.KualiConfigurationService; import org.kuali.rice.kns.service.ParameterService; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.KNSConstants; import org.kuali.rice.kns.util.ObjectUtils; import org.kuali.rice.kns.web.struts.form.KualiForm; import org.kuali.rice.kns.workflow.service.KualiWorkflowDocument; import org.kuali.rice.kns.workflow.service.WorkflowDocumentService; import org.springframework.transaction.annotation.Transactional; /** * This class... */ @Transactional public class ProposalHierarchyServiceImpl implements ProposalHierarchyService { private static final Log LOG = LogFactory.getLog(ProposalHierarchyServiceImpl.class); private BusinessObjectService businessObjectService; private DocumentService documentService; private KraAuthorizationService kraAuthorizationService; private ProposalHierarchyDao proposalHierarchyDao; private NarrativeService narrativeService; private BudgetService budgetService; private ProposalPersonBiographyService propPersonBioService; private ParameterService parameterService; private IdentityManagementService identityManagementService; private ProposalStateService proposalStateService; private KualiConfigurationService configurationService; /** * Sets the proposalStateService attribute value. * @param proposalStateService The ProposalStateService to set. */ public void setProposalStateService(ProposalStateService proposalStateService) { this.proposalStateService = proposalStateService; } /** * Sets the identityManagerService attribute value. * @param identityManagerService The IdentityManagerService to set. */ public void setIdentityManagementService(IdentityManagementService identityManagerService) { this.identityManagementService = identityManagerService; } /** * Sets the businessObjectService attribute value. * @param businessObjectService The businessObjectService to set. */ public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } /** * Sets the documentService attribute value. * @param documentService The documentService to set. */ public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } /** * Sets the kraAuthorizationService attribute value. * @param kraAuthorizationService The kraAuthorizationService to set. */ public void setKraAuthorizationService(KraAuthorizationService kraAuthorizationService) { this.kraAuthorizationService = kraAuthorizationService; } /** * Sets the proposalHierarchyDao attribute value. * @param proposalHierarchyDao The proposalHierarchyDao to set. */ public void setProposalHierarchyDao(ProposalHierarchyDao proposalHierarchyDao) { this.proposalHierarchyDao = proposalHierarchyDao; } /** * Sets the narrativeService attribute value. * @param narrativeService The narrativeService to set. */ public void setNarrativeService(NarrativeService narrativeService) { this.narrativeService = narrativeService; } /** * Sets the budgetService attribute value. * @param budgetService The budgetService to set. */ public void setBudgetService(BudgetService budgetService) { this.budgetService = budgetService; } /** * Sets the propPersonBioService attribute value. * @param propPersonBioService The propPersonBioService to set. */ public void setPropPersonBioService(ProposalPersonBiographyService propPersonBioService) { this.propPersonBioService = propPersonBioService; } /** * Sets the parameterService attribute value. * @param parameterService The parameterService to set. */ public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#createHierarchy(java.lang.String) */ public String createHierarchy(DevelopmentProposal initialChild) throws ProposalHierarchyException { LOG.info(String.format("***Create Hierarchy using Proposal #%s", initialChild.getProposalNumber())); if (initialChild.isInHierarchy()) { throw new ProposalHierarchyException("Cannot create hierarchy: proposal " + initialChild.getProposalNumber() + " is already a member of a hierarchy."); } // create a new proposal document ProposalDevelopmentDocument newDoc; // manually assembling a new PDDoc here because the DocumentService will deny initiator permission without context // since a person with MAINTAIN_PROPOSAL_HIERARCHY permission is allowed to initiate IF they are creating a parent // we circumvent the initiator step altogether. try { KualiWorkflowDocument workflowDocument = KraServiceLocator.getService(WorkflowDocumentService.class).createWorkflowDocument("ProposalDevelopmentDocument", GlobalVariables.getUserSession().getPerson()); GlobalVariables.getUserSession().setWorkflowDocument(workflowDocument); DocumentHeader documentHeader = new DocumentHeader(); documentHeader.setWorkflowDocument(workflowDocument); documentHeader.setDocumentNumber(workflowDocument.getRouteHeaderId().toString()); newDoc = new ProposalDevelopmentDocument(); newDoc.setDocumentHeader(documentHeader); newDoc.setDocumentNumber(documentHeader.getDocumentNumber()); } catch (WorkflowException x) { throw new ProposalHierarchyException("Error creating new document: " + x); } // copy the initial information to the new parent proposal DevelopmentProposal hierarchy = newDoc.getDevelopmentProposal(); copyInitialData(hierarchy, initialChild); hierarchy.setHierarchyStatus(HierarchyStatusConstants.Parent.code()); String docDescription = initialChild.getProposalDocument().getDocumentHeader() .getDocumentDescription(); newDoc.getDocumentHeader().setDocumentDescription(docDescription); // persist the document and add a budget try { documentService.saveDocument(newDoc); budgetService.addBudgetVersion(newDoc, "Hierarchy Budget"); } catch (WorkflowException x) { throw new ProposalHierarchyException("Error saving new document: " + x); } LOG.info(String.format("***New Hierarchy Parent (#%s) budget created", hierarchy.getProposalNumber())); // add aggregator to the document String userId = GlobalVariables.getUserSession().getPrincipalId(); kraAuthorizationService.addRole(userId, RoleConstants.AGGREGATOR, newDoc); initializeBudget(hierarchy, initialChild); prepareHierarchySync(hierarchy); // link the child to the parent linkChild(hierarchy, initialChild, HierarchyBudgetTypeConstants.SubBudget.code()); setInitialPi(hierarchy, initialChild); copyInitialAttachments(initialChild, hierarchy); aggregateHierarchy(hierarchy); LOG.info(String.format("***Initial Child (#%s) linked to Parent (#%s)", initialChild.getProposalNumber(), hierarchy.getProposalNumber())); finalizeHierarchySync(hierarchy); // return the parent id LOG.info(String.format("***Hierarchy creation (#%s) complete", hierarchy.getProposalNumber())); return hierarchy.getProposalNumber(); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#linkToHierarchy(org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal, org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal, java.lang.String) */ public void linkToHierarchy(DevelopmentProposal hierarchyProposal, DevelopmentProposal newChildProposal, String hierarchyBudgetTypeCode) throws ProposalHierarchyException { LOG.info(String.format("***Linking Child (#%s) linked to Parent (#%s)", newChildProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); if (!hierarchyProposal.isParent()) { throw new ProposalHierarchyException("Proposal " + hierarchyProposal.getProposalNumber() + " is not a hierarchy parent"); } if (newChildProposal.isInHierarchy()) { throw new ProposalHierarchyException("Proposal " + newChildProposal.getProposalNumber() + " is already a member of a hierarchy"); } prepareHierarchySync(hierarchyProposal); linkChild(hierarchyProposal, newChildProposal, hierarchyBudgetTypeCode); finalizeHierarchySync(hierarchyProposal); LOG.info(String.format("***Linking Child (#%s) linked to Parent (#%s) complete", newChildProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#removeFromHierarchy(java.lang.String) */ public void removeFromHierarchy(DevelopmentProposal childProposal) throws ProposalHierarchyException { String hierarchyProposalNumber = childProposal.getHierarchyParentProposalNumber(); DevelopmentProposal hierarchyProposal = getHierarchy(hierarchyProposalNumber); BudgetDocument<DevelopmentProposal> hierarchyBudgetDoc = getHierarchyBudget(hierarchyProposal); Budget hierarchyBudget = hierarchyBudgetDoc.getBudget(); LOG.info(String.format("***Removing Child (#%s) from Parent (#%s)", childProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); boolean isLast = proposalHierarchyDao.getHierarchyChildProposalNumbers(hierarchyProposalNumber).size()==1; childProposal.setHierarchyStatus(HierarchyStatusConstants.None.code()); childProposal.setHierarchyParentProposalNumber(null); removeChildElements(hierarchyProposal, hierarchyBudget, childProposal.getProposalNumber()); try { documentService.saveDocument(hierarchyBudgetDoc); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } if (isLast) { try { LOG.info(String.format("***Child (#%s) was last child, cancelling Parent (#%s)", childProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); businessObjectService.save(childProposal); Document doc = documentService.getByDocumentHeaderId(hierarchyProposal.getProposalDocument().getDocumentNumber()); documentService.cancelDocument(doc, "Removed last child from Proposal Hierarchy"); } catch (WorkflowException e) { throw new ProposalHierarchyException("Error cancelling empty parent proposal"); } } else { businessObjectService.save(childProposal); synchronizeAllChildren(hierarchyProposal); } LOG.info(String.format("***Removing Child (#%s) from Parent (#%s) complete", childProposal.getProposalNumber(), hierarchyProposal.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchySyncService#synchronizeAllChildren(java.lang.String) */ public void synchronizeAllChildren(ProposalDevelopmentDocument pdDoc) throws ProposalHierarchyException { prepareHierarchySync(pdDoc); synchronizeAll(pdDoc.getDevelopmentProposal()); finalizeHierarchySync(pdDoc); } private void synchronizeAllChildren(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { prepareHierarchySync(hierarchyProposal); synchronizeAll(hierarchyProposal); finalizeHierarchySync(hierarchyProposal); } private void synchronizeAll(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { boolean changed = false; DevelopmentProposal childProposal; LOG.info(String.format("***Synchronizing all Children of Parent (#%s)", hierarchyProposal.getProposalNumber())); if (!hierarchyProposal.isParent()) { throw new ProposalHierarchyException("Proposal " + hierarchyProposal.getProposalNumber() + " is not a hierarchy parent"); } for (String childProposalNumber : proposalHierarchyDao.getHierarchyChildProposalNumbers(hierarchyProposal.getProposalNumber())) { childProposal = getDevelopmentProposal(childProposalNumber); changed |= synchronizeChild(hierarchyProposal, childProposal); } if (changed) { aggregateHierarchy(hierarchyProposal); } LOG.info(String.format("***Synchronizing all Children of Parent (#%s) complete", hierarchyProposal.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchySyncService#synchronizeChild(java.lang.String) */ public void synchronizeChild(DevelopmentProposal childProposal) throws ProposalHierarchyException { DevelopmentProposal hierarchy = getHierarchy(childProposal.getHierarchyParentProposalNumber()); LOG.info(String.format("***Synchronizing Child (#%s) of Parent (#%s)", childProposal.getProposalNumber(), hierarchy.getProposalNumber())); prepareHierarchySync(hierarchy); boolean changed = synchronizeChild(hierarchy, childProposal); if (changed) { aggregateHierarchy(hierarchy); } finalizeHierarchySync(hierarchy); LOG.info(String.format("***Synchronizing Child (#%s) of Parent (#%s) complete", childProposal.getProposalNumber(), hierarchy.getProposalNumber())); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#lookupParent(org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal) */ public DevelopmentProposal lookupParent(DevelopmentProposal childProposal) throws ProposalHierarchyException { return getHierarchy(childProposal.getHierarchyParentProposalNumber()); } private void linkChild(DevelopmentProposal hierarchyProposal, DevelopmentProposal newChildProposal, String hierarchyBudgetTypeCode) throws ProposalHierarchyException { // set child to child status newChildProposal.setHierarchyStatus(HierarchyStatusConstants.Child.code()); newChildProposal.setHierarchyParentProposalNumber(hierarchyProposal.getProposalNumber()); newChildProposal.setHierarchyBudgetType(hierarchyBudgetTypeCode); // call synchronize synchronizeChild(hierarchyProposal, newChildProposal); // call aggregate aggregateHierarchy(hierarchyProposal); } private void copyInitialData(DevelopmentProposal hierarchyProposal, DevelopmentProposal srcProposal) throws ProposalHierarchyException { // Required fields for saving document hierarchyProposal.setSponsor(srcProposal.getSponsor()); hierarchyProposal.setSponsorCode(srcProposal.getSponsorCode()); hierarchyProposal.setProposalTypeCode(srcProposal.getProposalTypeCode()); hierarchyProposal.setRequestedStartDateInitial(srcProposal.getRequestedStartDateInitial()); hierarchyProposal.setRequestedEndDateInitial(srcProposal.getRequestedEndDateInitial()); hierarchyProposal.setOwnedByUnit(srcProposal.getOwnedByUnit()); hierarchyProposal.setOwnedByUnitNumber(srcProposal.getOwnedByUnitNumber()); hierarchyProposal.setActivityType(srcProposal.getActivityType()); hierarchyProposal.setActivityTypeCode(srcProposal.getActivityTypeCode()); hierarchyProposal.setTitle(srcProposal.getTitle()); // Sponsor & program information hierarchyProposal.setDeadlineDate(srcProposal.getDeadlineDate()); hierarchyProposal.setDeadlineType(srcProposal.getDeadlineType()); hierarchyProposal.setNoticeOfOpportunityCode(srcProposal.getNoticeOfOpportunityCode()); hierarchyProposal.setCfdaNumber(srcProposal.getCfdaNumber()); hierarchyProposal.setPrimeSponsorCode(srcProposal.getPrimeSponsorCode()); hierarchyProposal.setNsfCode(srcProposal.getNsfCode()); hierarchyProposal.setSponsorProposalNumber(srcProposal.getSponsorProposalNumber()); hierarchyProposal.setAgencyDivisionCode(srcProposal.getAgencyDivisionCode()); hierarchyProposal.setAgencyProgramCode(srcProposal.getAgencyProgramCode()); hierarchyProposal.setSubcontracts(srcProposal.getSubcontracts()); hierarchyProposal.setProgramAnnouncementNumber(srcProposal.getProgramAnnouncementNumber()); hierarchyProposal.setProgramAnnouncementTitle(srcProposal.getProgramAnnouncementTitle()); // Organization/location ProposalSite newSite; hierarchyProposal.getProposalSites().clear(); for (ProposalSite site : srcProposal.getProposalSites()) { newSite = (ProposalSite)ObjectUtils.deepCopy(site); newSite.setProposalNumber(null); newSite.setVersionNumber(null); for (CongressionalDistrict cd : newSite.getCongressionalDistricts()) { cd.setProposalNumber(null); cd.setCongressionalDistrictId(null); cd.setVersionNumber(null); } hierarchyProposal.addProposalSite(newSite); } // Delivery info hierarchyProposal.setMailBy(srcProposal.getMailBy()); hierarchyProposal.setMailType(srcProposal.getMailType()); hierarchyProposal.setMailAccountNumber(srcProposal.getMailAccountNumber()); hierarchyProposal.setNumberOfCopies(srcProposal.getNumberOfCopies()); hierarchyProposal.setMailingAddressId(srcProposal.getMailingAddressId()); hierarchyProposal.setMailDescription(srcProposal.getMailDescription()); } private boolean synchronizeChild(DevelopmentProposal hierarchyProposal, DevelopmentProposal childProposal) throws ProposalHierarchyException { String instituteNarrativeTypeGroup = parameterService.getParameterValue(ProposalDevelopmentDocument.class, PARAMETER_NAME_INSTITUTE_NARRATIVE_TYPE_GROUP); /* TODO restore code below after testing if (isSynchronized(childProposal.getProposalNumber())) { return false; } */ ProposalPerson pi = hierarchyProposal.getPrincipalInvestigator(); List<PropScienceKeyword> oldKeywords = new ArrayList<PropScienceKeyword>(); for (PropScienceKeyword keyword : hierarchyProposal.getPropScienceKeywords()) { if (StringUtils.equals(childProposal.getProposalNumber(), keyword.getHierarchyProposalNumber())) { oldKeywords.add(keyword); } } BudgetDocument<DevelopmentProposal> hierarchyBudgetDocument = getHierarchyBudget(hierarchyProposal); Budget hierarchyBudget = hierarchyBudgetDocument.getBudget(); BudgetDocument<DevelopmentProposal> childBudgetDocument = getFinalOrLatestChildBudget(childProposal); Budget childBudget = childBudgetDocument.getBudget(); ObjectUtils.materializeAllSubObjects(hierarchyBudget); ObjectUtils.materializeAllSubObjects(childBudget); childProposal.setHierarchyLastSyncHashCode(computeHierarchyHashCode(childProposal, childBudget)); removeChildElements(hierarchyProposal, hierarchyBudget, childProposal.getProposalNumber()); // copy PropScienceKeywords for (PropScienceKeyword keyword : childProposal.getPropScienceKeywords()) { PropScienceKeyword newKeyword = new PropScienceKeyword(hierarchyProposal.getProposalNumber(), keyword.getScienceKeyword()); int index = oldKeywords.indexOf(newKeyword); if (index > -1) { newKeyword = oldKeywords.get(index); } newKeyword.setHierarchyProposalNumber(childProposal.getProposalNumber()); hierarchyProposal.addPropScienceKeyword(newKeyword); } // copy PropSpecialReviews for(ProposalSpecialReview review : childProposal.getPropSpecialReviews()) { ProposalSpecialReview newReview = (ProposalSpecialReview)ObjectUtils.deepCopy(review); newReview.setProposalNumber(hierarchyProposal.getProposalNumber()); newReview.setSpecialReviewNumber(hierarchyProposal.getProposalDocument().getDocumentNextValue(Constants.PROPOSAL_SPECIALREVIEW_NUMBER)); newReview.setVersionNumber(null); newReview.setHierarchyProposalNumber(childProposal.getProposalNumber()); hierarchyProposal.getPropSpecialReviews().add(newReview); } // copy Narratives for (Narrative narrative : childProposal.getNarratives()) { if (!StringUtils.equalsIgnoreCase(narrative.getNarrativeType().getAllowMultiple(), "N") && !StringUtils.equalsIgnoreCase(narrative.getNarrativeType().getNarrativeTypeGroup(), instituteNarrativeTypeGroup)) { Map<String,String> primaryKey = new HashMap<String,String>(); primaryKey.put("proposalNumber", narrative.getProposalNumber()); primaryKey.put("moduleNumber", narrative.getModuleNumber()+""); NarrativeAttachment attachment = (NarrativeAttachment)businessObjectService.findByPrimaryKey(NarrativeAttachment.class, primaryKey); narrative.getNarrativeAttachmentList().clear(); narrative.getNarrativeAttachmentList().add(attachment); Narrative newNarrative = (Narrative)ObjectUtils.deepCopy(narrative); newNarrative.setVersionNumber(null); newNarrative.setHierarchyProposalNumber(childProposal.getProposalNumber()); narrativeService.addNarrative(hierarchyProposal.getProposalDocument(), newNarrative); } } // copy ProposalPersons int firstIndex, lastIndex; ProposalPerson firstInstance; for (ProposalPerson person : childProposal.getProposalPersons()) { firstIndex = hierarchyProposal.getProposalPersons().indexOf(person); lastIndex = hierarchyProposal.getProposalPersons().lastIndexOf(person); firstInstance = (firstIndex == -1) ? null : hierarchyProposal.getProposalPersons().get(firstIndex); if (firstIndex == -1 || (firstIndex == lastIndex && !rolesAreSimilar(person, firstInstance))) { ProposalPerson newPerson; newPerson = (ProposalPerson)ObjectUtils.deepCopy(person); newPerson.setProposalNumber(hierarchyProposal.getProposalNumber()); newPerson.getProposalPersonYnqs().clear(); newPerson.getCreditSplits().clear(); for (ProposalPersonUnit unit : newPerson.getUnits()) { unit.getCreditSplits().clear(); } newPerson.setProposalPersonNumber(null); newPerson.setVersionNumber(null); newPerson.setHierarchyProposalNumber(childProposal.getProposalNumber()); if (StringUtils.equalsIgnoreCase(person.getProposalPersonRoleId(), Constants.PRINCIPAL_INVESTIGATOR_ROLE)) { newPerson.setProposalPersonRoleId(Constants.CO_INVESTIGATOR_ROLE); } if (newPerson.equals(pi) && (firstIndex == -1 || !firstInstance.isInvestigator())) { newPerson.setProposalPersonRoleId(Constants.PRINCIPAL_INVESTIGATOR_ROLE); } hierarchyProposal.addProposalPerson(newPerson); } } businessObjectService.save(childProposal); LOG.info(String.format("***Beginning Hierarchy Budget Sync for Parent %s and Child %s", hierarchyProposal.getProposalNumber(), childProposal.getProposalNumber())); synchronizeChildBudget(hierarchyBudget, childBudget, childProposal.getProposalNumber(), childProposal.getHierarchyBudgetType()); if (hierarchyBudget.getEndDate().after(hierarchyProposal.getRequestedEndDateInitial())) { hierarchyProposal.setRequestedEndDateInitial(hierarchyBudget.getEndDate()); } if (childProposal.getRequestedEndDateInitial().after(hierarchyProposal.getRequestedEndDateInitial())) { hierarchyProposal.setRequestedEndDateInitial(childProposal.getRequestedEndDateInitial()); } try { documentService.saveDocument(hierarchyBudgetDocument); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } LOG.info(String.format("***Completed Hierarchy Budget Sync for Parent %s and Child %s", hierarchyProposal.getProposalNumber(), childProposal.getProposalNumber())); return true; } private void synchronizeChildBudget(Budget parentBudget, Budget childBudget, String childProposalNumber, String hierarchyBudgetTypeCode) throws ProposalHierarchyException { try { BudgetPerson newPerson; Map<Integer, BudgetPerson> personMap = new HashMap<Integer, BudgetPerson>(); for (BudgetPerson person : childBudget.getBudgetPersons()) { newPerson = (BudgetPerson) ObjectUtils.deepCopy(person); newPerson.setPersonSequenceNumber(parentBudget.getBudgetDocument().getHackedDocumentNextValue( Constants.PERSON_SEQUENCE_NUMBER)); // newPerson.setBudget(parentBudget); newPerson.setBudgetId(parentBudget.getBudgetId()); newPerson.setHierarchyProposalNumber(childProposalNumber); newPerson.setVersionNumber(null); parentBudget.addBudgetPerson(newPerson); personMap.put(person.getPersonSequenceNumber(), newPerson); } BudgetSubAwards newSubAwards; for (BudgetSubAwards childSubAwards : childBudget.getBudgetSubAwards()) { childSubAwards.refreshReferenceObject("budgetSubAwardAttachments"); childSubAwards.refreshReferenceObject("budgetSubAwardFiles"); newSubAwards = (BudgetSubAwards) ObjectUtils.deepCopy(childSubAwards); newSubAwards.setBudgetId(parentBudget.getBudgetId()); // newSubAwards.setBudget(parentBudget); newSubAwards.setBudgetVersionNumber(parentBudget.getBudgetVersionNumber()); newSubAwards.setSubAwardNumber(parentBudget.getBudgetDocument().getHackedDocumentNextValue("subAwardNumber") != null ? parentBudget.getBudgetDocument().getHackedDocumentNextValue("subAwardNumber") : 1); newSubAwards.setVersionNumber(null); newSubAwards.setHierarchyProposalNumber(childProposalNumber); for (BudgetSubAwardAttachment attachment : newSubAwards.getBudgetSubAwardAttachments()) { attachment.setSubAwardNumber(newSubAwards.getSubAwardNumber()); // attachment.setBudget(parentBudget); attachment.setBudgetId(parentBudget.getBudgetId()); attachment.setBudgetSubawardAttachmentId(null); attachment.setVersionNumber(null); } for (BudgetSubAwardFiles files : newSubAwards.getBudgetSubAwardFiles()) { files.setSubAwardNumber(newSubAwards.getSubAwardNumber()); // files.setBudget(parentBudget); files.setBudgetId(parentBudget.getBudgetId()); files.setVersionNumber(null); } List<BudgetAssociate> listToBeSaved = new ArrayList<BudgetAssociate>(); listToBeSaved.add(newSubAwards); listToBeSaved.addAll(newSubAwards.getBudgetSubAwardFiles()); listToBeSaved.addAll(newSubAwards.getBudgetSubAwardAttachments()); businessObjectService.save(listToBeSaved); parentBudget.getBudgetSubAwards().add(newSubAwards); } int parentStartPeriod = getCorrespondingParentPeriod(parentBudget, childBudget); if (parentStartPeriod == -1) { throw new ProposalHierarchyException("Cannot find a parent budget period that corresponds to the child period."); } List<BudgetPeriod> parentPeriods = parentBudget.getBudgetPeriods(); List<BudgetPeriod> childPeriods = childBudget.getBudgetPeriods(); BudgetPeriod parentPeriod, childPeriod; Long budgetId = parentBudget.getBudgetId(); Long budgetPeriodId; Integer budgetPeriod; for (int i = 0, j = parentStartPeriod; i < childPeriods.size(); i++, j++) { childPeriod = childPeriods.get(i); if (j >= parentPeriods.size()) { parentPeriod = parentBudget.getNewBudgetPeriod(); parentPeriod.setBudgetPeriod(j + 1); parentPeriod.setBudget(parentBudget); parentPeriod.setStartDate(childPeriod.getStartDate()); parentPeriod.setEndDate(childPeriod.getEndDate()); parentPeriod.setBudgetId(budgetId); parentBudget.add(parentPeriod); } else { parentPeriod = parentPeriods.get(j); } budgetPeriodId = parentPeriod.getBudgetPeriodId(); budgetPeriod = parentPeriod.getBudgetPeriod(); BudgetLineItem parentLineItem; Integer lineItemNumber; if (StringUtils.equals(hierarchyBudgetTypeCode, HierarchyBudgetTypeConstants.SubBudget.code())) { for (BudgetLineItem childLineItem : childPeriod.getBudgetLineItems()) { ObjectUtils.materializeSubObjectsToDepth(childLineItem, 5); parentLineItem = (BudgetLineItem) (KraServiceLocator.getService(DeepCopyPostProcessor.class).processDeepCopyWithDeepCopyIgnore(childLineItem)); parentLineItem.setBudgetId(budgetId); parentLineItem.setBudgetPeriodId(budgetPeriodId); parentLineItem.setBudgetPeriod(budgetPeriod); parentLineItem.setVersionNumber(null); lineItemNumber = parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_LINEITEM_NUMBER); parentLineItem.setLineItemNumber(lineItemNumber); parentLineItem.setHierarchyProposalNumber(childProposalNumber); //parentLineItem.setUnderrecoveryAmount(childLineItem.getUnderrecoveryAmount()); BudgetPerson budgetPerson; for (BudgetPersonnelDetails details : parentLineItem.getBudgetPersonnelDetailsList()) { budgetPerson = personMap.get(details.getPersonSequenceNumber()); details.setBudgetId(budgetId); details.setBudgetPeriodId(budgetPeriodId); details.setBudgetPeriod(budgetPeriod); details.setBudgetPerson(budgetPerson); details.setJobCode(budgetPerson.getJobCode()); details.setPersonId(budgetPerson.getPersonRolodexTbnId()); details.setPersonSequenceNumber(budgetPerson.getPersonSequenceNumber()); details.setPersonNumber(parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_PERSON_LINE_NUMBER)); details.setLineItemNumber(lineItemNumber); details.setVersionNumber(null); } parentPeriod.getBudgetLineItems().add(parentLineItem); } } else { // subproject budget Map<String, String> primaryKeys; CostElement costElement; String directCostElement = parameterService.getParameterValue(BudgetDocument.class, PARAMETER_NAME_DIRECT_COST_ELEMENT); String indirectCostElement = parameterService.getParameterValue(BudgetDocument.class, PARAMETER_NAME_INDIRECT_COST_ELEMENT); if (childPeriod.getTotalIndirectCost().isNonZero()) { primaryKeys = new HashMap<String, String>(); primaryKeys.put("costElement", indirectCostElement); costElement = (CostElement)businessObjectService.findByPrimaryKey(CostElement.class, primaryKeys); parentLineItem = parentBudget.getNewBudgetLineItem(); parentLineItem.setLineItemDescription(childProposalNumber); parentLineItem.setStartDate(parentPeriod.getStartDate()); parentLineItem.setEndDate(parentPeriod.getEndDate()); parentLineItem.setBudgetId(budgetId); parentLineItem.setBudgetPeriodId(budgetPeriodId); parentLineItem.setBudgetPeriod(budgetPeriod); parentLineItem.setVersionNumber(null); lineItemNumber = parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_LINEITEM_NUMBER); parentLineItem.setLineItemNumber(lineItemNumber); parentLineItem.setHierarchyProposalNumber(childProposalNumber); parentLineItem.setLineItemCost(childPeriod.getTotalIndirectCost()); parentLineItem.setIndirectCost(childPeriod.getTotalIndirectCost()); parentLineItem.setCostElementBO(costElement); parentLineItem.setCostElement(costElement.getCostElement()); parentLineItem.setBudgetCategoryCode(costElement.getBudgetCategoryCode()); parentLineItem.setOnOffCampusFlag(costElement.getOnOffCampusFlag()); parentLineItem.setApplyInRateFlag(true); parentPeriod.getBudgetLineItems().add(parentLineItem); } if (childPeriod.getTotalDirectCost().isNonZero()) { primaryKeys = new HashMap<String, String>(); primaryKeys.put("costElement", directCostElement); costElement = (CostElement)businessObjectService.findByPrimaryKey(CostElement.class, primaryKeys); parentLineItem = parentBudget.getNewBudgetLineItem(); parentLineItem.setLineItemDescription(childProposalNumber); parentLineItem.setStartDate(parentPeriod.getStartDate()); parentLineItem.setEndDate(parentPeriod.getEndDate()); parentLineItem.setBudgetId(budgetId); parentLineItem.setBudgetPeriodId(budgetPeriodId); parentLineItem.setBudgetPeriod(budgetPeriod); parentLineItem.setVersionNumber(null); lineItemNumber = parentBudget.getBudgetDocument().getHackedDocumentNextValue(Constants.BUDGET_LINEITEM_NUMBER); parentLineItem.setLineItemNumber(lineItemNumber); parentLineItem.setHierarchyProposalNumber(childProposalNumber); parentLineItem.setLineItemCost(childPeriod.getTotalDirectCost()); parentLineItem.setDirectCost(childPeriod.getTotalDirectCost()); parentLineItem.setCostElementBO(costElement); parentLineItem.setCostElement(costElement.getCostElement()); parentLineItem.setBudgetCategoryCode(costElement.getBudgetCategoryCode()); parentLineItem.setOnOffCampusFlag(costElement.getOnOffCampusFlag()); parentLineItem.setApplyInRateFlag(true); parentPeriod.getBudgetLineItems().add(parentLineItem); } } } parentBudget.setStartDate(parentBudget.getBudgetPeriod(0).getStartDate()); parentBudget.setEndDate(parentBudget.getBudgetPeriod(parentBudget.getBudgetPeriods().size()-1).getEndDate()); } catch (Exception e) { LOG.error("Problem copying line items to parent", e); throw new ProposalHierarchyException("Problem copying line items to parent", e); } } private void aggregateHierarchy(DevelopmentProposal hierarchy) throws ProposalHierarchyException { LOG.info(String.format("***Aggregating Proposal Hierarchy #%s", hierarchy.getProposalNumber())); List<ProposalPersonBiography> biosToRemove = new ArrayList<ProposalPersonBiography>(); for (ProposalPersonBiography bio : hierarchy.getPropPersonBios()) { String bioPersonId = bio.getPersonId(); Integer bioRolodexId = bio.getRolodexId(); boolean keep = false; for (ProposalPerson person : hierarchy.getProposalPersons()) { if ((bioPersonId != null && bioPersonId.equals(person.getPersonId())) || (bioRolodexId != null && bioRolodexId.equals(person.getRolodexId()))) { bio.setProposalPersonNumber(person.getProposalPersonNumber()); keep = true; break; } } if (!keep) { biosToRemove.add(bio); } } if (!biosToRemove.isEmpty()) { hierarchy.getPropPersonBios().removeAll(biosToRemove); } BudgetDocument<DevelopmentProposal> hierarchyBudgetDocument = getHierarchyBudget(hierarchy); Budget hierarchyBudget = hierarchyBudgetDocument.getBudget(); KualiForm oldForm = GlobalVariables.getKualiForm(); GlobalVariables.setKualiForm(null); KraServiceLocator.getService(BudgetCalculationService.class).calculateBudget(hierarchyBudget); KraServiceLocator.getService(BudgetCalculationService.class).calculateBudgetSummaryTotals(hierarchyBudget); GlobalVariables.setKualiForm(oldForm); try { documentService.saveDocument(hierarchyBudgetDocument); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } } private DevelopmentProposal getHierarchy(String hierarchyProposalNumber) throws ProposalHierarchyException { DevelopmentProposal hierarchy = getDevelopmentProposal(hierarchyProposalNumber); if (hierarchy == null || !hierarchy.isParent()) throw new ProposalHierarchyException("Proposal " + hierarchyProposalNumber + " is not a hierarchy"); return hierarchy; } public DevelopmentProposal getDevelopmentProposal(String proposalNumber) { Map<String, String> pk = new HashMap<String, String>(); pk.put("proposalNumber", proposalNumber); return (DevelopmentProposal) (businessObjectService.findByPrimaryKey(DevelopmentProposal.class, pk)); } private boolean isSynchronized(String childProposalNumber) throws ProposalHierarchyException { DevelopmentProposal childProposal = getDevelopmentProposal(childProposalNumber); Budget childBudget = getFinalOrLatestChildBudget(childProposal).getBudget(); ObjectUtils.materializeAllSubObjects(childBudget); int hc1 = computeHierarchyHashCode(childProposal, childBudget); int hc2 = childProposal.getHierarchyLastSyncHashCode(); return hc1 == hc2; } private void setInitialPi(DevelopmentProposal hierarchy, DevelopmentProposal child) { ProposalPerson pi = child.getPrincipalInvestigator(); if (pi != null) { int index = hierarchy.getProposalPersons().indexOf(pi); if (index > -1) { hierarchy.getProposalPerson(index).setProposalPersonRoleId(Constants.PRINCIPAL_INVESTIGATOR_ROLE); hierarchy.getProposalPerson(index).setHierarchyProposalNumber(null); } } } private BudgetDocument<DevelopmentProposal> getHierarchyBudget(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { String budgetDocumentNumber = hierarchyProposal.getProposalDocument().getBudgetDocumentVersions().get(0).getBudgetVersionOverview().getDocumentNumber(); BudgetDocument<DevelopmentProposal> budgetDocument = null; try { budgetDocument = (BudgetDocument<DevelopmentProposal>) documentService.getByDocumentHeaderId(budgetDocumentNumber); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } return budgetDocument;//.getBudget(); } private BudgetDocument<DevelopmentProposal> getFinalOrLatestChildBudget(DevelopmentProposal childProposal) throws ProposalHierarchyException { String budgetDocumentNumber = null; for (BudgetDocumentVersion version : childProposal.getProposalDocument().getBudgetDocumentVersions()) { budgetDocumentNumber = version.getDocumentNumber(); if (version.getBudgetVersionOverview().isFinalVersionFlag()) { break; } } BudgetDocument<DevelopmentProposal> budgetDocument = null; try { budgetDocument = (BudgetDocument<DevelopmentProposal>) documentService.getByDocumentHeaderId(budgetDocumentNumber); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } return budgetDocument;//.getBudget(); } private void initializeBudget (DevelopmentProposal hierarchyProposal, DevelopmentProposal childProposal) throws ProposalHierarchyException { BudgetDocument<DevelopmentProposal> parentBudgetDoc = getHierarchyBudget(hierarchyProposal); Budget parentBudget = parentBudgetDoc.getBudget(); BudgetDocument<DevelopmentProposal> childBudgetDocument = getFinalOrLatestChildBudget(childProposal); Budget childBudget = childBudgetDocument.getBudget(); BudgetPeriod parentPeriod, childPeriod; for (int i=0; i < childBudget.getBudgetPeriods().size(); i++) { parentPeriod = parentBudget.getBudgetPeriod(i); childPeriod = childBudget.getBudgetPeriod(i); parentPeriod.setStartDate(childPeriod.getStartDate()); parentPeriod.setEndDate(childPeriod.getEndDate()); parentPeriod.setBudgetPeriod(childPeriod.getBudgetPeriod()); } parentBudget.setCostSharingAmount(new BudgetDecimal(0)); parentBudget.setTotalCost(new BudgetDecimal(0)); parentBudget.setTotalDirectCost(new BudgetDecimal(0)); parentBudget.setTotalIndirectCost(new BudgetDecimal(0)); parentBudget.setUnderrecoveryAmount(new BudgetDecimal(0)); parentBudget.setOhRateClassCode(childBudget.getOhRateClassCode()); parentBudget.setOhRateTypeCode(childBudget.getOhRateTypeCode()); parentBudget.setUrRateClassCode(childBudget.getUrRateClassCode()); try { documentService.saveDocument(parentBudgetDoc); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } } public ProposalHierarchyErrorDto validateChildBudgetPeriods(DevelopmentProposal hierarchyProposal, DevelopmentProposal childProposal, boolean allowEndDateChange) throws ProposalHierarchyException { BudgetDocument<DevelopmentProposal> parentBudgetDoc = getHierarchyBudget(hierarchyProposal); Budget parentBudget = parentBudgetDoc.getBudget(); BudgetDocument<DevelopmentProposal> childBudgetDocument = getFinalOrLatestChildBudget(childProposal); Budget childBudget = childBudgetDocument.getBudget(); ProposalHierarchyErrorDto retval = null; // check that child budget starts on one of the budget period starts int correspondingStart = getCorrespondingParentPeriod(parentBudget, childBudget); if (correspondingStart == -1) { retval = new ProposalHierarchyErrorDto(ERROR_BUDGET_START_DATE_INCONSISTENT, childProposal.getProposalNumber()); } // check that child budget periods map to parent periods else { List<BudgetPeriod> parentPeriods = parentBudget.getBudgetPeriods(); List<BudgetPeriod> childPeriods = childBudget.getBudgetPeriods(); BudgetPeriod parentPeriod, childPeriod; int i; int j; for (i = correspondingStart, j = 0; i < parentPeriods.size() && j < childPeriods.size(); i++, j++) { parentPeriod = parentPeriods.get(i); childPeriod = childPeriods.get(j); if (!parentPeriod.getStartDate().equals(childPeriod.getStartDate()) || !parentPeriod.getEndDate().equals(childPeriod.getEndDate())) { retval = new ProposalHierarchyErrorDto(ERROR_BUDGET_PERIOD_DURATION_INCONSISTENT, childProposal.getProposalNumber()); break; } } if (retval == null && !allowEndDateChange && (j < childPeriods.size() || childProposal.getRequestedEndDateInitial().after(hierarchyProposal.getRequestedEndDateInitial()))) { retval = new ProposalHierarchyErrorDto(QUESTION_EXTEND_PROJECT_DATE_CONFIRM, childProposal.getProposalNumber()); } } return retval; } private int getCorrespondingParentPeriod(Budget parentBudget, Budget childBudget) { int correspondingStart = -1; // using start date of first period as start date and end date of last period // as end because budget start and end are not particularly reliable Date childStart = childBudget.getBudgetPeriod(0).getStartDate(); Date parentStart = parentBudget.getBudgetPeriod(0).getStartDate(); Date parentEnd = parentBudget.getBudgetPeriod(parentBudget.getBudgetPeriods().size()-1).getEndDate(); // check that child budget starts somewhere during parent budget if (childStart.compareTo(parentStart) >= 0 && childStart.compareTo(parentEnd) < 0) { // check that child budget starts on one of the budget period starts List<BudgetPeriod> parentPeriods = parentBudget.getBudgetPeriods(); for (int i=0; i<parentPeriods.size(); i++) { if (childStart.equals(parentPeriods.get(i).getStartDate())) { correspondingStart = i; break; } } } return correspondingStart; } private void removeChildElements(DevelopmentProposal parentProposal, Budget parentBudget, String childProposalNumber) { List<PropScienceKeyword> keywords = parentProposal.getPropScienceKeywords(); for (int i=keywords.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, keywords.get(i).getHierarchyProposalNumber())) { keywords.remove(i); } } List<ProposalSpecialReview> reviews = parentProposal.getPropSpecialReviews(); for (int i=reviews.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, reviews.get(i).getHierarchyProposalNumber())) { reviews.remove(i); } } List<Narrative> narratives = parentProposal.getNarratives(); for (int i=narratives.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, narratives.get(i).getHierarchyProposalNumber())) { narratives.remove(i); } } List<ProposalPerson> persons = parentProposal.getProposalPersons(); for (int i=persons.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, persons.get(i).getHierarchyProposalNumber())) { persons.remove(i); } } List<BudgetSubAwards> subAwards = parentBudget.getBudgetSubAwards(); for (int i=subAwards.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, subAwards.get(i).getHierarchyProposalNumber())) { subAwards.remove(i); } } BudgetPersonnelBudgetService budgetPersonnelBudgetService = KraServiceLocator.getService(BudgetPersonnelBudgetService.class); List<BudgetPeriod> periods = parentBudget.getBudgetPeriods(); List<BudgetLineItem> lineItems; List<BudgetPersonnelDetails> personnelDetailsList; BudgetPeriod period = null; BudgetLineItem lineItem = null; for (int i = periods.size()-1; i>=0; i--) { period = periods.get(i); lineItems = period.getBudgetLineItems(); for (int j = lineItems.size()-1; j>=0; j--) { lineItem = lineItems.get(j); if (StringUtils.equals(childProposalNumber, lineItem.getHierarchyProposalNumber())) { personnelDetailsList = lineItem.getBudgetPersonnelDetailsList(); for (int k = personnelDetailsList.size()-1; k>=0; k--) { budgetPersonnelBudgetService.deleteBudgetPersonnelDetails(parentBudget, i, j, k); } lineItems.remove(j); parentBudget.setBudgetLineItemDeleted(true); } } if (lineItems.isEmpty()) { periods.remove(period); } } List<BudgetPerson> budgetPersons = parentBudget.getBudgetPersons(); for (int i=budgetPersons.size()-1; i>=0; i--) { if (StringUtils.equals(childProposalNumber, budgetPersons.get(i).getHierarchyProposalNumber())) { budgetPersonnelBudgetService.deleteBudgetPersonnelDetailsForPerson(parentBudget, budgetPersons.get(i)); budgetPersons.remove(i); } } } private void prepareHierarchySync(DevelopmentProposal hierarchyProposal) { prepareHierarchySync(hierarchyProposal.getProposalDocument()); } private void prepareHierarchySync(ProposalDevelopmentDocument pdDoc) { pdDoc.refreshReferenceObject("documentNextvalues"); } private void finalizeHierarchySync(ProposalDevelopmentDocument pdDoc) throws ProposalHierarchyException { pdDoc.refreshReferenceObject("budgetDocumentVersions"); try { documentService.saveDocument(pdDoc); } catch (WorkflowException e) { throw new ProposalHierarchyException(e); } } private void finalizeHierarchySync(DevelopmentProposal hierarchyProposal) throws ProposalHierarchyException { businessObjectService.save(hierarchyProposal.getProposalDocument().getDocumentNextvalues()); businessObjectService.save(hierarchyProposal); } private void copyInitialAttachments(DevelopmentProposal srcProposal, DevelopmentProposal destProposal) { String instituteNarrativeTypeGroup = parameterService.getParameterValue(ProposalDevelopmentDocument.class, PARAMETER_NAME_INSTITUTE_NARRATIVE_TYPE_GROUP); ProposalPersonBiography destPropPersonBio; ProposalPerson srcPerson = null; ProposalPerson destPerson = null; for (ProposalPersonBiography srcPropPersonBio : srcProposal.getPropPersonBios()) { for (ProposalPerson person : srcProposal.getProposalPersons()) { if (person.getProposalPersonNumber().equals(srcPropPersonBio.getProposalPersonNumber())) { srcPerson = person; break; } } for (ProposalPerson person : destProposal.getProposalPersons()) { if (person.equals(srcPerson)) { destPerson = person; break; } } loadBioContent(srcPropPersonBio); destPropPersonBio = (ProposalPersonBiography)ObjectUtils.deepCopy(srcPropPersonBio); destPropPersonBio.setProposalPersonNumber(destPerson.getProposalPersonNumber()); destPropPersonBio.setPersonId(destPerson.getPersonId()); destPropPersonBio.setRolodexId(destPerson.getRolodexId()); propPersonBioService.addProposalPersonBiography(destProposal.getProposalDocument(), destPropPersonBio); } Narrative destNarrative; for (Narrative srcNarrative : srcProposal.getNarratives()) { if (StringUtils.equalsIgnoreCase(srcNarrative.getNarrativeType().getAllowMultiple(), "N") && !srcProposal.getInstituteAttachments().contains(srcNarrative) && !StringUtils.equalsIgnoreCase(srcNarrative.getNarrativeType().getNarrativeTypeGroup(), instituteNarrativeTypeGroup)) { loadAttachmentContent(srcNarrative); destNarrative = (Narrative)ObjectUtils.deepCopy(srcNarrative); destNarrative.setModuleStatusCode("I"); narrativeService.addNarrative(destProposal.getProposalDocument(), destNarrative); } } } private void loadAttachmentContent(Narrative narrative){ Map<String,String> primaryKey = new HashMap<String,String>(); primaryKey.put("proposalNumber", narrative.getProposalNumber()); primaryKey.put("moduleNumber", narrative.getModuleNumber()+""); NarrativeAttachment attachment = (NarrativeAttachment)businessObjectService.findByPrimaryKey(NarrativeAttachment.class, primaryKey); narrative.getNarrativeAttachmentList().clear(); narrative.getNarrativeAttachmentList().add(attachment); } private void loadBioContent(ProposalPersonBiography bio){ Map<String,String> primaryKey = new HashMap<String,String>(); primaryKey.put("proposalNumber", bio.getProposalNumber()); primaryKey.put("biographyNumber", bio.getBiographyNumber()+""); primaryKey.put("proposalPersonNumber", bio.getProposalPersonNumber()+""); ProposalPersonBiographyAttachment attachment = (ProposalPersonBiographyAttachment)businessObjectService.findByPrimaryKey(ProposalPersonBiographyAttachment.class, primaryKey); bio.getPersonnelAttachmentList().clear(); bio.getPersonnelAttachmentList().add(attachment); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getHierarchyChildRouteStatus(java.lang.String, java.lang.String) */ public String getHierarchyChildRouteStatus( String oldStatus, String newStatus) { LOG.info( String.format( "Route status change %s:%s",oldStatus,newStatus)); String retCd = null; if( StringUtils.equals(newStatus,KEWConstants.ROUTE_HEADER_ENROUTE_CD) && ( StringUtils.equals( oldStatus, KEWConstants.ROUTE_HEADER_INITIATED_CD) || StringUtils.equals(oldStatus, KEWConstants.ROUTE_HEADER_SAVED_CD) || StringUtils.equals(KEWConstants.ROUTE_HEADER_ENROUTE_CD, oldStatus)) ) { retCd = renderMessage( HIERARCHY_CHILD_ENROUTE_APPSTATUS ); } else if ( StringUtils.equals(newStatus, KEWConstants.ROUTE_HEADER_FINAL_CD)) { retCd = renderMessage( HIERARCHY_CHILD_FINAL_APPSTATUS ); } else if( StringUtils.equals( newStatus, KEWConstants.ROUTE_HEADER_DISAPPROVED_CD )) { retCd = renderMessage( HIERARCHY_CHILD_DISAPPROVE_APPSTATUS ); } else if( StringUtils.equals( newStatus, KEWConstants.ROUTE_HEADER_CANCEL_CD ) ) { retCd = renderMessage( HIERARCHY_CHILD_CANCEL_APPSTATUS ); } else { LOG.warn(String.format("Do not know how to calculate hierarchy child status for %s to %s",oldStatus,newStatus) ); } if( LOG.isDebugEnabled() ) LOG.debug(String.format("Route status for children:%s",retCd )); return retCd; } /** * Creates a hash of the data pertinent to a hierarchy for comparison during hierarchy syncing. */ private int computeHierarchyHashCode(DevelopmentProposal proposal, Budget budget) { int prime = 31; int result = 1; KraServiceLocator.getService(BudgetCalculationService.class).calculateBudget(budget); KraServiceLocator.getService(BudgetCalculationService.class).calculateBudgetSummaryTotals(budget); for (ProposalPerson person : proposal.getProposalPersons()) { result = prime * result + person.hashCode(); } for (Narrative narrative : proposal.getNarratives()) { result = prime * result + narrative.hierarchyHashCode(); } for (PropScienceKeyword keyword : proposal.getPropScienceKeywords()) { result = prime * result + keyword.getScienceKeywordCode().hashCode(); } for (ProposalSpecialReview review : proposal.getPropSpecialReviews()) { result = prime * result + review.hierarchyHashCode(); } result = prime * result + budget.getBudgetSummaryTotals().hashCode(); return result; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getChildProposalDevelopmentDocuments(java.lang.String) */ public List<ProposalDevelopmentDocument> getChildProposalDevelopmentDocuments(String parentProposalNumber) throws ProposalHierarchyException { List<ProposalDevelopmentDocument> outList = new ArrayList<ProposalDevelopmentDocument>(); for( DevelopmentProposal child : getHierarchyChildren(parentProposalNumber)) { try { outList.add( (ProposalDevelopmentDocument)documentService.getByDocumentHeaderId( child.getProposalDocument().getDocumentNumber() ) ); } catch (WorkflowException e) { LOG.error( String.format( "Could not find document for child proposal number %s", parentProposalNumber, child.getProposalNumber() ), e); throw new ProposalHierarchyException( String.format( "Could not find document for child proposal number %s", parentProposalNumber, child.getProposalNumber() ), e ); } } return outList; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getHierarchyChildren(java.lang.String) */ public List<DevelopmentProposal> getHierarchyChildren(String parentProposalNumber) { List<DevelopmentProposal> children = new ArrayList<DevelopmentProposal>(); for( String childProposalNumber : proposalHierarchyDao.getHierarchyChildProposalNumbers(parentProposalNumber)) { children.add(getDevelopmentProposal(childProposalNumber)); } return children; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getParentWorkflowStatus(org.kuali.kra.proposaldevelopment.bo.DevelopmentProposal) */ public KualiWorkflowDocument getParentWorkflowDocument(ProposalDevelopmentDocument child) throws ProposalHierarchyException { return getParentDocument( child ).getDocumentHeader().getWorkflowDocument(); } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getParentDocument(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument) */ public ProposalDevelopmentDocument getParentDocument(ProposalDevelopmentDocument child) throws ProposalHierarchyException { try { DevelopmentProposal parentProposal = getHierarchy(child.getDevelopmentProposal().getHierarchyParentProposalNumber()); String parentDocumentNumber = parentProposal.getProposalDocument().getDocumentNumber(); return (ProposalDevelopmentDocument)documentService.getByDocumentHeaderId(parentDocumentNumber); } catch (WorkflowException e) { LOG.error( "Workflow exception thrown getting hierarchy routing status.", e ); throw new ProposalHierarchyException( String.format("Could not lookup hierarchy workflow status for child:%s",child.getDocumentHeader().getDocumentNumber()),e); } } /** * Reject a proposal by sending it to the first node ( as named by PROPOSALDEVELOPMENTDOCUMENT_KEW_INITIAL_NODE_NAME ) * @param proposalDoc The ProposalDevelopmentDocument that should be rejected. * @param appDocStatus the application status to set in the workflow document. * @param principalName the principal name we are rejecting the document as. * @param appDocStatus the application document status to apply ( does not apply if null ) * @throws WorkflowException */ private void rejectProposal( ProposalDevelopmentDocument proposalDoc, String reason, String principalName, String appDocStatus ) throws WorkflowException { WorkflowDocument workflowDocument = new WorkflowDocument(identityManagementService.getPrincipalByPrincipalName(principalName).getPrincipalId(), proposalDoc.getDocumentHeader().getWorkflowDocument().getRouteHeaderId()); workflowDocument.returnToPreviousNode(reason, getProposalDevelopmentInitialNodeName() ); workflowDocument.updateAppDocStatus( appDocStatus ); } /** * Reject an entire proposal hierarchy. This works by first rejecting each child, and then rejecting the parent. * @param hierarchyParent The hierarchy to reject * @param reason the reason to be applied to the annotation field. The reason will be pre-pended with static text indicating if it was a child or the parent. * @param principalName the name of the principal that is rejecting the document. * @throws ProposalHierarchyException If hierarchyParent is not a hierarchy, or there was a problem rejecting one of the documents. */ private void rejectProposalHierarchy(ProposalDevelopmentDocument hierarchyParent, String reason, String principalName ) throws ProposalHierarchyException { //1. reject the parent. try { rejectProposal( hierarchyParent, renderMessage( PROPOSAL_ROUTING_REJECTED_ANNOTATION, reason ), principalName, renderMessage( HIERARCHY_REJECTED_APPSTATUS ) ); } catch (WorkflowException e) { throw new ProposalHierarchyException( String.format( "WorkflowException encountered rejecting proposal hierarchy parent %s", hierarchyParent.getDevelopmentProposal().getProposalNumber() ),e); } //2. Try to reject all of the children. for( ProposalDevelopmentDocument child : getChildProposalDevelopmentDocuments(hierarchyParent.getDevelopmentProposal().getProposalNumber())) { try { rejectProposal( child, renderMessage( HIERARCHY_ROUTING_PARENT_REJECTED_ANNOTATION, reason ), KEWConstants.SYSTEM_USER, renderMessage( HIERARCHY_CHILD_REJECTED_APPSTATUS ) ); } catch (WorkflowException e) { throw new ProposalHierarchyException( String.format( "WorkflowException encountered rejecting child document %s", child.getDevelopmentProposal().getProposalNumber()), e ); } } } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#rejectProposalDevelopmentDocument(java.lang.String, java.lang.String) */ public void rejectProposalDevelopmentDocument( String proposalNumber, String reason, String principalName ) throws WorkflowException, ProposalHierarchyException { DevelopmentProposal pbo = getDevelopmentProposal(proposalNumber); ProposalDevelopmentDocument pDoc = (ProposalDevelopmentDocument)documentService.getByDocumentHeaderId(getDevelopmentProposal(proposalNumber).getProposalDocument().getDocumentNumber()); if( !pbo.isInHierarchy() ) { rejectProposal( pDoc, renderMessage( PROPOSAL_ROUTING_REJECTED_ANNOTATION, reason ), principalName, renderMessage( HIERARCHY_REJECTED_APPSTATUS ) ); } else if ( pbo.isParent() ) { rejectProposalHierarchy( pDoc, reason, principalName ); } else { //it is a child or in some unknown state, either way we do not support rejecting it. throw new UnsupportedOperationException( String.format( "Cannot reject proposal %s it is a hierarchy child or ", proposalNumber )); } } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getProposalDevelopmentInitialNodeName() */ public String getProposalDevelopmentInitialNodeName() { DocumentTypeService dService = KEWServiceLocator.getDocumentTypeService(); DocumentTypeDTO proposalDevDocType = dService.getDocumentTypeVO("ProposalDevelopmentDocument"); ProcessDTO p = proposalDevDocType.getRoutePath().getPrimaryProcess(); return p.getInitialRouteNode().getRouteNodeName(); } /** * * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#isProposalOnInitialRouteNode(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument) */ public boolean isProposalOnInitialRouteNode( ProposalDevelopmentDocument document ) { boolean ret = false; try { if( ArrayUtils.contains(document.getDocumentHeader().getWorkflowDocument().getNodeNames(), getProposalDevelopmentInitialNodeName())) ret = true; } catch ( WorkflowException we ) { throw new RuntimeException( String.format( "Could not get node names for document: %s", document.getDocumentNumber()), we ); } return ret; } /** * Based on the hierarchy, and route status change of the parent, calculate what route action should be taken on the children. * @param hierarchy the heirarchy being routed * @param dto the route status change information. * @return The route action to take on the children. */ private String calculateChildRouteStatus( ProposalDevelopmentDocument hierarchy, DocumentRouteStatusChangeDTO dto ) { String parentOldStatus = dto.getOldRouteStatus(); String parentNewStatus = dto.getNewRouteStatus(); String newChildStatusTarget = ""; if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_INITIATED_CD)) { // nothing to do here. } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_SAVED_CD)) { // previous status was saved newChildStatusTarget = parentNewStatus; if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_ENROUTE_CD)) { // nothing to do } else if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_CANCEL_CD)) { // nothing to do. } else { throw new UnsupportedOperationException(String.format( "Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus, parentNewStatus)); } } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_ENROUTE_CD)) { // we are moving from enroute to some other state. if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_CANCEL_CD) || StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_DISAPPROVED_CD)) { newChildStatusTarget = parentNewStatus; } else if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_APPROVED_CD)) { // nothing to do here, wait for the document to go final. } else if( StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_ENROUTE_CD)) { //special case, document has been rejected and being approved again to simulate entry into workflow. //this value will trigger an approve. newChildStatusTarget = KEWConstants.ROUTE_HEADER_ENROUTE_CD; } else { throw new UnsupportedOperationException(String.format("Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus,parentNewStatus)); } } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_APPROVED_CD)) { // nothing to do here. } else if (StringUtils.equals(parentOldStatus, KEWConstants.ROUTE_HEADER_PROCESSED_CD)) { if (StringUtils.equals(parentNewStatus, KEWConstants.ROUTE_HEADER_FINAL_CD)) { newChildStatusTarget = parentNewStatus; } else { throw new UnsupportedOperationException(String.format("Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus,parentNewStatus)); } } else { throw new UnsupportedOperationException(String.format( "Do not know how to handle children of hierarchy for route status chnage from %s to %s", parentOldStatus,parentNewStatus)); } return newChildStatusTarget; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#routeHierarchyChildren(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument, org.kuali.rice.kew.dto.DocumentRouteStatusChangeDTO, java.lang.String) */ public void routeHierarchyChildren(ProposalDevelopmentDocument proposalDevelopmentDocument, DocumentRouteStatusChangeDTO dto ) throws ProposalHierarchyException { String childStatusTarget = calculateChildRouteStatus(proposalDevelopmentDocument, dto ); WorkflowDocument workdoc; ProposalDevelopmentDocument child = null; try { LOG.info( IdentityManagementService.class ); for (ProposalDevelopmentDocument c : getChildProposalDevelopmentDocuments(proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber() )) { child = c; if (!StringUtils.equals("", childStatusTarget)) { if (StringUtils.equals(KEWConstants.ROUTE_HEADER_ENROUTE_CD, childStatusTarget)) { //The user currently must initially route the child documents in order for them to hold in the system users action list. workdoc = new WorkflowDocument(child.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId(), child.getDocumentHeader().getWorkflowDocument().getRouteHeaderId() ); workdoc.updateAppDocStatus(getHierarchyChildRouteStatus( dto.getOldRouteStatus(), dto.getNewRouteStatus() )); if( !workdoc.stateIsEnroute() ) { workdoc.routeDocument(renderMessage( HIERARCHY_ROUTING_PARENT_SUBMITTED_ANNOTATION )); } else { //this means the status change is actually in the form of an approve action on a document that was moved back to the initial node. //we need to do an approval. workdoc.approve(renderMessage( HIERARCHY_ROUTING_PARENT_RESUBMITTED_ANNOTATION )); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_ENROUTE_APPSTATUS ) ); } } else { workdoc = new WorkflowDocument( identityManagementService.getPrincipalByPrincipalName(KNSConstants.SYSTEM_USER ).getPrincipalId(),child.getDocumentHeader().getWorkflowDocument().getRouteHeaderId() ); workdoc.updateAppDocStatus(getHierarchyChildRouteStatus( dto.getOldRouteStatus(), dto.getNewRouteStatus() )); if (StringUtils.equals(KEWConstants.ROUTE_HEADER_CANCEL_CD,childStatusTarget)) { workdoc.cancel(renderMessage( HIERARCHY_ROUTING_PARENT_CANCELLED_ANNOTATION)); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_CANCEL_APPSTATUS )); } else if (StringUtils.equals(KEWConstants.ROUTE_HEADER_FINAL_CD, childStatusTarget)) { workdoc.approve(renderMessage( HIERARCHY_ROUTING_PARENT_APPROVED_ANNOTATION )); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_FINAL_APPSTATUS )); } else if (StringUtils.equals(KEWConstants.ROUTE_HEADER_DISAPPROVED_CD, childStatusTarget)) { workdoc.disapprove(renderMessage( HIERARCHY_ROUTING_PARENT_DISAPPROVED_ANNOTATION )); workdoc.updateAppDocStatus(renderMessage( HIERARCHY_CHILD_DISAPPROVE_APPSTATUS )); } else { throw new UnsupportedOperationException(String.format("Do not know how to handle new child status of %s", childStatusTarget)); } } } } } catch ( WorkflowException we ) { throw new ProposalHierarchyException( String.format( "WorkflowException encountrered while attempting to route child proposal %s ( document #%s ) of proposal hierarchy %s ( document #%s )", child.getDevelopmentProposal().getProposalNumber(), child.getDocumentNumber(), proposalDevelopmentDocument.getDevelopmentProposal().getProposalNumber(), proposalDevelopmentDocument.getDocumentNumber() ), we); } } public void calculateAndSetProposalAppDocStatus( ProposalDevelopmentDocument doc, DocumentRouteStatusChangeDTO dto ) throws ProposalHierarchyException { String principalId = GlobalVariables.getUserSession().getPrincipalId(); if( StringUtils.equals( dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_ENROUTE_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_ENROUTE_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_CANCEL_CD)) { updateAppDocStatus( doc, principalId, HIERARCHY_CANCEL_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_DISAPPROVED_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_DISAPPROVE_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_FINAL_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_FINAL_APPSTATUS ); } else if ( StringUtils.equals(dto.getNewRouteStatus(), KEWConstants.ROUTE_HEADER_PROCESSED_CD )) { updateAppDocStatus( doc, principalId, HIERARCHY_PROCESSED_APPSTATUS ) ; } } public void updateAppDocStatus( ProposalDevelopmentDocument doc, String principalId, String newStatus ) throws ProposalHierarchyException { try { WorkflowDocument wdoc = new WorkflowDocument(principalId, doc.getDocumentHeader().getWorkflowDocument().getRouteHeaderId() ); wdoc.updateAppDocStatus(renderMessage( newStatus )); } catch (WorkflowException e) { throw new ProposalHierarchyException( String.format( "WorkflowException encountrered while attempting to update App Doc Status of proposal %s ( document #%s )", doc.getDevelopmentProposal().getProposalNumber(), doc.getDocumentNumber() ), e); } } public boolean allChildBudgetsAreComplete(String parentProposalNumber) { boolean retval = true; String completeCode = parameterService.getParameterValue(BudgetDocument.class, Constants.BUDGET_STATUS_COMPLETE_CODE); for (ProposalBudgetStatus status : proposalHierarchyDao.getHierarchyChildProposalBudgetStatuses(parentProposalNumber)) { if (!StringUtils.equalsIgnoreCase(completeCode, status.getBudgetStatusCode())) { retval = false; break; } } return retval; } private boolean rolesAreSimilar(ProposalPerson person1, ProposalPerson person2) { boolean isInvestigator1 = StringUtils.equals(person1.getProposalPersonRoleId(), Constants.PRINCIPAL_INVESTIGATOR_ROLE) || StringUtils.equals(person1.getProposalPersonRoleId(), Constants.CO_INVESTIGATOR_ROLE); boolean isInvestigator2 = StringUtils.equals(person2.getProposalPersonRoleId(), Constants.PRINCIPAL_INVESTIGATOR_ROLE) || StringUtils.equals(person2.getProposalPersonRoleId(), Constants.CO_INVESTIGATOR_ROLE); return isInvestigator1 == isInvestigator2; } /** * @see org.kuali.kra.proposaldevelopment.hierarchy.service.ProposalHierarchyService#getHierarchyProposalSummaries(java.lang.String) */ public List<HierarchyProposalSummary> getHierarchyProposalSummaries(String proposalNumber) throws ProposalHierarchyException { DevelopmentProposal proposal = getDevelopmentProposal(proposalNumber); List<HierarchyProposalSummary> summaries = new ArrayList<HierarchyProposalSummary>(); List<String> proposalNumbers = new ArrayList<String>(); if (proposal.isParent()) { proposalNumbers.add(proposalNumber); } else if (proposal.isChild()) { proposalNumbers.add(proposal.getHierarchyParentProposalNumber()); } else { throw new ProposalHierarchyException("Proposal " + proposalNumber + " is not a member of a hierarchy."); } proposalNumbers.addAll(proposalHierarchyDao.getHierarchyChildProposalNumbers(proposalNumbers.get(0))); HierarchyProposalSummary summary; for (String number : proposalNumbers) { summary = new HierarchyProposalSummary(); summary.setProposalNumber(number); if (!StringUtils.equals(number, proposalNumbers.get(0))) { summary.setSynced(isSynchronized(number)); } summaries.add(summary); } return summaries; } public boolean validateRemovePermissions(DevelopmentProposal childProposal, String principalId) { boolean valid = true; valid &= kraAuthorizationService.hasPermission(principalId, childProposal.getProposalDocument(), PermissionConstants.MAINTAIN_PROPOSAL_HIERARCHY); try { valid &= kraAuthorizationService.hasPermission(principalId, getHierarchy(childProposal.getHierarchyParentProposalNumber()).getProposalDocument(), PermissionConstants.MAINTAIN_PROPOSAL_HIERARCHY); } catch (ProposalHierarchyException e) { valid = false; } return valid; } /** * Gets the configurationService attribute. * @return Returns the configurationService. */ public KualiConfigurationService getConfigurationService() { return configurationService; } /** * Sets the configurationService attribute value. * @param configurationService The configurationService to set. */ public void setConfigurationService(KualiConfigurationService configurationService) { this.configurationService = configurationService; } private String renderMessage( String key, String... params ) { String msg = configurationService.getPropertyString(key); for (int i = 0; i < params.length; i++) { msg = replace(msg, "{" + i + "}", params[i]); } return msg; } }
KRACOEUS-3781 : Personnel Details were 'moving' to child instead of being 'copied' to child, so personnel line item became summary line item. Fixed so it copies now.
src/main/java/org/kuali/kra/proposaldevelopment/hierarchy/service/impl/ProposalHierarchyServiceImpl.java
KRACOEUS-3781 : Personnel Details were 'moving' to child instead of being 'copied' to child, so personnel line item became summary line item. Fixed so it copies now.
<ide><path>rc/main/java/org/kuali/kra/proposaldevelopment/hierarchy/service/impl/ProposalHierarchyServiceImpl.java <ide> BudgetPerson budgetPerson; <ide> for (BudgetPersonnelDetails details : parentLineItem.getBudgetPersonnelDetailsList()) { <ide> budgetPerson = personMap.get(details.getPersonSequenceNumber()); <add> details.setBudgetPersonnelLineItemId(null); <ide> details.setBudgetId(budgetId); <ide> details.setBudgetPeriodId(budgetPeriodId); <ide> details.setBudgetPeriod(budgetPeriod);
Java
apache-2.0
127ae7c7f68e245b92226b220cbe54ba613638d9
0
Erudika/para,Erudika/para
/* * Copyright 2013-2016 Erudika. http://erudika.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. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.utils.filters; import com.erudika.para.core.ParaObject; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; /** * Filter response entities dynamically, based on a list of selected fields. Returns partial objects. * * @author Alex Bogdanovski [[email protected]] */ @Provider public class FieldFilter implements ContainerResponseFilter { @Context private HttpServletRequest request; @Override @SuppressWarnings("unchecked") public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { try { if (responseContext.getEntity() != null && !StringUtils.isBlank(request.getParameter("select"))) { String[] sarr = StringUtils.split(request.getParameter("select"), ","); List<String> fields = sarr == null ? new ArrayList<String>(0) : Arrays.asList(sarr); if (!fields.isEmpty()) { Object entity = responseContext.getEntity(); Object newEntity = null; if (entity instanceof ParaObject) { Map<String, Object> newItem = new HashMap<String, Object>(); for (String field : fields) { newItem.put(field, getProperty(entity, field)); } newEntity = newItem; } else if (entity instanceof Map) { if (((Map) entity).containsKey("items")) { newEntity = new ArrayList<Map<String, Object>>(); for (ParaObject item : (List<ParaObject>) ((Map) entity).get("items")) { Map<String, Object> newItem = new HashMap<String, Object>(); for (String field : fields) { newItem.put(field, getProperty(item, field)); } ((List) newEntity).add(newItem); } ((Map) entity).put("items", newEntity); } } else if (entity instanceof List) { newEntity = new ArrayList<Map<String, Object>>(); if (!((List) entity).isEmpty() && ((List) entity).get(0) instanceof ParaObject) { for (ParaObject item : (List<ParaObject>) entity) { Map<String, Object> newItem = new HashMap<String, Object>(); for (String field : fields) { newItem.put(field, getProperty(item, field)); } ((List) newEntity).add(newItem); } } } if (newEntity != null) { responseContext.setEntity(newEntity); } } } } catch (Exception e) { LoggerFactory.getLogger(this.getClass()).warn(null, e); } } private Object getProperty(Object obj, String prop) { try { return BeanUtils.getProperty(obj, prop); } catch (Exception e) { return null; } } }
para-server/src/main/java/com/erudika/para/utils/filters/FieldFilter.java
/* * Copyright 2013-2016 Erudika. http://erudika.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. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.utils.filters; import com.erudika.para.core.ParaObject; import com.erudika.para.utils.Utils; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; /** * Filter response entities dynamically, based on a list of selected fields. Returns partial objects. * * @author Alex Bogdanovski [[email protected]] */ @Provider public class FieldFilter implements ContainerResponseFilter { @Context private HttpServletRequest request; @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (responseContext.getEntity() != null) { String[] sarr = StringUtils.split(request.getParameter("select"), ","); List<String> fields = sarr == null ? new ArrayList<String>(0) : Arrays.asList(sarr); filterObject(fields, responseContext.getEntity()); } } @SuppressWarnings("unchecked") private void filterObject(List<String> fields, Object entity) { if (fields == null || fields.isEmpty()) { return; } if (entity instanceof List) { for (Object obj : (List) entity) { filterObject(fields, obj); } } else if (entity instanceof Map) { for (Object obj : ((Map) entity).values()) { filterObject(fields, obj); } } else if (entity instanceof Object[]) { for (Object obj : (Object[]) entity) { filterObject(fields, obj); } } else if (!ClassUtils.isPrimitiveOrWrapper(entity.getClass()) && !(entity instanceof String)) { for (Field field : Utils.getAllDeclaredFields((Class<? extends ParaObject>) entity.getClass())) { try { if (!Modifier.isStatic(field.getModifiers())) { String fieldName = field.getName(); field.setAccessible(true); if (!fields.contains(fieldName) && !isBoolean(field.getType())) { field.set(entity, null); } } } catch (Exception e) { LoggerFactory.getLogger(this.getClass()).warn(null, e); } } } } private boolean isBoolean(Class<?> returnType) { return boolean.class.equals(returnType) || Boolean.class.equals(returnType); } }
fixed FieldFilter - complete rewrite
para-server/src/main/java/com/erudika/para/utils/filters/FieldFilter.java
fixed FieldFilter - complete rewrite
<ide><path>ara-server/src/main/java/com/erudika/para/utils/filters/FieldFilter.java <ide> package com.erudika.para.utils.filters; <ide> <ide> import com.erudika.para.core.ParaObject; <del>import com.erudika.para.utils.Utils; <ide> import java.io.IOException; <del>import java.lang.reflect.Field; <del>import java.lang.reflect.Modifier; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <add>import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.ws.rs.container.ContainerResponseFilter; <ide> import javax.ws.rs.core.Context; <ide> import javax.ws.rs.ext.Provider; <del>import org.apache.commons.lang3.ClassUtils; <add>import org.apache.commons.beanutils.BeanUtils; <ide> import org.apache.commons.lang3.StringUtils; <ide> import org.slf4j.LoggerFactory; <ide> <ide> private HttpServletRequest request; <ide> <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public void filter(ContainerRequestContext requestContext, <ide> ContainerResponseContext responseContext) throws IOException { <del> if (responseContext.getEntity() != null) { <del> String[] sarr = StringUtils.split(request.getParameter("select"), ","); <del> List<String> fields = sarr == null ? new ArrayList<String>(0) : Arrays.asList(sarr); <del> filterObject(fields, responseContext.getEntity()); <add> try { <add> if (responseContext.getEntity() != null && !StringUtils.isBlank(request.getParameter("select"))) { <add> String[] sarr = StringUtils.split(request.getParameter("select"), ","); <add> List<String> fields = sarr == null ? new ArrayList<String>(0) : Arrays.asList(sarr); <add> if (!fields.isEmpty()) { <add> Object entity = responseContext.getEntity(); <add> Object newEntity = null; <add> if (entity instanceof ParaObject) { <add> Map<String, Object> newItem = new HashMap<String, Object>(); <add> for (String field : fields) { <add> newItem.put(field, getProperty(entity, field)); <add> } <add> newEntity = newItem; <add> } else if (entity instanceof Map) { <add> if (((Map) entity).containsKey("items")) { <add> newEntity = new ArrayList<Map<String, Object>>(); <add> for (ParaObject item : (List<ParaObject>) ((Map) entity).get("items")) { <add> Map<String, Object> newItem = new HashMap<String, Object>(); <add> for (String field : fields) { <add> newItem.put(field, getProperty(item, field)); <add> } <add> ((List) newEntity).add(newItem); <add> } <add> ((Map) entity).put("items", newEntity); <add> } <add> } else if (entity instanceof List) { <add> newEntity = new ArrayList<Map<String, Object>>(); <add> if (!((List) entity).isEmpty() && ((List) entity).get(0) instanceof ParaObject) { <add> for (ParaObject item : (List<ParaObject>) entity) { <add> Map<String, Object> newItem = new HashMap<String, Object>(); <add> for (String field : fields) { <add> newItem.put(field, getProperty(item, field)); <add> } <add> ((List) newEntity).add(newItem); <add> } <add> } <add> } <add> if (newEntity != null) { <add> responseContext.setEntity(newEntity); <add> } <add> } <add> } <add> } catch (Exception e) { <add> LoggerFactory.getLogger(this.getClass()).warn(null, e); <ide> } <ide> } <ide> <del> @SuppressWarnings("unchecked") <del> private void filterObject(List<String> fields, Object entity) { <del> if (fields == null || fields.isEmpty()) { <del> return; <del> } <del> if (entity instanceof List) { <del> for (Object obj : (List) entity) { <del> filterObject(fields, obj); <del> } <del> } else if (entity instanceof Map) { <del> for (Object obj : ((Map) entity).values()) { <del> filterObject(fields, obj); <del> } <del> } else if (entity instanceof Object[]) { <del> for (Object obj : (Object[]) entity) { <del> filterObject(fields, obj); <del> } <del> } else if (!ClassUtils.isPrimitiveOrWrapper(entity.getClass()) && !(entity instanceof String)) { <del> for (Field field : Utils.getAllDeclaredFields((Class<? extends ParaObject>) entity.getClass())) { <del> try { <del> if (!Modifier.isStatic(field.getModifiers())) { <del> String fieldName = field.getName(); <del> field.setAccessible(true); <del> if (!fields.contains(fieldName) && !isBoolean(field.getType())) { <del> field.set(entity, null); <del> } <del> } <del> } catch (Exception e) { <del> LoggerFactory.getLogger(this.getClass()).warn(null, e); <del> } <del> } <add> private Object getProperty(Object obj, String prop) { <add> try { <add> return BeanUtils.getProperty(obj, prop); <add> } catch (Exception e) { <add> return null; <ide> } <ide> } <del> <del> private boolean isBoolean(Class<?> returnType) { <del> return boolean.class.equals(returnType) || Boolean.class.equals(returnType); <del> } <ide> }
Java
apache-2.0
05e9f70dcd293b909692c8ebc7485f22bcef3ee2
0
Myasuka/systemml,ckadner/systemml,fmakari/systemml,fmakari/systemml,dusenberrymw/systemml_old,fmakari/systemml,aloknsingh/systemml,fmakari/systemml,dusenberrymw/systemml_old,ckadner/systemml,aloknsingh/systemml,Myasuka/systemml,fmakari/systemml,wjuncdl/systemml,ckadner/systemml,Myasuka/systemml,Myasuka/systemml,aloknsingh/systemml,aloknsingh/systemml,wjuncdl/systemml,wjuncdl/systemml,Myasuka/systemml,wjuncdl/systemml,aloknsingh/systemml,fmakari/systemml,wjuncdl/systemml,aloknsingh/systemml,dusenberrymw/systemml_old,ckadner/systemml,dusenberrymw/systemml_old,Myasuka/systemml,dusenberrymw/systemml_old,dusenberrymw/systemml_old,ckadner/systemml,ckadner/systemml,wjuncdl/systemml
/** * IBM Confidential * OCO Source Materials * (C) Copyright IBM Corp. 2010, 2014 * The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office. */ package com.ibm.bi.dml.hops; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM; import com.ibm.bi.dml.conf.ConfigurationManager; import com.ibm.bi.dml.conf.DMLConfig; import com.ibm.bi.dml.hops.OptimizerUtils.OptimizationType; import com.ibm.bi.dml.lops.Lop; import com.ibm.bi.dml.lops.LopsException; import com.ibm.bi.dml.lops.LopProperties.ExecType; import com.ibm.bi.dml.parser.StatementBlock; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.ValueType; import com.ibm.bi.dml.runtime.controlprogram.LocalVariableMap; import com.ibm.bi.dml.runtime.controlprogram.parfor.ProgramConverter; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDSequence; import com.ibm.bi.dml.runtime.instructions.CPInstructions.Data; import com.ibm.bi.dml.runtime.instructions.CPInstructions.ScalarObject; import com.ibm.bi.dml.runtime.util.UtilFunctions; import com.ibm.bi.dml.sql.sqllops.SQLLops; import com.ibm.bi.dml.sql.sqllops.SQLLops.GENERATES; public abstract class Hop { @SuppressWarnings("unused") private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2013\n" + "US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp."; protected static final Log LOG = LogFactory.getLog(Hop.class.getName()); public static boolean BREAKONSCALARS = false; public static boolean SPLITLARGEMATRIXMULT = true; public static long CPThreshold = 2000; public enum Kind { UnaryOp, BinaryOp, AggUnaryOp, AggBinaryOp, ReorgOp, Reblock, DataOp, LiteralOp, PartitionOp, CrossvalOp, DataGenOp, GenericFunctionOp, TertiaryOp, ParameterizedBuiltinOp, Indexing, FunctionOp }; public enum VISIT_STATUS { DONE, VISITING, NOTVISITED } // static variable to assign an unique ID to every hop that is created private static IDSequence UniqueHopID = new IDSequence(); protected long ID; protected Kind _kind; protected String _name; protected DataType _dataType; protected ValueType _valueType; protected VISIT_STATUS _visited = VISIT_STATUS.NOTVISITED; protected long _dim1 = -1; protected long _dim2 = -1; protected long _rows_in_block = -1; protected long _cols_in_block = -1; protected long _nnz = -1; protected ArrayList<Hop> _parent = new ArrayList<Hop>(); protected ArrayList<Hop> _input = new ArrayList<Hop>(); private Lop _lops = null; private SQLLops _sqllops = null; protected ExecType _etype = null; //currently used exec type protected ExecType _etypeForced = null; //exec type forced via platform or external optimizer // Estimated size for the output produced from this Hop protected double _outputMemEstimate = OptimizerUtils.INVALID_SIZE; // Estimated size for the entire operation represented by this Hop // It includes the memory required for all inputs as well as the output protected double _memEstimate = OptimizerUtils.INVALID_SIZE; protected double _processingMemEstimate = 0; // indicates if there are unknowns during compilation // (in that case re-complication ensures robustness and efficiency) protected boolean _requiresRecompile = false; protected Hop(){ //default constructor for clone } public Hop(Kind k, String l, DataType dt, ValueType vt) { _kind = k; set_name(l); _dataType = dt; _valueType = vt; ID = getNextHopID(); } private static long getNextHopID() { return UniqueHopID.getNextID(); } public long getHopID() { return ID; } public ExecType getExecType() { return _etype; } /** * * @return */ public ExecType getForcedExecType() { return _etypeForced; } /** * * @param etype */ public void setForcedExecType(ExecType etype) { _etypeForced = etype; } /** * * @return */ public abstract boolean allowsAllExecTypes(); /** * */ public void checkAndSetForcedPlatform() { if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) _etypeForced = ExecType.CP; else if ( DMLScript.rtplatform == RUNTIME_PLATFORM.HADOOP ) _etypeForced = ExecType.MR; } /** * Returns the memory estimate for the output produced from this Hop. * It must be invoked only within Hops. From outside Hops, one must * only use getMemEstimate(), which gives memory required to store * all inputs and the output. * * @return */ protected double getOutputSize() { return _outputMemEstimate; } protected double getInputOutputSize() { double sum = this._outputMemEstimate; sum += this._processingMemEstimate; for(Hop h : _input ) { sum += h._outputMemEstimate; } return sum; } protected double getInputSize() { double sum = 0; for(Hop h : _input ) { sum += h._outputMemEstimate; } return sum; } /** * * @param pos * @return */ protected double getInputSize( int pos ){ double ret = 0; if( _input.size()>pos ) ret = _input.get(pos)._outputMemEstimate; return ret; } protected double getIntermediateSize() { return _processingMemEstimate; } /** * NOTES: * * Purpose: Whenever the output dimensions / sparsity of a hop are unknown, this hop * should store its worst-case output statistics (if known) in that table. Subsequent * hops can then * * Invocation: Intended to be called for ALL root nodes of one Hops DAG with the same * (initially empty) memo table. * * @param memo * @return */ public double getMemEstimate() { if ( OptimizerUtils.getOptType() == OptimizationType.MEMORY_BASED ) { if ( ! isMemEstimated() ) { LOG.warn("Nonexisting memory estimate - reestimating w/o memo table."); computeMemEstimate( new MemoTable() ); } return _memEstimate; } else { return OptimizerUtils.INVALID_SIZE; } } /** * Returns memory estimate in bytes * * @param mem */ public void setMemEstimate( double mem ) { _memEstimate = mem; } public boolean isMemEstimated() { return (_memEstimate != OptimizerUtils.INVALID_SIZE); } /** * Computes the estimate of memory required to store the input/output of this hop in memory. * This is the default implementation (orchestration of hop-specific implementation) * that should suffice for most hops. If a hop requires more control, this method should * be overwritten with awareness of (1) output estimates, and (2) propagation of worst-case * matrix characteristics (dimensions, sparsity). * * TODO remove memo table and, on constructor refresh, inference in refresh, single compute mem, * maybe general computeMemEstimate, flags to indicate if estimate or not. * * @return computed estimate */ protected void computeMemEstimate( MemoTable memo ) { long[] wstats = null; //output size estimate switch( get_dataType() ) { case SCALAR: { if( get_valueType()== ValueType.DOUBLE) //default case _outputMemEstimate = OptimizerUtils.DOUBLE_SIZE; else //literalops, dataops _outputMemEstimate = computeOutputMemEstimate(_dim1, _dim2, _nnz); break; } case MATRIX: { if( dimsKnown() ) { //nnz should be known as well, if applicable (see refreshSizeInformation) //1) compute mem estimate based on known dimensions/sparsity (dense if sparsity unknown) long lnnz = ((_nnz>=0)?_nnz:_dim1*_dim2); _outputMemEstimate = computeOutputMemEstimate( _dim1, _dim2, lnnz ); } else if( memo.hasInputStatistics(this) ) { //2) infer the output stats wstats = inferOutputCharacteristics(memo); if( wstats != null ) { //2a) use worst case characteristics to estimate mem long lnnz = ((wstats[2]>=0)?wstats[2]:wstats[0]*wstats[1]); _outputMemEstimate = computeOutputMemEstimate( wstats[0], wstats[1], lnnz ); //propagate worst-case estimate memo.memoizeStatistics(getHopID(), wstats[0], wstats[1], wstats[2]); } else { //System.out.println("could not infer output characteristics for "+this.getOpString()); //2b) unknown output size _outputMemEstimate = OptimizerUtils.DEFAULT_SIZE; } } else { //System.out.println("no stats for "+this.getOpString()); //3) unknown output size _outputMemEstimate = OptimizerUtils.DEFAULT_SIZE; } break; } case OBJECT: case UNKNOWN: { _outputMemEstimate = OptimizerUtils.DEFAULT_SIZE; break; } } //intermediate size estimate if( dimsKnown() ) { //incl scalar output long lnnz = ((_nnz>=0)?_nnz:_dim1*_dim2); _processingMemEstimate = computeIntermediateMemEstimate(_dim1, _dim2, lnnz); } else if( wstats!=null ) { long lnnz = ((wstats[2]>=0)?wstats[2]:wstats[0]*wstats[1]); _processingMemEstimate = computeIntermediateMemEstimate( wstats[0], wstats[1], lnnz ); } //final estimate (sum of inputs/intermediates/output) _memEstimate = getInputOutputSize(); } /** * Computes the hop-specific output memory estimate in bytes. Should be 0 if not * applicable. * * @param dim1 * @param dim2 * @param nnz * @return */ protected abstract double computeOutputMemEstimate( long dim1, long dim2, long nnz ); /** * Computes the hop-specific intermediate memory estimate in bytes. Should be 0 if not * applicable. * * @param dim1 * @param dim2 * @param nnz * @return */ protected abstract double computeIntermediateMemEstimate( long dim1, long dim2, long nnz ); /** * Computes the output matrix characteristics (rows, cols, nnz) based on worst-case output * and/or input estimates. Should return null if dimensions are unknown. * * @param memo * @return */ protected abstract long[] inferOutputCharacteristics( MemoTable memo ); /** * This function is used only for sanity check. * Returns true if estimates for all the hops in the DAG rooted at the current * hop are computed. Returns false if any of the hops have INVALID estimate. * * @return */ public boolean checkEstimates() { boolean childStatus = true; for (Hop h : this.getInput()) childStatus = childStatus && h.checkEstimates(); return childStatus && (_memEstimate != OptimizerUtils.INVALID_SIZE); } /** * Recursively computes memory estimates for all the Hops in the DAG rooted at the * current hop pointed by <code>this</code>. * */ public void refreshMemEstimates( MemoTable memo ) { if (get_visited() == VISIT_STATUS.DONE) return; for (Hop h : this.getInput()) h.refreshMemEstimates( memo ); this.computeMemEstimate( memo ); this.set_visited(VISIT_STATUS.DONE); } /** * This method determines the execution type (CP, MR) based ONLY on the * estimated memory footprint required for this operation, which includes * memory for all inputs and the output represented by this Hop. * * It is used when <code>OptimizationType = MEMORY_BASED</code>. * This optimization schedules an operation to CP whenever inputs+output * fit in memory -- note that this decision MAY NOT be optimal in terms of * execution time. * * @return */ protected ExecType findExecTypeByMemEstimate() { ExecType et = null; char c = ' '; if ( getMemEstimate() < OptimizerUtils.getMemBudget(true) ) { et = ExecType.CP; } else { et = ExecType.MR; c = '*'; } if (LOG.isDebugEnabled()){ String s = String.format(" %c %-5s %-8s (%s,%s) %s", c, getHopID(), getOpString(), OptimizerUtils.toMB(_outputMemEstimate), OptimizerUtils.toMB(_memEstimate), et); //System.out.println(s); LOG.debug(s); } // This is the old format for reference // %c %-5s %-8s (%s,%s) %s\n", c, getHopID(), getOpString(), OptimizerUtils.toMB(_outputMemEstimate), OptimizerUtils.toMB(_memEstimate), et); return et; } public ArrayList<Hop> getParent() { return _parent; } public ArrayList<Hop> getInput() { return _input; } /** * Create bidirectional links * * @param h */ public void addInput( Hop h ) { _input.add(h); h._parent.add(this); } public long get_rows_in_block() { return _rows_in_block; } public void set_rows_in_block(long rowsInBlock) { _rows_in_block = rowsInBlock; } public long get_cols_in_block() { return _cols_in_block; } public void set_cols_in_block(long colsInBlock) { _cols_in_block = colsInBlock; } public void setNnz(long nnz){ _nnz = nnz; } public long getNnz(){ return _nnz; } /** * Should not be used because this might return a too aggressive sparsity estimate. * @return */ @Deprecated public double getSparsity() { if ( _dataType == DataType.SCALAR ) return 1.0; if (dimsKnown() && _nnz > 0) return (double)_nnz/(double)(_dim1*_dim2); else return OptimizerUtils.DEF_SPARSITY; } public Kind getKind() { return _kind; } abstract public Lop constructLops() throws HopsException, LopsException; abstract public SQLLops constructSQLLOPs() throws HopsException; abstract protected ExecType optFindExecType() throws HopsException; abstract public String getOpString(); protected boolean isVector() { return (dimsKnown() && (_dim1 == 1 || _dim2 == 1) ); } protected boolean areDimsBelowThreshold() { return (_dim1 <= Hop.CPThreshold && _dim2 <= Hop.CPThreshold ); } protected boolean dimsKnown() { return ( _dataType == DataType.SCALAR || (_dataType==DataType.MATRIX && _dim1 > 0 && _dim2 > 0) ); } public static void resetVisitStatus( ArrayList<Hop> hops ) { for( Hop hopRoot : hops ) hopRoot.resetVisitStatus(); } public void resetVisitStatus() { if (this.get_visited() == Hop.VISIT_STATUS.NOTVISITED) return; for (Hop h : this.getInput()) h.resetVisitStatus(); if(this.get_sqllops() != null) this.get_sqllops().set_visited(VISIT_STATUS.NOTVISITED); this.set_visited(Hop.VISIT_STATUS.NOTVISITED); } public void rule_BlockSizeAndReblock(int GLOBAL_BLOCKSIZE) throws HopsException { // TODO BJR: traverse HOP DAG and insert Reblock HOPs // Go to the source(s) of the DAG for (Hop hi : this.getInput()) { if (get_visited() != Hop.VISIT_STATUS.DONE) hi.rule_BlockSizeAndReblock(GLOBAL_BLOCKSIZE); } boolean canReblock = true; if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) canReblock = false; if (this instanceof DataOp) { // if block size does not match if (canReblock && get_dataType() != DataType.SCALAR && (get_rows_in_block() != GLOBAL_BLOCKSIZE || get_cols_in_block() != GLOBAL_BLOCKSIZE)) { if (((DataOp) this).get_dataop() == DataOp.DataOpTypes.PERSISTENTREAD) { // insert reblock after the hop ReblockOp r = new ReblockOp(this, GLOBAL_BLOCKSIZE, GLOBAL_BLOCKSIZE); r.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); r.computeMemEstimate(null); r.set_visited(Hop.VISIT_STATUS.DONE); } else if (((DataOp) this).get_dataop() == DataOp.DataOpTypes.PERSISTENTWRITE) { if (get_rows_in_block() == -1 && get_cols_in_block() == -1) { // if this dataop is for cell ouput, then no reblock is // needed as (A) all jobtypes can produce block2cell and // cell2cell and (B) we don't generate an explicit // instruction for it (the info is conveyed through // OutputInfo. } else if (getInput().get(0) instanceof ReblockOp && getInput().get(0).getParent().size() == 1) { // if a reblock is feeding into this, then use it if // this is // the only parent, otherwise new Reblock getInput().get(0).set_rows_in_block(this.get_rows_in_block()); getInput().get(0).set_cols_in_block(this.get_cols_in_block()); } else { ReblockOp r = new ReblockOp(this); r.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); r.computeMemEstimate(null); r.set_visited(Hop.VISIT_STATUS.DONE); } } else if (((DataOp) this).get_dataop() == DataOp.DataOpTypes.TRANSIENTWRITE || ((DataOp) this).get_dataop() == DataOp.DataOpTypes.TRANSIENTREAD) { if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) { // simply copy the values from its input set_rows_in_block(getInput().get(0).get_rows_in_block()); set_cols_in_block(getInput().get(0).get_cols_in_block()); } else { // by default, all transient reads and writes are in blocked format set_rows_in_block(GLOBAL_BLOCKSIZE); set_cols_in_block(GLOBAL_BLOCKSIZE); } } else { throw new HopsException(this.printErrorLocation() + "unexpected non-scalar Data HOP in reblock.\n"); } } } else { // TODO: following two lines are commented, and the subsequent hack is used instead! //set_rows_per_block(GLOBAL_BLOCKSIZE); //set_cols_per_block(GLOBAL_BLOCKSIZE); // TODO: this is hack! /* * Handle hops whose output dimensions are unknown! * * Constraint C1: * Currently, only ctable() and groupedAggregate() fall into this category. * The MR jobs for both these functions run in "cell" mode and hence make their * blocking dimensions to (-1,-1). * * Constraint C2: * Blocking dimensions are not applicable for hops that produce scalars. * CMCOV and GroupedAgg jobs always run in "cell" mode, and hence they * produce output in cell format. * * Constraint C3: * Remaining hops will get their blocking dimensions from their input hops. */ if ( this instanceof ReblockOp ) { set_rows_in_block(GLOBAL_BLOCKSIZE); set_cols_in_block(GLOBAL_BLOCKSIZE); } // Constraint C1: //else if ( (this instanceof ParameterizedBuiltinOp && ((ParameterizedBuiltinOp)this)._op == ParamBuiltinOp.GROUPEDAGG) ) { // set_rows_in_block(-1); // set_cols_in_block(-1); //} // Constraint C2: else if ( this.get_dataType() == DataType.SCALAR ) { set_rows_in_block(-1); set_cols_in_block(-1); } // Constraint C3: else { if ( !canReblock ) { set_rows_in_block(-1); set_cols_in_block(-1); } else { set_rows_in_block(GLOBAL_BLOCKSIZE); set_cols_in_block(GLOBAL_BLOCKSIZE); } // if any input is not blocked then the output of current Hop should not be blocked for ( Hop h : getInput() ) { if ( h.get_dataType() == DataType.MATRIX && h.get_rows_in_block() == -1 && h.get_cols_in_block() == -1 ) { set_rows_in_block(-1); set_cols_in_block(-1); break; } } } } this.set_visited(Hop.VISIT_STATUS.DONE); } /** * * @param dataops * @param literalops * @return * @throws HopsException */ public int rule_CommonSubexpressionElimination_MergeLeafs( HashMap<String, Hop> dataops, HashMap<String, Hop> literalops ) throws HopsException { int ret = 0; if( get_visited() == Hop.VISIT_STATUS.DONE ) return ret; if( getInput().size()==0 ) //LEAF NODE { if( this instanceof LiteralOp ) { if( !literalops.containsKey(get_name()) ) literalops.put(get_name(), this); } else if( this instanceof DataOp && ((DataOp)this).isRead()) { if(!dataops.containsKey(get_name()) ) dataops.put(get_name(), this); } } else //INNER NODE { //merge leaf nodes (data, literal) for( int i=0; i<getInput().size(); i++ ) { Hop hi = getInput().get(i); if( hi instanceof DataOp && ((DataOp)hi).isRead() && dataops.containsKey(hi.get_name()) ) { //replace child node ref Hop tmp = dataops.get(hi.get_name()); tmp.getParent().add(this); getInput().set(i, tmp); ret++; } else if( hi instanceof LiteralOp && literalops.containsKey(hi.get_name()) ) { Hop tmp = literalops.get(hi.get_name()); if(hi.get_valueType()==tmp.get_valueType()) { //replace child node ref tmp.getParent().add(this); getInput().set(i, tmp); ret++; } } //recursive invocation (direct return on merged nodes) ret += hi.rule_CommonSubexpressionElimination_MergeLeafs(dataops, literalops); } } this.set_visited(Hop.VISIT_STATUS.DONE); return ret; } public int rule_CommonSubexpressionElimination( HashMap<String, Hop> dataops, HashMap<String, Hop> literalops ) throws HopsException { int ret = 0; if( get_visited() == Hop.VISIT_STATUS.DONE ) return ret; //step 1: merge childs recursively first for(Hop hi : this.getInput()) ret += hi.rule_CommonSubexpressionElimination(dataops, literalops); //step 2: merge parent nodes if( getParent().size()>1 ) //multiple consumers { //for all pairs for( int i=0; i<getParent().size()-1; i++ ) for( int j=i+1; j<getParent().size(); j++ ) { Hop h1 = getParent().get(i); Hop h2 = getParent().get(j); if( h1==h2 ) { //remove redundant h2 from parent list getParent().remove(j); j--; } else if( h1.compare(h2) ) //merge h2 into h1 { //remove h2 from parent list getParent().remove(j); //replace h2 w/ h1 in h2-parent inputs ArrayList<Hop> parent = h2.getParent(); for( Hop p : parent ) for( int k=0; k<p.getInput().size(); k++ ) if( p.getInput().get(k)==h2 ) { p.getInput().set(k, h1); h1.getParent().add(p); } //replace h2 w/ h1 in h2-input parents for( Hop in : h2.getInput() ) in.getParent().remove(h2); ret++; j--; } } } this.set_visited(Hop.VISIT_STATUS.DONE); return ret; } /** * Test and debugging only. * * @param h * @throws HopsException */ public void checkParentChildPointers( ) throws HopsException { if( get_visited() == VISIT_STATUS.DONE ) return; for( Hop in : getInput() ) { if( !in.getParent().contains(this) ) throw new HopsException("Parent-Child pointers incorrect."); in.checkParentChildPointers(); } set_visited(VISIT_STATUS.DONE); } public void rule_ConstantFolding( ) throws HopsException { rConstantFoldingBinaryExpression(this); } public void rule_RehangTransientWriteParents(StatementBlock sb) throws HopsException { if (this instanceof DataOp && ((DataOp) this).get_dataop() == DataOpTypes.TRANSIENTWRITE && !this.getParent().isEmpty()) { // update parents inputs with data op input for (Hop p : this.getParent()) { p.getInput().set(p.getInput().indexOf(this), this.getInput().get(0)); } // update dataop input parent to add new parents except for // dataop itself this.getInput().get(0).getParent().addAll(this.getParent()); // remove dataop parents this.getParent().clear(); // add dataop as root for this Hops DAG sb.get_hops().add(this); // do the same thing for my inputs (children) for (Hop hi : this.getInput()) { hi.rule_RehangTransientWriteParents(sb); } } } /** * rule_OptimizeMMChains(): This method recurses through all Hops in the DAG * to find chains that need to be optimized. */ public void rule_OptimizeMMChains() throws HopsException { if(this.get_visited() == Hop.VISIT_STATUS.DONE) return; if (this.getKind() == Hop.Kind.AggBinaryOp && ((AggBinaryOp) this).isMatrixMultiply() && this.get_visited() != Hop.VISIT_STATUS.DONE) { // Try to find and optimize the chain in which current Hop is the // last operator this.optimizeMMChain(); } for (Hop hi : this.getInput()) hi.rule_OptimizeMMChains(); this.set_visited(Hop.VISIT_STATUS.DONE); } /** * mmChainDP(): Core method to perform dynamic programming on a given array * of matrix dimensions. */ public int[][] mmChainDP(long dimArray[], int size) { long dpMatrix[][] = new long[size][size]; int split[][] = new int[size][size]; int i, j, k, l; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { dpMatrix[i][j] = 0; split[i][j] = -1; } } long cost; long MAX = Long.MAX_VALUE; for (l = 2; l <= size; l++) { // chain length for (i = 0; i < size - l + 1; i++) { j = i + l - 1; // find cost of (i,j) dpMatrix[i][j] = MAX; for (k = i; k <= j - 1; k++) { cost = dpMatrix[i][k] + dpMatrix[k + 1][j] + (dimArray[i] * dimArray[k + 1] * dimArray[j + 1]); if (cost < dpMatrix[i][j]) { dpMatrix[i][j] = cost; split[i][j] = k; } } } } return split; } /** * mmChainRelinkHops(): This method gets invoked after finding the optimal * order (split[][]) from dynamic programming. It relinks the Hops that are * part of the mmChain. mmChain : basic operands in the entire matrix * multiplication chain. mmOperators : Hops that store the intermediate * results in the chain. For example: A = B %*% (C %*% D) there will be * three Hops in mmChain (B,C,D), and two Hops in mmOperators (one for each * %*%) . */ private void mmChainRelinkHops(Hop h, int i, int j, ArrayList<Hop> mmChain, ArrayList<Hop> mmOperators, int opIndex, int[][] split) { if (i == j) return; Hop input1, input2; // Set Input1 for current Hop h if (i == split[i][j]) { input1 = mmChain.get(i); h.getInput().add(mmChain.get(i)); mmChain.get(i).getParent().add(h); } else { input1 = mmOperators.get(opIndex); h.getInput().add(mmOperators.get(opIndex)); mmOperators.get(opIndex).getParent().add(h); opIndex = opIndex + 1; } // Set Input2 for current Hop h if (split[i][j] + 1 == j) { input2 = mmChain.get(j); h.getInput().add(mmChain.get(j)); mmChain.get(j).getParent().add(h); } else { input2 = mmOperators.get(opIndex); h.getInput().add(mmOperators.get(opIndex)); mmOperators.get(opIndex).getParent().add(h); opIndex = opIndex + 1; } // Find children for both the inputs mmChainRelinkHops(h.getInput().get(0), i, split[i][j], mmChain, mmOperators, opIndex, split); mmChainRelinkHops(h.getInput().get(1), split[i][j] + 1, j, mmChain, mmOperators, opIndex, split); // Propagate properties of input hops to current hop h h.set_dim1(input1.get_dim1()); h.set_rows_in_block(input1.get_rows_in_block()); h.set_dim2(input2.get_dim2()); h.set_cols_in_block(input2.get_cols_in_block()); } private void clearLinksWithinChain ( ArrayList<Hop> operators ) throws HopsException { Hop op, input1, input2; for ( int i=0; i < operators.size(); i++ ) { op = operators.get(i); if ( op.getInput().size() != 2 || (i != 0 && op.getParent().size() > 1 ) ) { throw new HopsException(this.printErrorLocation() + "Unexpected error while applying optimization on matrix-mult chain. \n"); } input1 = op.getInput().get(0); input2 = op.getInput().get(1); op.getInput().clear(); input1.getParent().remove(op); input2.getParent().remove(op); } } private long [] getDimArray ( ArrayList<Hop> chain ) throws HopsException { // Build the array containing dimensions from all matrices in the // chain long dimArray[] = new long[chain.size() + 1]; // check the dimensions in the matrix chain to insure all dimensions are known boolean shortCircuit = false; for (int i=0; i< chain.size(); i++){ if (chain.get(i)._dim1 <= 0 || chain.get(i)._dim2 <= 0) shortCircuit = true; } if (shortCircuit){ for (int i=0; i< dimArray.length; i++){ dimArray[i] = 1; } LOG.trace("short-circuit optimizeMMChain() for matrices with unknown size"); return dimArray; } for (int i = 0; i < chain.size(); i++) { if (i == 0) { dimArray[i] = chain.get(i).get_dim1(); if (dimArray[i] <= 0) { throw new HopsException(this.printErrorLocation() + "Hops::optimizeMMChain() : Invalid Matrix Dimension: " + dimArray[i]); } } else { if (chain.get(i - 1).get_dim2() != chain.get(i) .get_dim1()) { throw new HopsException(this.printErrorLocation() + "Hops::optimizeMMChain() : Matrix Dimension Mismatch"); } } dimArray[i + 1] = chain.get(i).get_dim2(); if (dimArray[i + 1] <= 0) { throw new HopsException(this.printErrorLocation() + "Hops::optimizeMMChain() : Invalid Matrix Dimension: " + dimArray[i + 1]); } } return dimArray; } private int inputCount ( Hop p, Hop h ) { int count = 0; for ( int i=0; i < p.getInput().size(); i++ ) if ( p.getInput().get(i).equals(h) ) count++; return count; } /** * optimizeMMChain(): It optimizes the matrix multiplication chain in which * the last Hop is "this". Step-1) Identify the chain (mmChain). (Step-2) clear all * links among the Hops that are involved in mmChain. (Step-3) Find the * optimal ordering (dynamic programming) (Step-4) Relink the hops in * mmChain. */ private void optimizeMMChain() throws HopsException { LOG.trace("MM Chain Optimization for HOP: (" + " " + getKind() + ", " + getHopID() + ", " + get_name() + ")"); ArrayList<Hop> mmChain = new ArrayList<Hop>(); ArrayList<Hop> mmOperators = new ArrayList<Hop>(); ArrayList<Hop> tempList; /* * Step-1: Identify the chain (mmChain) & clear all links among the Hops * that are involved in mmChain. */ mmOperators.add(this); // Initialize mmChain with my inputs for (Hop hi : this.getInput()) { mmChain.add(hi); } // expand each Hop in mmChain to find the entire matrix multiplication // chain int i = 0; while (i < mmChain.size()) { boolean expandable = false; Hop h = mmChain.get(i); /* * Check if mmChain[i] is expandable: * 1) It must be MATMULT * 2) It must not have been visited already * (one MATMULT should get expanded only in one chain) * 3) Its output should not be used in multiple places * (either within chain or outside the chain) */ if (h.getKind() == Hop.Kind.AggBinaryOp && ((AggBinaryOp) h).isMatrixMultiply() && h.get_visited() != Hop.VISIT_STATUS.DONE) { // check if the output of "h" is used at multiple places. If yes, it can // not be expanded. if (h.getParent().size() > 1 || inputCount( (Hop) ((h.getParent().toArray())[0]), h) > 1 ) { expandable = false; break; } else expandable = true; } h.set_visited(Hop.VISIT_STATUS.DONE); if ( !expandable ) { i = i + 1; } else { tempList = mmChain.get(i).getInput(); if (tempList.size() != 2) { throw new HopsException(this.printErrorLocation() + "Hops::rule_OptimizeMMChain(): AggBinary must have exactly two inputs."); } // add current operator to mmOperators, and its input nodes to mmChain mmOperators.add(mmChain.get(i)); mmChain.set(i, tempList.get(0)); mmChain.add(i + 1, tempList.get(1)); } } // print the MMChain if (LOG.isTraceEnabled()) { LOG.trace("Identified MM Chain: "); //System.out.print("MMChain_" + getHopID() + " (" + mmChain.size() + "): "); for (Hop h : mmChain) { LOG.trace("Hop " + h.get_name() + "(" + h.getKind() + ", " + h.getHopID() + ")" + " " + h.get_dim1() + "x" + h.get_dim2()); //System.out.print("[" + h.get_name() + "(" + h.getKind() + ", " + h.getHopID() + ")" + " " + h.get_dim1() + "x" + h.get_dim2() + "] "); } //System.out.println(""); LOG.trace("--End of MM Chain--"); } if (mmChain.size() == 2) { // If the chain size is 2, then there is nothing to optimize. return; } else { // Step-2: clear the links among Hops within the identified chain clearLinksWithinChain ( mmOperators ); // Step-3: Find the optimal ordering via dynamic programming. long dimArray[] = getDimArray ( mmChain ); // Invoke Dynamic Programming int size = mmChain.size(); int[][] split = new int[size][size]; split = mmChainDP(dimArray, mmChain.size()); // Step-4: Relink the hops using the optimal ordering (split[][]) found from DP. mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, 1, split); } //System.out.println(" ."); } public void printMe() throws HopsException { if (LOG.isDebugEnabled()) { StringBuilder s = new StringBuilder(""); s.append(_kind + " " + getHopID() + "\n"); s.append(" Label: " + get_name() + "; DataType: " + _dataType + "; ValueType: " + _valueType + "\n"); s.append(" Parent: "); for (Hop h : getParent()) { s.append(h.hashCode() + "; "); } ; s.append("\n Input: "); for (Hop h : getInput()) { s.append(h.getHopID() + "; "); } s.append("\n dims [" + _dim1 + "," + _dim2 + "] blk [" + _rows_in_block + "," + _cols_in_block + "] nnz " + _nnz); s.append(" MemEstimate = Out " + (_outputMemEstimate/1024/1024) + " MB, In&Out " + (_memEstimate/1024/1024) + " MB" ); LOG.debug(s.toString()); } } public long get_dim1() { return _dim1; } public void set_dim1(long dim1) { _dim1 = dim1; } public long get_dim2() { return _dim2; } public Lop get_lops() { return _lops; } public void set_lops(Lop lops) { _lops = lops; } public SQLLops get_sqllops() { return _sqllops; } public void set_sqllops(SQLLops sqllops) { _sqllops = sqllops; } public void set_dim2(long dim2) { _dim2 = dim2; } public VISIT_STATUS get_visited() { return _visited; } public DataType get_dataType() { return _dataType; } public void set_dataType( DataType dt ) { _dataType = dt; } public void set_visited(VISIT_STATUS visited) { _visited = visited; } public void set_name(String _name) { this._name = _name; } public String get_name() { return _name; } public ValueType get_valueType() { return _valueType; } // TODO BJR: I intend to remove OpOp1.MINUS, once we made the change public enum OpOp1 { MINUS, NOT, ABS, SIN, COS, TAN, ASIN, ACOS, ATAN, SQRT, LOG, EXP, CAST_AS_SCALAR, PRINT, EIGEN, NROW, NCOL, LENGTH, ROUND, IQM, PRINT2 } // Operations that require two operands public enum OpOp2 { PLUS, MINUS, MULT, DIV, MODULUS, LESS, LESSEQUAL, GREATER, GREATEREQUAL, EQUAL, NOTEQUAL, MIN, MAX, AND, OR, LOG, POW, PRINT, CONCAT, QUANTILE, INTERQUANTILE, IQM, CENTRALMOMENT, COVARIANCE, APPEND, SEQINCR, INVALID }; // Operations that require 3 operands public enum OpOp3 { QUANTILE, INTERQUANTILE, CTABLE, CENTRALMOMENT, COVARIANCE, INVALID }; public enum AggOp { SUM, MIN, MAX, TRACE, PROD, MEAN, MAXINDEX }; public enum ReOrgOp { TRANSPOSE, DIAG_V2M, DIAG_M2V, RESHAPE }; public enum DataGenMethod { RAND, SEQ, INVALID }; public enum ParamBuiltinOp { INVALID, CDF, GROUPEDAGG, RMEMPTY }; /** * Functions that are built in, but whose execution takes place in an * external library */ public enum ExtBuiltInOp { EIGEN, CHOLESKY }; public enum FileFormatTypes { TEXT, BINARY, MM, CSV }; public enum DataOpTypes { PERSISTENTREAD, PERSISTENTWRITE, TRANSIENTREAD, TRANSIENTWRITE, FUNCTIONOUTPUT }; public enum Direction { RowCol, Row, Col }; static public HashMap<DataOpTypes, com.ibm.bi.dml.lops.Data.OperationTypes> HopsData2Lops; static { HopsData2Lops = new HashMap<Hop.DataOpTypes, com.ibm.bi.dml.lops.Data.OperationTypes>(); HopsData2Lops.put(DataOpTypes.PERSISTENTREAD, com.ibm.bi.dml.lops.Data.OperationTypes.READ); HopsData2Lops.put(DataOpTypes.PERSISTENTWRITE, com.ibm.bi.dml.lops.Data.OperationTypes.WRITE); HopsData2Lops.put(DataOpTypes.TRANSIENTWRITE, com.ibm.bi.dml.lops.Data.OperationTypes.WRITE); HopsData2Lops.put(DataOpTypes.TRANSIENTREAD, com.ibm.bi.dml.lops.Data.OperationTypes.READ); } static public HashMap<Hop.AggOp, com.ibm.bi.dml.lops.Aggregate.OperationTypes> HopsAgg2Lops; static { HopsAgg2Lops = new HashMap<Hop.AggOp, com.ibm.bi.dml.lops.Aggregate.OperationTypes>(); HopsAgg2Lops.put(AggOp.SUM, com.ibm.bi.dml.lops.Aggregate.OperationTypes.KahanSum); // HopsAgg2Lops.put(AggOp.SUM, dml.lops.Aggregate.OperationTypes.Sum); HopsAgg2Lops.put(AggOp.TRACE, com.ibm.bi.dml.lops.Aggregate.OperationTypes.KahanTrace); HopsAgg2Lops.put(AggOp.MIN, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Min); HopsAgg2Lops.put(AggOp.MAX, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Max); HopsAgg2Lops.put(AggOp.MAXINDEX, com.ibm.bi.dml.lops.Aggregate.OperationTypes.MaxIndex); HopsAgg2Lops.put(AggOp.PROD, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Product); HopsAgg2Lops.put(AggOp.MEAN, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Mean); } static public HashMap<ReOrgOp, com.ibm.bi.dml.lops.Transform.OperationTypes> HopsTransf2Lops; static { HopsTransf2Lops = new HashMap<ReOrgOp, com.ibm.bi.dml.lops.Transform.OperationTypes>(); HopsTransf2Lops.put(ReOrgOp.TRANSPOSE, com.ibm.bi.dml.lops.Transform.OperationTypes.Transpose); HopsTransf2Lops.put(ReOrgOp.DIAG_V2M, com.ibm.bi.dml.lops.Transform.OperationTypes.VectortoDiagMatrix); //HopsTransf2Lops.put(ReorgOp.DIAG_M2V, dml.lops.Transform.OperationTypes.MatrixtoDiagVector); HopsTransf2Lops.put(ReOrgOp.RESHAPE, com.ibm.bi.dml.lops.Transform.OperationTypes.ReshapeMatrix); } static public HashMap<Hop.Direction, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes> HopsDirection2Lops; static { HopsDirection2Lops = new HashMap<Hop.Direction, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes>(); HopsDirection2Lops.put(Direction.RowCol, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes.RowCol); HopsDirection2Lops.put(Direction.Col, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes.Col); HopsDirection2Lops.put(Direction.Row, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes.Row); } static public HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Binary.OperationTypes> HopsOpOp2LopsB; static { HopsOpOp2LopsB = new HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Binary.OperationTypes>(); HopsOpOp2LopsB.put(OpOp2.PLUS, com.ibm.bi.dml.lops.Binary.OperationTypes.ADD); HopsOpOp2LopsB.put(OpOp2.MINUS, com.ibm.bi.dml.lops.Binary.OperationTypes.SUBTRACT); HopsOpOp2LopsB.put(OpOp2.MULT, com.ibm.bi.dml.lops.Binary.OperationTypes.MULTIPLY); HopsOpOp2LopsB.put(OpOp2.DIV, com.ibm.bi.dml.lops.Binary.OperationTypes.DIVIDE); HopsOpOp2LopsB.put(OpOp2.MODULUS, com.ibm.bi.dml.lops.Binary.OperationTypes.MODULUS); HopsOpOp2LopsB.put(OpOp2.LESS, com.ibm.bi.dml.lops.Binary.OperationTypes.LESS_THAN); HopsOpOp2LopsB.put(OpOp2.LESSEQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.LESS_THAN_OR_EQUALS); HopsOpOp2LopsB.put(OpOp2.GREATER, com.ibm.bi.dml.lops.Binary.OperationTypes.GREATER_THAN); HopsOpOp2LopsB.put(OpOp2.GREATEREQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.GREATER_THAN_OR_EQUALS); HopsOpOp2LopsB.put(OpOp2.EQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.EQUALS); HopsOpOp2LopsB.put(OpOp2.NOTEQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.NOT_EQUALS); HopsOpOp2LopsB.put(OpOp2.MIN, com.ibm.bi.dml.lops.Binary.OperationTypes.MIN); HopsOpOp2LopsB.put(OpOp2.MAX, com.ibm.bi.dml.lops.Binary.OperationTypes.MAX); HopsOpOp2LopsB.put(OpOp2.AND, com.ibm.bi.dml.lops.Binary.OperationTypes.OR); HopsOpOp2LopsB.put(OpOp2.OR, com.ibm.bi.dml.lops.Binary.OperationTypes.AND); HopsOpOp2LopsB.put(OpOp2.POW, com.ibm.bi.dml.lops.Binary.OperationTypes.NOTSUPPORTED); HopsOpOp2LopsB.put(OpOp2.LOG, com.ibm.bi.dml.lops.Binary.OperationTypes.NOTSUPPORTED); } static public HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.BinaryCP.OperationTypes> HopsOpOp2LopsBS; static { HopsOpOp2LopsBS = new HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.BinaryCP.OperationTypes>(); HopsOpOp2LopsBS.put(OpOp2.PLUS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.ADD); HopsOpOp2LopsBS.put(OpOp2.MINUS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.SUBTRACT); HopsOpOp2LopsBS.put(OpOp2.MULT, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MULTIPLY); HopsOpOp2LopsBS.put(OpOp2.DIV, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.DIVIDE); HopsOpOp2LopsBS.put(OpOp2.MODULUS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MODULUS); HopsOpOp2LopsBS.put(OpOp2.LESS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.LESS_THAN); HopsOpOp2LopsBS.put(OpOp2.LESSEQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.LESS_THAN_OR_EQUALS); HopsOpOp2LopsBS.put(OpOp2.GREATER, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.GREATER_THAN); HopsOpOp2LopsBS.put(OpOp2.GREATEREQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.GREATER_THAN_OR_EQUALS); HopsOpOp2LopsBS.put(OpOp2.EQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.EQUALS); HopsOpOp2LopsBS.put(OpOp2.NOTEQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.NOT_EQUALS); HopsOpOp2LopsBS.put(OpOp2.MIN, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MIN); HopsOpOp2LopsBS.put(OpOp2.MAX, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MAX); HopsOpOp2LopsBS.put(OpOp2.AND, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.AND); HopsOpOp2LopsBS.put(OpOp2.OR, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.OR); HopsOpOp2LopsBS.put(OpOp2.LOG, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.LOG); HopsOpOp2LopsBS.put(OpOp2.POW, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.POW); HopsOpOp2LopsBS.put(OpOp2.PRINT, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.PRINT); HopsOpOp2LopsBS.put(OpOp2.SEQINCR, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.SEQINCR); } static public HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Unary.OperationTypes> HopsOpOp2LopsU; static { HopsOpOp2LopsU = new HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Unary.OperationTypes>(); HopsOpOp2LopsU.put(OpOp2.PLUS, com.ibm.bi.dml.lops.Unary.OperationTypes.ADD); HopsOpOp2LopsU.put(OpOp2.MINUS, com.ibm.bi.dml.lops.Unary.OperationTypes.SUBTRACT); HopsOpOp2LopsU.put(OpOp2.MULT, com.ibm.bi.dml.lops.Unary.OperationTypes.MULTIPLY); HopsOpOp2LopsU.put(OpOp2.DIV, com.ibm.bi.dml.lops.Unary.OperationTypes.DIVIDE); HopsOpOp2LopsU.put(OpOp2.MODULUS, com.ibm.bi.dml.lops.Unary.OperationTypes.MODULUS); HopsOpOp2LopsU.put(OpOp2.LESSEQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.LESS_THAN_OR_EQUALS); HopsOpOp2LopsU.put(OpOp2.LESS, com.ibm.bi.dml.lops.Unary.OperationTypes.LESS_THAN); HopsOpOp2LopsU.put(OpOp2.GREATEREQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.GREATER_THAN_OR_EQUALS); HopsOpOp2LopsU.put(OpOp2.GREATER, com.ibm.bi.dml.lops.Unary.OperationTypes.GREATER_THAN); HopsOpOp2LopsU.put(OpOp2.EQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.EQUALS); HopsOpOp2LopsU.put(OpOp2.NOTEQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.NOT_EQUALS); HopsOpOp2LopsU.put(OpOp2.AND, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); HopsOpOp2LopsU.put(OpOp2.OR, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); HopsOpOp2LopsU.put(OpOp2.MAX, com.ibm.bi.dml.lops.Unary.OperationTypes.MAX); HopsOpOp2LopsU.put(OpOp2.MIN, com.ibm.bi.dml.lops.Unary.OperationTypes.MIN); HopsOpOp2LopsU.put(OpOp2.LOG, com.ibm.bi.dml.lops.Unary.OperationTypes.LOG); HopsOpOp2LopsU.put(OpOp2.POW, com.ibm.bi.dml.lops.Unary.OperationTypes.POW); } static public HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.Unary.OperationTypes> HopsOpOp1LopsU; static { HopsOpOp1LopsU = new HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.Unary.OperationTypes>(); HopsOpOp1LopsU.put(OpOp1.MINUS, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); HopsOpOp1LopsU.put(OpOp1.NOT, com.ibm.bi.dml.lops.Unary.OperationTypes.NOT); HopsOpOp1LopsU.put(OpOp1.ABS, com.ibm.bi.dml.lops.Unary.OperationTypes.ABS); HopsOpOp1LopsU.put(OpOp1.SIN, com.ibm.bi.dml.lops.Unary.OperationTypes.SIN); HopsOpOp1LopsU.put(OpOp1.COS, com.ibm.bi.dml.lops.Unary.OperationTypes.COS); HopsOpOp1LopsU.put(OpOp1.TAN, com.ibm.bi.dml.lops.Unary.OperationTypes.TAN); HopsOpOp1LopsU.put(OpOp1.ASIN, com.ibm.bi.dml.lops.Unary.OperationTypes.ASIN); HopsOpOp1LopsU.put(OpOp1.ACOS, com.ibm.bi.dml.lops.Unary.OperationTypes.ACOS); HopsOpOp1LopsU.put(OpOp1.ATAN, com.ibm.bi.dml.lops.Unary.OperationTypes.ATAN); HopsOpOp1LopsU.put(OpOp1.SQRT, com.ibm.bi.dml.lops.Unary.OperationTypes.SQRT); HopsOpOp1LopsU.put(OpOp1.EXP, com.ibm.bi.dml.lops.Unary.OperationTypes.EXP); HopsOpOp1LopsU.put(OpOp1.LOG, com.ibm.bi.dml.lops.Unary.OperationTypes.LOG); HopsOpOp1LopsU.put(OpOp1.ROUND, com.ibm.bi.dml.lops.Unary.OperationTypes.ROUND); HopsOpOp1LopsU.put(OpOp1.CAST_AS_SCALAR, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); } static public HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.UnaryCP.OperationTypes> HopsOpOp1LopsUS; static { HopsOpOp1LopsUS = new HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.UnaryCP.OperationTypes>(); HopsOpOp1LopsUS.put(OpOp1.MINUS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NOTSUPPORTED); HopsOpOp1LopsUS.put(OpOp1.NOT, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NOT); HopsOpOp1LopsUS.put(OpOp1.ABS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ABS); HopsOpOp1LopsUS.put(OpOp1.SIN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.SIN); HopsOpOp1LopsUS.put(OpOp1.COS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.COS); HopsOpOp1LopsUS.put(OpOp1.TAN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.TAN); HopsOpOp1LopsUS.put(OpOp1.ASIN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ASIN); HopsOpOp1LopsUS.put(OpOp1.ACOS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ACOS); HopsOpOp1LopsUS.put(OpOp1.ATAN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ATAN); HopsOpOp1LopsUS.put(OpOp1.SQRT, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.SQRT); HopsOpOp1LopsUS.put(OpOp1.EXP, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.EXP); HopsOpOp1LopsUS.put(OpOp1.LOG, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.LOG); HopsOpOp1LopsUS.put(OpOp1.CAST_AS_SCALAR, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.CAST_AS_SCALAR); HopsOpOp1LopsUS.put(OpOp1.NROW, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NROW); HopsOpOp1LopsUS.put(OpOp1.NCOL, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NCOL); HopsOpOp1LopsUS.put(OpOp1.LENGTH, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.LENGTH); HopsOpOp1LopsUS.put(OpOp1.PRINT, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.PRINT); HopsOpOp1LopsUS.put(OpOp1.PRINT2, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.PRINT2); HopsOpOp1LopsUS.put(OpOp1.ROUND, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ROUND); } static public HashMap<Hop.OpOp1, String> HopsOpOp12String; static { HopsOpOp12String = new HashMap<OpOp1, String>(); HopsOpOp12String.put(OpOp1.ABS, "abs"); HopsOpOp12String.put(OpOp1.CAST_AS_SCALAR, "castAsScalar"); HopsOpOp12String.put(OpOp1.COS, "cos"); HopsOpOp12String.put(OpOp1.EIGEN, "eigen"); HopsOpOp12String.put(OpOp1.EXP, "exp"); HopsOpOp12String.put(OpOp1.IQM, "iqm"); HopsOpOp12String.put(OpOp1.LENGTH, "length"); HopsOpOp12String.put(OpOp1.LOG, "log"); HopsOpOp12String.put(OpOp1.MINUS, "-"); HopsOpOp12String.put(OpOp1.NCOL, "ncol"); HopsOpOp12String.put(OpOp1.NOT, "!"); HopsOpOp12String.put(OpOp1.NROW, "nrow"); HopsOpOp12String.put(OpOp1.PRINT, "print"); HopsOpOp12String.put(OpOp1.PRINT2, "print2"); HopsOpOp12String.put(OpOp1.ROUND, "round"); HopsOpOp12String.put(OpOp1.SIN, "sin"); HopsOpOp12String.put(OpOp1.SQRT, "sqrt"); HopsOpOp12String.put(OpOp1.TAN, "tan"); HopsOpOp12String.put(OpOp1.ASIN, "asin"); HopsOpOp12String.put(OpOp1.ACOS, "acos"); HopsOpOp12String.put(OpOp1.ATAN, "atan"); } static public HashMap<Hop.ParamBuiltinOp, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes> HopsParameterizedBuiltinLops; static { HopsParameterizedBuiltinLops = new HashMap<Hop.ParamBuiltinOp, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes>(); HopsParameterizedBuiltinLops.put(ParamBuiltinOp.CDF, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes.CDF); HopsParameterizedBuiltinLops.put(ParamBuiltinOp.RMEMPTY, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes.RMEMPTY); } static public HashMap<Hop.OpOp2, String> HopsOpOp2String; static { HopsOpOp2String = new HashMap<Hop.OpOp2, String>(); HopsOpOp2String.put(OpOp2.PLUS, "+"); HopsOpOp2String.put(OpOp2.MINUS, "-"); HopsOpOp2String.put(OpOp2.MULT, "*"); HopsOpOp2String.put(OpOp2.DIV, "/"); HopsOpOp2String.put(OpOp2.MIN, "min"); HopsOpOp2String.put(OpOp2.MAX, "max"); HopsOpOp2String.put(OpOp2.LESSEQUAL, "<="); HopsOpOp2String.put(OpOp2.LESS, "<"); HopsOpOp2String.put(OpOp2.GREATEREQUAL, ">="); HopsOpOp2String.put(OpOp2.GREATER, ">"); HopsOpOp2String.put(OpOp2.EQUAL, "="); HopsOpOp2String.put(OpOp2.NOTEQUAL, "!="); HopsOpOp2String.put(OpOp2.OR, "|"); HopsOpOp2String.put(OpOp2.AND, "&"); HopsOpOp2String.put(OpOp2.LOG, "log"); HopsOpOp2String.put(OpOp2.POW, "^"); HopsOpOp2String.put(OpOp2.CONCAT, "concat"); HopsOpOp2String.put(OpOp2.INVALID, "?"); HopsOpOp2String.put(OpOp2.QUANTILE, "quantile"); HopsOpOp2String.put(OpOp2.INTERQUANTILE, "interquantile"); HopsOpOp2String.put(OpOp2.IQM, "IQM"); HopsOpOp2String.put(OpOp2.CENTRALMOMENT, "centraMoment"); HopsOpOp2String.put(OpOp2.COVARIANCE, "cov"); HopsOpOp2String.put(OpOp2.APPEND, "APP"); } static public HashMap<Hop.OpOp3, String> HopsOpOp3String; static { HopsOpOp3String = new HashMap<Hop.OpOp3, String>(); HopsOpOp3String.put(OpOp3.QUANTILE, "quantile"); HopsOpOp3String.put(OpOp3.INTERQUANTILE, "interquantile"); HopsOpOp3String.put(OpOp3.CTABLE, "ctable"); HopsOpOp3String.put(OpOp3.CENTRALMOMENT, "centraMoment"); HopsOpOp3String.put(OpOp3.COVARIANCE, "cov"); } static public HashMap<Hop.Direction, String> HopsDirection2String; static { HopsDirection2String = new HashMap<Hop.Direction, String>(); HopsDirection2String.put(Direction.RowCol, "RC"); HopsDirection2String.put(Direction.Col, "C"); HopsDirection2String.put(Direction.Row, "R"); } static public HashMap<Hop.AggOp, String> HopsAgg2String; static { HopsAgg2String = new HashMap<Hop.AggOp, String>(); HopsAgg2String.put(AggOp.SUM, "+"); HopsAgg2String.put(AggOp.PROD, "*"); HopsAgg2String.put(AggOp.MIN, "min"); HopsAgg2String.put(AggOp.MAX, "max"); HopsAgg2String.put(AggOp.MAXINDEX, "maxindex"); HopsAgg2String.put(AggOp.TRACE, "trace"); HopsAgg2String.put(AggOp.MEAN, "mean"); } static public HashMap<Hop.ReOrgOp, String> HopsTransf2String; static { HopsTransf2String = new HashMap<ReOrgOp, String>(); HopsTransf2String.put(ReOrgOp.TRANSPOSE, "t"); HopsTransf2String.put(ReOrgOp.DIAG_M2V, "diagM2V"); HopsTransf2String.put(ReOrgOp.DIAG_V2M, "diagV2M"); HopsTransf2String.put(ReOrgOp.RESHAPE, "rshape"); } static public HashMap<DataOpTypes, String> HopsData2String; static { HopsData2String = new HashMap<Hop.DataOpTypes, String>(); HopsData2String.put(DataOpTypes.PERSISTENTREAD, "PRead"); HopsData2String.put(DataOpTypes.PERSISTENTWRITE, "PWrite"); HopsData2String.put(DataOpTypes.TRANSIENTWRITE, "TWrite"); HopsData2String.put(DataOpTypes.TRANSIENTREAD, "TRead"); } public static boolean isFunction(OpOp2 op) { return op == OpOp2.MIN || op == OpOp2.MAX || op == OpOp2.LOG;// || op == OpOp2.CONCAT; //concat is || in Netezza } public static boolean isSupported(OpOp2 op) { return op != OpOp2.INVALID && op != OpOp2.QUANTILE && op != OpOp2.INTERQUANTILE && op != OpOp2.IQM; } public static boolean isFunction(OpOp1 op) { return op == OpOp1.SIN || op == OpOp1.TAN || op == OpOp1.COS || op == OpOp1.ABS || op == OpOp1.EXP || op == OpOp1.LOG || op == OpOp1.ROUND || op == OpOp1.SQRT; } public static boolean isBooleanOperation(OpOp2 op) { return op == OpOp2.AND || op == OpOp2.EQUAL || op == OpOp2.GREATER || op == OpOp2.GREATEREQUAL || op == OpOp2.LESS || op == OpOp2.LESSEQUAL || op == OpOp2.OR; } public static ValueType getResultValueType(ValueType vt1, ValueType vt2) { if(vt1 == ValueType.STRING || vt2 == ValueType.STRING) return ValueType.STRING; else if(vt1 == ValueType.DOUBLE || vt2 == ValueType.DOUBLE) return ValueType.DOUBLE; else return ValueType.INT; } protected GENERATES determineGeneratesFlag() { //Check whether this is going to be an Insert or With GENERATES gen = GENERATES.SQL; if(this.getParent().size() > 1) gen = GENERATES.DML; else { boolean hasWriteOutput = false; for(Hop h : this.getParent()) if(h instanceof DataOp) { DataOp o = ((DataOp)h); if(o._dataop == DataOpTypes.PERSISTENTWRITE || o._dataop == DataOpTypes.TRANSIENTWRITE) { hasWriteOutput = true; break; } } else if(h instanceof UnaryOp && ((UnaryOp)h).get_op() == OpOp1.PRINT2) { hasWriteOutput = true; break; } if(hasWriteOutput) gen = GENERATES.DML; } if(BREAKONSCALARS && this.get_dataType() == DataType.SCALAR) gen = GENERATES.DML; return gen; } ///////////////////////////////////// // methods for dynamic re-compilation ///////////////////////////////////// /** * Indicates if dynamic recompilation is required for this hop. */ public boolean requiresRecompile() { return _requiresRecompile; } public void setRequiresRecompile() { _requiresRecompile = true; } public void unsetRequiresRecompile() { _requiresRecompile = false; } /** * Update the output size information for this hop. */ public abstract void refreshSizeInformation(); /** * Util function for refreshing scalar rows input parameter. */ protected void refreshRowsParameterInformation( Hop input ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim1(input.getInput().get(0).get_dim1()); else if ( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim1(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim1(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>()); if( dim != Long.MAX_VALUE ) //if known set_dim1( dim ); } } public void refreshRowsParameterInformation( Hop input, LocalVariableMap vars ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim1(input.getInput().get(0).get_dim1()); else if ( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim1(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim1(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>(), vars); if( dim != Long.MAX_VALUE ) //if known set_dim1( dim ); } else if( input instanceof DataOp ) { String name = input.get_name(); Data dat = vars.get(name); if( dat!=null && dat instanceof ScalarObject ) set_dim1( ((ScalarObject)dat).getLongValue() ); } } /** * Util function for refreshing scalar cols input parameter. */ protected void refreshColsParameterInformation( Hop input ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim2(input.getInput().get(0).get_dim1()); else if( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim2(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim2(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>()); if( dim != Long.MAX_VALUE ) //if known set_dim2( dim ); } } public void refreshColsParameterInformation( Hop input, LocalVariableMap vars ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim2(input.getInput().get(0).get_dim1()); else if( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim2(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim2(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>(), vars); if( dim != Long.MAX_VALUE ) //if known set_dim2( dim ); } else if( input instanceof DataOp ) { String name = input.get_name(); Data dat = vars.get(name); if( dat!=null && dat instanceof ScalarObject ) set_dim2( ((ScalarObject)dat).getLongValue() ); } } /** * Function to evaluate simple size expressions of binary operators * (plus, minus, mult, div, min, max) over literals and now/ncol. * * It returns the exact results of this expressions if known, otherwise * Long.MAX_VALUE if unknown. * * TODO: extend to memo table usage (for this, memo needs to contain min/max bounds, * other wise expressions like b-a might give not a worst-case estimate if a is overestimated) * * @param root * @return */ protected long rEvalSimpleBinarySizeExpression( Hop root, HashMap<Long, Long> memo ) { //memoization (prevent redundant computation of common subexpr) if( memo.containsKey(root.getHopID()) ) return memo.get(root.getHopID()); long ret = Long.MAX_VALUE; if( root instanceof LiteralOp ) { long dim = UtilFunctions.parseToLong(root.get_name()); if( dim != -1 ) //if known ret = dim; } else if( root instanceof UnaryOp ) { UnaryOp uroot = (UnaryOp) root; long dim = -1; if(uroot.get_op() == Hop.OpOp1.NROW) dim = uroot.getInput().get(0).get_dim1(); else if( uroot.get_op() == Hop.OpOp1.NCOL ) dim = uroot.getInput().get(0).get_dim2(); if( dim != -1 ) //if known ret = dim; } else if( root instanceof BinaryOp ) { if( OptimizerUtils.ALLOW_SIZE_EXPRESSION_EVALUATION ) { BinaryOp broot = (BinaryOp) root; long lret = rEvalSimpleBinarySizeExpression(broot.getInput().get(0), memo); long rret = rEvalSimpleBinarySizeExpression(broot.getInput().get(1), memo); //note: positive and negative values might be valid subexpressions if( lret!=Long.MAX_VALUE && rret!=Long.MAX_VALUE ) //if known { switch( broot.op ) { case PLUS: ret = lret + rret; break; case MINUS: ret = lret - rret; break; case MULT: ret = lret * rret; break; case DIV: ret = lret / rret; break; case MIN: ret = Math.min(lret, rret); break; case MAX: ret = Math.max(lret, rret); break; } } } } memo.put(root.getHopID(), ret); return ret; } protected long rEvalSimpleBinarySizeExpression( Hop root, HashMap<Long, Long> memo, LocalVariableMap vars ) { //memoization (prevent redundant computation of common subexpr) if( memo.containsKey(root.getHopID()) ) return memo.get(root.getHopID()); long ret = Long.MAX_VALUE; if( root instanceof LiteralOp ) { long dim = UtilFunctions.parseToLong(root.get_name()); if( dim != -1 ) //if known ret = dim; } else if( root instanceof UnaryOp ) { UnaryOp uroot = (UnaryOp) root; long dim = -1; if(uroot.get_op() == Hop.OpOp1.NROW) dim = uroot.getInput().get(0).get_dim1(); else if( uroot.get_op() == Hop.OpOp1.NCOL ) dim = uroot.getInput().get(0).get_dim2(); if( dim != -1 ) //if known ret = dim; } else if( root instanceof DataOp ) { String name = root.get_name(); Data dat = vars.get(name); if( dat!=null && dat instanceof ScalarObject ) ret = ((ScalarObject)dat).getLongValue(); } else if( root instanceof BinaryOp ) { if( OptimizerUtils.ALLOW_SIZE_EXPRESSION_EVALUATION ) { BinaryOp broot = (BinaryOp) root; long lret = rEvalSimpleBinarySizeExpression(broot.getInput().get(0), memo, vars); long rret = rEvalSimpleBinarySizeExpression(broot.getInput().get(1), memo, vars); //note: positive and negative values might be valid subexpressions if( lret!=Long.MAX_VALUE && rret!=Long.MAX_VALUE ) //if known { switch( broot.op ) { case PLUS: ret = lret + rret; break; case MINUS: ret = lret - rret; break; case MULT: ret = lret * rret; break; case DIV: ret = lret / rret; break; case MIN: ret = Math.min(lret, rret); break; case MAX: ret = Math.max(lret, rret); break; } } } } memo.put(root.getHopID(), ret); return ret; } protected void rConstantFoldingBinaryExpression( Hop root ) throws HopsException { if( root.get_visited() == VISIT_STATUS.DONE ) return; //recursively process childs (before replacement to allow bottom-recursion) //no iterator in order to prevent concurrent modification for( int i=0; i<root.getInput().size(); i++ ) { Hop h = root.getInput().get(i); rConstantFoldingBinaryExpression(h); } //fold binary op if both are literals if( root instanceof BinaryOp && root.getInput().get(0) instanceof LiteralOp && root.getInput().get(1) instanceof LiteralOp ) { BinaryOp broot = (BinaryOp) root; LiteralOp lit1 = (LiteralOp) root.getInput().get(0); LiteralOp lit2 = (LiteralOp) root.getInput().get(1); double ret = Double.MAX_VALUE; if( (lit1.get_valueType()==ValueType.DOUBLE || lit1.get_valueType()==ValueType.INT) && (lit2.get_valueType()==ValueType.DOUBLE || lit2.get_valueType()==ValueType.INT) ) { double lret = lit1.getDoubleValue(); double rret = lit2.getDoubleValue(); switch( broot.op ) { case PLUS: ret = lret + rret; break; case MINUS: ret = lret - rret; break; case MULT: ret = lret * rret; break; case DIV: ret = lret / rret; break; case MIN: ret = Math.min(lret, rret); break; case MAX: ret = Math.max(lret, rret); break; } } if( ret!=Double.MAX_VALUE ) { LiteralOp literal = null; if( broot.get_valueType()==ValueType.DOUBLE ) literal = new LiteralOp(String.valueOf(ret), ret); else if( broot.get_valueType()==ValueType.INT ) literal = new LiteralOp(String.valueOf((long)ret), (long)ret); //reverse replacement in order to keep common subexpression elimination for( int i=0; i<broot.getParent().size(); i++ ) //for all parents { Hop parent = broot.getParent().get(i); for( int j=0; j<parent.getInput().size(); j++ ) { Hop child = parent.getInput().get(j); if( broot == child ) { //replace operator parent.getInput().remove(j); parent.getInput().add(j, literal); } } } broot.getParent().clear(); } } //mark processed root.set_visited( VISIT_STATUS.DONE ); } /** * * @return */ public String constructBaseDir() { StringBuilder sb = new StringBuilder(); sb.append( ConfigurationManager.getConfig().getTextValue(DMLConfig.SCRATCH_SPACE) ); sb.append( Lop.FILE_SEPARATOR ); sb.append( Lop.PROCESS_PREFIX ); sb.append( DMLScript.getUUID() ); sb.append( Lop.FILE_SEPARATOR ); sb.append( Lop.FILE_SEPARATOR ); sb.append( ProgramConverter.CP_ROOT_THREAD_ID ); sb.append( Lop.FILE_SEPARATOR ); return sb.toString(); } /** * Clones the attributes of that and copies it over to this. * * @param that * @throws HopsException */ protected void clone( Hop that, boolean withRefs ) throws CloneNotSupportedException { if( withRefs ) throw new CloneNotSupportedException( "Hops deep copy w/ lops/inputs/parents not supported." ); ID = that.ID; _kind = that._kind; _name = that._name; _dataType = that._dataType; _valueType = that._valueType; _visited = that._visited; _dim1 = that._dim1; _dim2 = that._dim2; _rows_in_block = that._rows_in_block; _cols_in_block = that._cols_in_block; _nnz = that._nnz; //no copy of lops (regenerated) _parent = new ArrayList<Hop>(); _input = new ArrayList<Hop>(); _lops = null; _sqllops = null; _etype = that._etype; _etypeForced = that._etypeForced; _outputMemEstimate = that._outputMemEstimate; _memEstimate = that._memEstimate; _processingMemEstimate = that._processingMemEstimate; _requiresRecompile = that._requiresRecompile; _beginLine = that._beginLine; _beginColumn = that._beginColumn; _endLine = that._endLine; _endColumn = that._endColumn; } public abstract Object clone() throws CloneNotSupportedException; public abstract boolean compare( Hop that ); /////////////////////////////////////////////////////////////////////////// // store position information for Hops /////////////////////////////////////////////////////////////////////////// public int _beginLine, _beginColumn; public int _endLine, _endColumn; public void setBeginLine(int passed) { _beginLine = passed; } public void setBeginColumn(int passed) { _beginColumn = passed; } public void setEndLine(int passed) { _endLine = passed; } public void setEndColumn(int passed) { _endColumn = passed; } public void setAllPositions(int blp, int bcp, int elp, int ecp){ _beginLine = blp; _beginColumn = bcp; _endLine = elp; _endColumn = ecp; } public int getBeginLine() { return _beginLine; } public int getBeginColumn() { return _beginColumn; } public int getEndLine() { return _endLine; } public int getEndColumn() { return _endColumn; } public String printErrorLocation(){ return "ERROR: line " + _beginLine + ", column " + _beginColumn + " -- "; } public String printWarningLocation(){ return "WARNING: line " + _beginLine + ", column " + _beginColumn + " -- "; } } // end class
SystemML/DML/src/com/ibm/bi/dml/hops/Hop.java
/** * IBM Confidential * OCO Source Materials * (C) Copyright IBM Corp. 2010, 2014 * The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office. */ package com.ibm.bi.dml.hops; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM; import com.ibm.bi.dml.conf.ConfigurationManager; import com.ibm.bi.dml.conf.DMLConfig; import com.ibm.bi.dml.hops.OptimizerUtils.OptimizationType; import com.ibm.bi.dml.lops.Lop; import com.ibm.bi.dml.lops.LopsException; import com.ibm.bi.dml.lops.LopProperties.ExecType; import com.ibm.bi.dml.parser.StatementBlock; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.ValueType; import com.ibm.bi.dml.runtime.controlprogram.LocalVariableMap; import com.ibm.bi.dml.runtime.controlprogram.parfor.ProgramConverter; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDSequence; import com.ibm.bi.dml.runtime.instructions.CPInstructions.Data; import com.ibm.bi.dml.runtime.instructions.CPInstructions.ScalarObject; import com.ibm.bi.dml.runtime.util.UtilFunctions; import com.ibm.bi.dml.sql.sqllops.SQLLops; import com.ibm.bi.dml.sql.sqllops.SQLLops.GENERATES; public abstract class Hop { @SuppressWarnings("unused") private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2013\n" + "US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp."; protected static final Log LOG = LogFactory.getLog(Hop.class.getName()); public static boolean BREAKONSCALARS = false; public static boolean SPLITLARGEMATRIXMULT = true; public static long CPThreshold = 2000; public enum Kind { UnaryOp, BinaryOp, AggUnaryOp, AggBinaryOp, ReorgOp, Reblock, DataOp, LiteralOp, PartitionOp, CrossvalOp, DataGenOp, GenericFunctionOp, TertiaryOp, ParameterizedBuiltinOp, Indexing, FunctionOp }; public enum VISIT_STATUS { DONE, VISITING, NOTVISITED } // static variable to assign an unique ID to every hop that is created private static IDSequence UniqueHopID = new IDSequence(); protected long ID; protected Kind _kind; protected String _name; protected DataType _dataType; protected ValueType _valueType; protected VISIT_STATUS _visited = VISIT_STATUS.NOTVISITED; protected long _dim1 = -1; protected long _dim2 = -1; protected long _rows_in_block = -1; protected long _cols_in_block = -1; protected long _nnz = -1; protected ArrayList<Hop> _parent = new ArrayList<Hop>(); protected ArrayList<Hop> _input = new ArrayList<Hop>(); private Lop _lops = null; private SQLLops _sqllops = null; protected ExecType _etype = null; //currently used exec type protected ExecType _etypeForced = null; //exec type forced via platform or external optimizer // Estimated size for the output produced from this Hop protected double _outputMemEstimate = OptimizerUtils.INVALID_SIZE; // Estimated size for the entire operation represented by this Hop // It includes the memory required for all inputs as well as the output protected double _memEstimate = OptimizerUtils.INVALID_SIZE; protected double _processingMemEstimate = 0; // indicates if there are unknowns during compilation // (in that case re-complication ensures robustness and efficiency) protected boolean _requiresRecompile = false; protected Hop(){ //default constructor for clone } public Hop(Kind k, String l, DataType dt, ValueType vt) { _kind = k; set_name(l); _dataType = dt; _valueType = vt; ID = getNextHopID(); } private static long getNextHopID() { return UniqueHopID.getNextID(); } public long getHopID() { return ID; } public ExecType getExecType() { return _etype; } /** * * @return */ public ExecType getForcedExecType() { return _etypeForced; } /** * * @param etype */ public void setForcedExecType(ExecType etype) { _etypeForced = etype; } /** * * @return */ public abstract boolean allowsAllExecTypes(); /** * */ public void checkAndSetForcedPlatform() { if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) _etypeForced = ExecType.CP; else if ( DMLScript.rtplatform == RUNTIME_PLATFORM.HADOOP ) _etypeForced = ExecType.MR; } /** * Returns the memory estimate for the output produced from this Hop. * It must be invoked only within Hops. From outside Hops, one must * only use getMemEstimate(), which gives memory required to store * all inputs and the output. * * @return */ protected double getOutputSize() { return _outputMemEstimate; } protected double getInputOutputSize() { double sum = this._outputMemEstimate; sum += this._processingMemEstimate; for(Hop h : _input ) { sum += h._outputMemEstimate; } return sum; } protected double getInputSize() { double sum = 0; for(Hop h : _input ) { sum += h._outputMemEstimate; } return sum; } /** * * @param pos * @return */ protected double getInputSize( int pos ){ double ret = 0; if( _input.size()>pos ) ret = _input.get(pos)._outputMemEstimate; return ret; } protected double getIntermediateSize() { return _processingMemEstimate; } /** * NOTES: * * Purpose: Whenever the output dimensions / sparsity of a hop are unknown, this hop * should store its worst-case output statistics (if known) in that table. Subsequent * hops can then * * Invocation: Intended to be called for ALL root nodes of one Hops DAG with the same * (initially empty) memo table. * * @param memo * @return */ public double getMemEstimate() { if ( OptimizerUtils.getOptType() == OptimizationType.MEMORY_BASED ) { if ( ! isMemEstimated() ) { LOG.warn("Nonexisting memory estimate - reestimating w/o memo table."); computeMemEstimate( new MemoTable() ); } return _memEstimate; } else { return OptimizerUtils.INVALID_SIZE; } } /** * Returns memory estimate in bytes * * @param mem */ public void setMemEstimate( double mem ) { _memEstimate = mem; } public boolean isMemEstimated() { return (_memEstimate != OptimizerUtils.INVALID_SIZE); } /** * Computes the estimate of memory required to store the input/output of this hop in memory. * This is the default implementation (orchestration of hop-specific implementation) * that should suffice for most hops. If a hop requires more control, this method should * be overwritten with awareness of (1) output estimates, and (2) propagation of worst-case * matrix characteristics (dimensions, sparsity). * * TODO remove memo table and, on constructor refresh, inference in refresh, single compute mem, * maybe general computeMemEstimate, flags to indicate if estimate or not. * * @return computed estimate */ protected void computeMemEstimate( MemoTable memo ) { long[] wstats = null; //output size estimate switch( get_dataType() ) { case SCALAR: { if( get_valueType()== ValueType.DOUBLE) //default case _outputMemEstimate = OptimizerUtils.DOUBLE_SIZE; else //literalops, dataops _outputMemEstimate = computeOutputMemEstimate(_dim1, _dim2, _nnz); break; } case MATRIX: { if( dimsKnown() ) { //nnz should be known as well, if applicable (see refreshSizeInformation) //1) compute mem estimate based on known dimensions/sparsity (dense if sparsity unknown) long lnnz = ((_nnz>=0)?_nnz:_dim1*_dim2); _outputMemEstimate = computeOutputMemEstimate( _dim1, _dim2, lnnz ); } else if( memo.hasInputStatistics(this) ) { //2) infer the output stats wstats = inferOutputCharacteristics(memo); if( wstats != null ) { //2a) use worst case characteristics to estimate mem long lnnz = ((wstats[2]>=0)?wstats[2]:wstats[0]*wstats[1]); _outputMemEstimate = computeOutputMemEstimate( wstats[0], wstats[1], lnnz ); //propagate worst-case estimate memo.memoizeStatistics(getHopID(), wstats[0], wstats[1], wstats[2]); } else { //System.out.println("could not infer output characteristics for "+this.getOpString()); //2b) unknown output size _outputMemEstimate = OptimizerUtils.DEFAULT_SIZE; } } else { //System.out.println("no stats for "+this.getOpString()); //3) unknown output size _outputMemEstimate = OptimizerUtils.DEFAULT_SIZE; } break; } case OBJECT: case UNKNOWN: { _outputMemEstimate = OptimizerUtils.DEFAULT_SIZE; break; } } //intermediate size estimate if( dimsKnown() ) { //incl scalar output long lnnz = ((_nnz>=0)?_nnz:_dim1*_dim2); _processingMemEstimate = computeIntermediateMemEstimate(_dim1, _dim2, lnnz); } else if( wstats!=null ) { long lnnz = ((wstats[2]>=0)?wstats[2]:wstats[0]*wstats[1]); _processingMemEstimate = computeIntermediateMemEstimate( wstats[0], wstats[1], lnnz ); } //final estimate (sum of inputs/intermediates/output) _memEstimate = getInputOutputSize(); } /** * Computes the hop-specific output memory estimate in bytes. Should be 0 if not * applicable. * * @param dim1 * @param dim2 * @param nnz * @return */ protected abstract double computeOutputMemEstimate( long dim1, long dim2, long nnz ); /** * Computes the hop-specific intermediate memory estimate in bytes. Should be 0 if not * applicable. * * @param dim1 * @param dim2 * @param nnz * @return */ protected abstract double computeIntermediateMemEstimate( long dim1, long dim2, long nnz ); /** * Computes the output matrix characteristics (rows, cols, nnz) based on worst-case output * and/or input estimates. Should return null if dimensions are unknown. * * @param memo * @return */ protected abstract long[] inferOutputCharacteristics( MemoTable memo ); /** * This function is used only for sanity check. * Returns true if estimates for all the hops in the DAG rooted at the current * hop are computed. Returns false if any of the hops have INVALID estimate. * * @return */ public boolean checkEstimates() { boolean childStatus = true; for (Hop h : this.getInput()) childStatus = childStatus && h.checkEstimates(); return childStatus && (_memEstimate != OptimizerUtils.INVALID_SIZE); } /** * Recursively computes memory estimates for all the Hops in the DAG rooted at the * current hop pointed by <code>this</code>. * */ public void refreshMemEstimates( MemoTable memo ) { if (get_visited() == VISIT_STATUS.DONE) return; for (Hop h : this.getInput()) h.refreshMemEstimates( memo ); this.computeMemEstimate( memo ); this.set_visited(VISIT_STATUS.DONE); } /** * This method determines the execution type (CP, MR) based ONLY on the * estimated memory footprint required for this operation, which includes * memory for all inputs and the output represented by this Hop. * * It is used when <code>OptimizationType = MEMORY_BASED</code>. * This optimization schedules an operation to CP whenever inputs+output * fit in memory -- note that this decision MAY NOT be optimal in terms of * execution time. * * @return */ protected ExecType findExecTypeByMemEstimate() { ExecType et = null; char c = ' '; if ( getMemEstimate() < OptimizerUtils.getMemBudget(true) ) { et = ExecType.CP; } else { et = ExecType.MR; c = '*'; } if (LOG.isDebugEnabled()){ String s = String.format(" %c %-5s %-8s (%s,%s) %s", c, getHopID(), getOpString(), OptimizerUtils.toMB(_outputMemEstimate), OptimizerUtils.toMB(_memEstimate), et); //System.out.println(s); LOG.debug(s); } // This is the old format for reference // %c %-5s %-8s (%s,%s) %s\n", c, getHopID(), getOpString(), OptimizerUtils.toMB(_outputMemEstimate), OptimizerUtils.toMB(_memEstimate), et); return et; } public ArrayList<Hop> getParent() { return _parent; } public ArrayList<Hop> getInput() { return _input; } /** * Create bidirectional links * * @param h */ public void addInput( Hop h ) { _input.add(h); h._parent.add(this); } public long get_rows_in_block() { return _rows_in_block; } public void set_rows_in_block(long rowsInBlock) { _rows_in_block = rowsInBlock; } public long get_cols_in_block() { return _cols_in_block; } public void set_cols_in_block(long colsInBlock) { _cols_in_block = colsInBlock; } public void setNnz(long nnz){ _nnz = nnz; } public long getNnz(){ return _nnz; } /** * Should not be used because this might return a too aggressive sparsity estimate. * @return */ @Deprecated public double getSparsity() { if ( _dataType == DataType.SCALAR ) return 1.0; if (dimsKnown() && _nnz > 0) return (double)_nnz/(double)(_dim1*_dim2); else return OptimizerUtils.DEF_SPARSITY; } public Kind getKind() { return _kind; } abstract public Lop constructLops() throws HopsException, LopsException; abstract public SQLLops constructSQLLOPs() throws HopsException; abstract protected ExecType optFindExecType() throws HopsException; abstract public String getOpString(); protected boolean isVector() { return (dimsKnown() && (_dim1 == 1 || _dim2 == 1) ); } protected boolean areDimsBelowThreshold() { return (_dim1 <= Hop.CPThreshold && _dim2 <= Hop.CPThreshold ); } protected boolean dimsKnown() { return ( _dataType == DataType.SCALAR || (_dataType==DataType.MATRIX && _dim1 > 0 && _dim2 > 0) ); } public static void resetVisitStatus( ArrayList<Hop> hops ) { for( Hop hopRoot : hops ) hopRoot.resetVisitStatus(); } public void resetVisitStatus() { if (this.get_visited() == Hop.VISIT_STATUS.NOTVISITED) return; for (Hop h : this.getInput()) h.resetVisitStatus(); if(this.get_sqllops() != null) this.get_sqllops().set_visited(VISIT_STATUS.NOTVISITED); this.set_visited(Hop.VISIT_STATUS.NOTVISITED); } public void rule_BlockSizeAndReblock(int GLOBAL_BLOCKSIZE) throws HopsException { // TODO BJR: traverse HOP DAG and insert Reblock HOPs // Go to the source(s) of the DAG for (Hop hi : this.getInput()) { if (get_visited() != Hop.VISIT_STATUS.DONE) hi.rule_BlockSizeAndReblock(GLOBAL_BLOCKSIZE); } boolean canReblock = true; if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) canReblock = false; if (this instanceof DataOp) { // if block size does not match if (canReblock && get_dataType() != DataType.SCALAR && (get_rows_in_block() != GLOBAL_BLOCKSIZE || get_cols_in_block() != GLOBAL_BLOCKSIZE)) { if (((DataOp) this).get_dataop() == DataOp.DataOpTypes.PERSISTENTREAD) { // insert reblock after the hop ReblockOp r = new ReblockOp(this, GLOBAL_BLOCKSIZE, GLOBAL_BLOCKSIZE); r.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); r.computeMemEstimate(null); r.set_visited(Hop.VISIT_STATUS.DONE); } else if (((DataOp) this).get_dataop() == DataOp.DataOpTypes.PERSISTENTWRITE) { if (get_rows_in_block() == -1 && get_cols_in_block() == -1) { // if this dataop is for cell ouput, then no reblock is // needed as (A) all jobtypes can produce block2cell and // cell2cell and (B) we don't generate an explicit // instruction for it (the info is conveyed through // OutputInfo. } else if (getInput().get(0) instanceof ReblockOp && getInput().get(0).getParent().size() == 1) { // if a reblock is feeding into this, then use it if // this is // the only parent, otherwise new Reblock getInput().get(0).set_rows_in_block(this.get_rows_in_block()); getInput().get(0).set_cols_in_block(this.get_cols_in_block()); } else { ReblockOp r = new ReblockOp(this); r.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn()); r.computeMemEstimate(null); r.set_visited(Hop.VISIT_STATUS.DONE); } } else if (((DataOp) this).get_dataop() == DataOp.DataOpTypes.TRANSIENTWRITE || ((DataOp) this).get_dataop() == DataOp.DataOpTypes.TRANSIENTREAD) { if ( DMLScript.rtplatform == RUNTIME_PLATFORM.SINGLE_NODE ) { // simply copy the values from its input set_rows_in_block(getInput().get(0).get_rows_in_block()); set_cols_in_block(getInput().get(0).get_cols_in_block()); } else { // by default, all transient reads and writes are in blocked format set_rows_in_block(GLOBAL_BLOCKSIZE); set_cols_in_block(GLOBAL_BLOCKSIZE); } } else { throw new HopsException(this.printErrorLocation() + "unexpected non-scalar Data HOP in reblock.\n"); } } } else { // TODO: following two lines are commented, and the subsequent hack is used instead! //set_rows_per_block(GLOBAL_BLOCKSIZE); //set_cols_per_block(GLOBAL_BLOCKSIZE); // TODO: this is hack! /* * Handle hops whose output dimensions are unknown! * * Constraint C1: * Currently, only ctable() and groupedAggregate() fall into this category. * The MR jobs for both these functions run in "cell" mode and hence make their * blocking dimensions to (-1,-1). * * Constraint C2: * Blocking dimensions are not applicable for hops that produce scalars. * CMCOV and GroupedAgg jobs always run in "cell" mode, and hence they * produce output in cell format. * * Constraint C3: * Remaining hops will get their blocking dimensions from their input hops. */ if ( this instanceof ReblockOp ) { set_rows_in_block(GLOBAL_BLOCKSIZE); set_cols_in_block(GLOBAL_BLOCKSIZE); } // Constraint C1: //else if ( (this instanceof ParameterizedBuiltinOp && ((ParameterizedBuiltinOp)this)._op == ParamBuiltinOp.GROUPEDAGG) ) { // set_rows_in_block(-1); // set_cols_in_block(-1); //} // Constraint C2: else if ( this.get_dataType() == DataType.SCALAR ) { set_rows_in_block(-1); set_cols_in_block(-1); } // Constraint C3: else { if ( !canReblock ) { set_rows_in_block(-1); set_cols_in_block(-1); } else { set_rows_in_block(GLOBAL_BLOCKSIZE); set_cols_in_block(GLOBAL_BLOCKSIZE); } // if any input is not blocked then the output of current Hop should not be blocked for ( Hop h : getInput() ) { if ( h.get_dataType() == DataType.MATRIX && h.get_rows_in_block() == -1 && h.get_cols_in_block() == -1 ) { set_rows_in_block(-1); set_cols_in_block(-1); break; } } } } this.set_visited(Hop.VISIT_STATUS.DONE); } /** * * @param dataops * @param literalops * @return * @throws HopsException */ public int rule_CommonSubexpressionElimination_MergeLeafs( HashMap<String, Hop> dataops, HashMap<String, Hop> literalops ) throws HopsException { int ret = 0; if( get_visited() == Hop.VISIT_STATUS.DONE ) return ret; if( getInput().size()==0 ) //LEAF NODE { if( this instanceof LiteralOp ) { if( !literalops.containsKey(get_name()) ) literalops.put(get_name(), this); } else if( this instanceof DataOp && ((DataOp)this).isRead()) { if(!dataops.containsKey(get_name()) ) dataops.put(get_name(), this); } } else //INNER NODE { //merge leaf nodes (data, literal) for( int i=0; i<getInput().size(); i++ ) { Hop hi = getInput().get(i); if( hi instanceof DataOp && ((DataOp)hi).isRead() && dataops.containsKey(hi.get_name()) ) { //replace child node ref Hop tmp = dataops.get(hi.get_name()); tmp.getParent().add(this); getInput().set(i, tmp); ret++; } else if( hi instanceof LiteralOp && literalops.containsKey(hi.get_name()) ) { Hop tmp = literalops.get(hi.get_name()); if(hi.get_valueType()==tmp.get_valueType()) { //replace child node ref tmp.getParent().add(this); getInput().set(i, tmp); ret++; } } //recursive invocation (direct return on merged nodes) ret += hi.rule_CommonSubexpressionElimination_MergeLeafs(dataops, literalops); } } this.set_visited(Hop.VISIT_STATUS.DONE); return ret; } public int rule_CommonSubexpressionElimination( HashMap<String, Hop> dataops, HashMap<String, Hop> literalops ) throws HopsException { int ret = 0; if( get_visited() == Hop.VISIT_STATUS.DONE ) return ret; //step 1: merge childs recursively first for(Hop hi : this.getInput()) ret += hi.rule_CommonSubexpressionElimination(dataops, literalops); //step 2: merge parent nodes if( getParent().size()>1 ) //multiple consumers { //for all pairs for( int i=0; i<getParent().size()-1; i++ ) for( int j=i+1; j<getParent().size(); j++ ) { Hop h1 = getParent().get(i); Hop h2 = getParent().get(j); if( h1==h2 ) { //remove redundant h2 from parent list getParent().remove(j); j--; } else if( h1.compare(h2) ) //merge h2 into h1 { //remove h2 from parent list getParent().remove(j); //replace h2 w/ h1 in h2-parent inputs ArrayList<Hop> parent = h2.getParent(); for( Hop p : parent ) for( int k=0; k<p.getInput().size(); k++ ) if( p.getInput().get(k)==h2 ) { p.getInput().set(k, h1); h1.getParent().add(p); } //replace h2 w/ h1 in h2-input parents for( Hop in : h2.getInput() ) in.getParent().remove(h2); ret++; j--; } } } this.set_visited(Hop.VISIT_STATUS.DONE); return ret; } /** * Test and debugging only. * * @param h * @throws HopsException */ public void checkParentChildPointers( ) throws HopsException { if( get_visited() == VISIT_STATUS.DONE ) return; for( Hop in : getInput() ) { if( !in.getParent().contains(this) ) throw new HopsException("Parent-Child pointers incorrect."); in.checkParentChildPointers(); } set_visited(VISIT_STATUS.DONE); } public void rule_ConstantFolding( ) throws HopsException { rConstantFoldingBinaryExpression(this); } public void rule_RehangTransientWriteParents(StatementBlock sb) throws HopsException { if (this instanceof DataOp && ((DataOp) this).get_dataop() == DataOpTypes.TRANSIENTWRITE && !this.getParent().isEmpty()) { // update parents inputs with data op input for (Hop p : this.getParent()) { p.getInput().set(p.getInput().indexOf(this), this.getInput().get(0)); } // update dataop input parent to add new parents except for // dataop itself this.getInput().get(0).getParent().addAll(this.getParent()); // remove dataop parents this.getParent().clear(); // add dataop as root for this Hops DAG sb.get_hops().add(this); // do the same thing for my inputs (children) for (Hop hi : this.getInput()) { hi.rule_RehangTransientWriteParents(sb); } } } /** * rule_OptimizeMMChains(): This method recurses through all Hops in the DAG * to find chains that need to be optimized. */ public void rule_OptimizeMMChains() throws HopsException { if(this.get_visited() == Hop.VISIT_STATUS.DONE) return; if (this.getKind() == Hop.Kind.AggBinaryOp && ((AggBinaryOp) this).isMatrixMultiply() && this.get_visited() != Hop.VISIT_STATUS.DONE) { // Try to find and optimize the chain in which current Hop is the // last operator this.optimizeMMChain(); } for (Hop hi : this.getInput()) hi.rule_OptimizeMMChains(); this.set_visited(Hop.VISIT_STATUS.DONE); } /** * mmChainDP(): Core method to perform dynamic programming on a given array * of matrix dimensions. */ public int[][] mmChainDP(long dimArray[], int size) { long dpMatrix[][] = new long[size][size]; int split[][] = new int[size][size]; int i, j, k, l; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { dpMatrix[i][j] = 0; split[i][j] = -1; } } long cost; long MAX = Long.MAX_VALUE; for (l = 2; l <= size; l++) { // chain length for (i = 0; i < size - l + 1; i++) { j = i + l - 1; // find cost of (i,j) dpMatrix[i][j] = MAX; for (k = i; k <= j - 1; k++) { cost = dpMatrix[i][k] + dpMatrix[k + 1][j] + (dimArray[i] * dimArray[k + 1] * dimArray[j + 1]); if (cost < dpMatrix[i][j]) { dpMatrix[i][j] = cost; split[i][j] = k; } } } } return split; } /** * mmChainRelinkHops(): This method gets invoked after finding the optimal * order (split[][]) from dynamic programming. It relinks the Hops that are * part of the mmChain. mmChain : basic operands in the entire matrix * multiplication chain. mmOperators : Hops that store the intermediate * results in the chain. For example: A = B %*% (C %*% D) there will be * three Hops in mmChain (B,C,D), and two Hops in mmOperators (one for each * %*%) . */ private void mmChainRelinkHops(Hop h, int i, int j, ArrayList<Hop> mmChain, ArrayList<Hop> mmOperators, int opIndex, int[][] split) { if (i == j) return; Hop input1, input2; // Set Input1 for current Hop h if (i == split[i][j]) { input1 = mmChain.get(i); h.getInput().add(mmChain.get(i)); mmChain.get(i).getParent().add(h); } else { input1 = mmOperators.get(opIndex); h.getInput().add(mmOperators.get(opIndex)); mmOperators.get(opIndex).getParent().add(h); opIndex = opIndex + 1; } // Set Input2 for current Hop h if (split[i][j] + 1 == j) { input2 = mmChain.get(j); h.getInput().add(mmChain.get(j)); mmChain.get(j).getParent().add(h); } else { input2 = mmOperators.get(opIndex); h.getInput().add(mmOperators.get(opIndex)); mmOperators.get(opIndex).getParent().add(h); opIndex = opIndex + 1; } // Find children for both the inputs mmChainRelinkHops(h.getInput().get(0), i, split[i][j], mmChain, mmOperators, opIndex, split); mmChainRelinkHops(h.getInput().get(1), split[i][j] + 1, j, mmChain, mmOperators, opIndex, split); // Propagate properties of input hops to current hop h h.set_dim1(input1.get_dim1()); h.set_rows_in_block(input1.get_rows_in_block()); h.set_dim2(input2.get_dim2()); h.set_cols_in_block(input2.get_cols_in_block()); } private void clearLinksWithinChain ( ArrayList<Hop> operators ) throws HopsException { Hop op, input1, input2; for ( int i=0; i < operators.size(); i++ ) { op = operators.get(i); if ( op.getInput().size() != 2 || (i != 0 && op.getParent().size() > 1 ) ) { throw new HopsException(this.printErrorLocation() + "Unexpected error while applying optimization on matrix-mult chain. \n"); } input1 = op.getInput().get(0); input2 = op.getInput().get(1); op.getInput().clear(); input1.getParent().remove(op); input2.getParent().remove(op); } } private long [] getDimArray ( ArrayList<Hop> chain ) throws HopsException { // Build the array containing dimensions from all matrices in the // chain long dimArray[] = new long[chain.size() + 1]; // check the dimensions in the matrix chain to insure all dimensions are known boolean shortCircuit = false; for (int i=0; i< chain.size(); i++){ if (chain.get(i)._dim1 <= 0 || chain.get(i)._dim2 <= 0) shortCircuit = true; } if (shortCircuit){ for (int i=0; i< dimArray.length; i++){ dimArray[i] = 1; } LOG.trace("short-circuit optimizeMMChain() for matrices with unknown size"); return dimArray; } for (int i = 0; i < chain.size(); i++) { if (i == 0) { dimArray[i] = chain.get(i).get_dim1(); if (dimArray[i] <= 0) { throw new HopsException(this.printErrorLocation() + "Hops::optimizeMMChain() : Invalid Matrix Dimension: " + dimArray[i]); } } else { if (chain.get(i - 1).get_dim2() != chain.get(i) .get_dim1()) { throw new HopsException(this.printErrorLocation() + "Hops::optimizeMMChain() : Matrix Dimension Mismatch"); } } dimArray[i + 1] = chain.get(i).get_dim2(); if (dimArray[i + 1] <= 0) { throw new HopsException(this.printErrorLocation() + "Hops::optimizeMMChain() : Invalid Matrix Dimension: " + dimArray[i + 1]); } } return dimArray; } private int inputCount ( Hop p, Hop h ) { int count = 0; for ( int i=0; i < p.getInput().size(); i++ ) if ( p.getInput().get(i).equals(h) ) count++; return count; } /** * optimizeMMChain(): It optimizes the matrix multiplication chain in which * the last Hop is "this". Step-1) Identify the chain (mmChain). (Step-2) clear all * links among the Hops that are involved in mmChain. (Step-3) Find the * optimal ordering (dynamic programming) (Step-4) Relink the hops in * mmChain. */ private void optimizeMMChain() throws HopsException { LOG.trace("MM Chain Optimization for HOP: (" + " " + getKind() + ", " + getHopID() + ", " + get_name() + ")"); ArrayList<Hop> mmChain = new ArrayList<Hop>(); ArrayList<Hop> mmOperators = new ArrayList<Hop>(); ArrayList<Hop> tempList; /* * Step-1: Identify the chain (mmChain) & clear all links among the Hops * that are involved in mmChain. */ mmOperators.add(this); // Initialize mmChain with my inputs for (Hop hi : this.getInput()) { mmChain.add(hi); } // expand each Hop in mmChain to find the entire matrix multiplication // chain int i = 0; while (i < mmChain.size()) { boolean expandable = false; Hop h = mmChain.get(i); /* * Check if mmChain[i] is expandable: * 1) It must be MATMULT * 2) It must not have been visited already * (one MATMULT should get expanded only in one chain) * 3) Its output should not be used in multiple places * (either within chain or outside the chain) */ if (h.getKind() == Hop.Kind.AggBinaryOp && ((AggBinaryOp) h).isMatrixMultiply() && h.get_visited() != Hop.VISIT_STATUS.DONE) { // check if the output of "h" is used at multiple places. If yes, it can // not be expanded. if (h.getParent().size() > 1 || inputCount( (Hop) ((h.getParent().toArray())[0]), h) > 1 ) { expandable = false; break; } else expandable = true; } h.set_visited(Hop.VISIT_STATUS.DONE); if ( !expandable ) { i = i + 1; } else { tempList = mmChain.get(i).getInput(); if (tempList.size() != 2) { throw new HopsException(this.printErrorLocation() + "Hops::rule_OptimizeMMChain(): AggBinary must have exactly two inputs."); } // add current operator to mmOperators, and its input nodes to mmChain mmOperators.add(mmChain.get(i)); mmChain.set(i, tempList.get(0)); mmChain.add(i + 1, tempList.get(1)); } } // print the MMChain if (LOG.isTraceEnabled()) { LOG.trace("Identified MM Chain: "); //System.out.print("MMChain_" + getHopID() + " (" + mmChain.size() + "): "); for (Hop h : mmChain) { LOG.trace("Hop " + h.get_name() + "(" + h.getKind() + ", " + h.getHopID() + ")" + " " + h.get_dim1() + "x" + h.get_dim2()); //System.out.print("[" + h.get_name() + "(" + h.getKind() + ", " + h.getHopID() + ")" + " " + h.get_dim1() + "x" + h.get_dim2() + "] "); } //System.out.println(""); LOG.trace("--End of MM Chain--"); } if (mmChain.size() == 2) { // If the chain size is 2, then there is nothing to optimize. return; } else { // Step-2: clear the links among Hops within the identified chain clearLinksWithinChain ( mmOperators ); // Step-3: Find the optimal ordering via dynamic programming. long dimArray[] = getDimArray ( mmChain ); // Invoke Dynamic Programming int size = mmChain.size(); int[][] split = new int[size][size]; split = mmChainDP(dimArray, mmChain.size()); // Step-4: Relink the hops using the optimal ordering (split[][]) found from DP. mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, 1, split); } System.out.println(" ."); } public void printMe() throws HopsException { if (LOG.isDebugEnabled()) { StringBuilder s = new StringBuilder(""); s.append(_kind + " " + getHopID() + "\n"); s.append(" Label: " + get_name() + "; DataType: " + _dataType + "; ValueType: " + _valueType + "\n"); s.append(" Parent: "); for (Hop h : getParent()) { s.append(h.hashCode() + "; "); } ; s.append("\n Input: "); for (Hop h : getInput()) { s.append(h.getHopID() + "; "); } s.append("\n dims [" + _dim1 + "," + _dim2 + "] blk [" + _rows_in_block + "," + _cols_in_block + "] nnz " + _nnz); s.append(" MemEstimate = Out " + (_outputMemEstimate/1024/1024) + " MB, In&Out " + (_memEstimate/1024/1024) + " MB" ); LOG.debug(s.toString()); } } public long get_dim1() { return _dim1; } public void set_dim1(long dim1) { _dim1 = dim1; } public long get_dim2() { return _dim2; } public Lop get_lops() { return _lops; } public void set_lops(Lop lops) { _lops = lops; } public SQLLops get_sqllops() { return _sqllops; } public void set_sqllops(SQLLops sqllops) { _sqllops = sqllops; } public void set_dim2(long dim2) { _dim2 = dim2; } public VISIT_STATUS get_visited() { return _visited; } public DataType get_dataType() { return _dataType; } public void set_dataType( DataType dt ) { _dataType = dt; } public void set_visited(VISIT_STATUS visited) { _visited = visited; } public void set_name(String _name) { this._name = _name; } public String get_name() { return _name; } public ValueType get_valueType() { return _valueType; } // TODO BJR: I intend to remove OpOp1.MINUS, once we made the change public enum OpOp1 { MINUS, NOT, ABS, SIN, COS, TAN, ASIN, ACOS, ATAN, SQRT, LOG, EXP, CAST_AS_SCALAR, PRINT, EIGEN, NROW, NCOL, LENGTH, ROUND, IQM, PRINT2 } // Operations that require two operands public enum OpOp2 { PLUS, MINUS, MULT, DIV, MODULUS, LESS, LESSEQUAL, GREATER, GREATEREQUAL, EQUAL, NOTEQUAL, MIN, MAX, AND, OR, LOG, POW, PRINT, CONCAT, QUANTILE, INTERQUANTILE, IQM, CENTRALMOMENT, COVARIANCE, APPEND, SEQINCR, INVALID }; // Operations that require 3 operands public enum OpOp3 { QUANTILE, INTERQUANTILE, CTABLE, CENTRALMOMENT, COVARIANCE, INVALID }; public enum AggOp { SUM, MIN, MAX, TRACE, PROD, MEAN, MAXINDEX }; public enum ReOrgOp { TRANSPOSE, DIAG_V2M, DIAG_M2V, RESHAPE }; public enum DataGenMethod { RAND, SEQ, INVALID }; public enum ParamBuiltinOp { INVALID, CDF, GROUPEDAGG, RMEMPTY }; /** * Functions that are built in, but whose execution takes place in an * external library */ public enum ExtBuiltInOp { EIGEN, CHOLESKY }; public enum FileFormatTypes { TEXT, BINARY, MM, CSV }; public enum DataOpTypes { PERSISTENTREAD, PERSISTENTWRITE, TRANSIENTREAD, TRANSIENTWRITE, FUNCTIONOUTPUT }; public enum Direction { RowCol, Row, Col }; static public HashMap<DataOpTypes, com.ibm.bi.dml.lops.Data.OperationTypes> HopsData2Lops; static { HopsData2Lops = new HashMap<Hop.DataOpTypes, com.ibm.bi.dml.lops.Data.OperationTypes>(); HopsData2Lops.put(DataOpTypes.PERSISTENTREAD, com.ibm.bi.dml.lops.Data.OperationTypes.READ); HopsData2Lops.put(DataOpTypes.PERSISTENTWRITE, com.ibm.bi.dml.lops.Data.OperationTypes.WRITE); HopsData2Lops.put(DataOpTypes.TRANSIENTWRITE, com.ibm.bi.dml.lops.Data.OperationTypes.WRITE); HopsData2Lops.put(DataOpTypes.TRANSIENTREAD, com.ibm.bi.dml.lops.Data.OperationTypes.READ); } static public HashMap<Hop.AggOp, com.ibm.bi.dml.lops.Aggregate.OperationTypes> HopsAgg2Lops; static { HopsAgg2Lops = new HashMap<Hop.AggOp, com.ibm.bi.dml.lops.Aggregate.OperationTypes>(); HopsAgg2Lops.put(AggOp.SUM, com.ibm.bi.dml.lops.Aggregate.OperationTypes.KahanSum); // HopsAgg2Lops.put(AggOp.SUM, dml.lops.Aggregate.OperationTypes.Sum); HopsAgg2Lops.put(AggOp.TRACE, com.ibm.bi.dml.lops.Aggregate.OperationTypes.KahanTrace); HopsAgg2Lops.put(AggOp.MIN, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Min); HopsAgg2Lops.put(AggOp.MAX, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Max); HopsAgg2Lops.put(AggOp.MAXINDEX, com.ibm.bi.dml.lops.Aggregate.OperationTypes.MaxIndex); HopsAgg2Lops.put(AggOp.PROD, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Product); HopsAgg2Lops.put(AggOp.MEAN, com.ibm.bi.dml.lops.Aggregate.OperationTypes.Mean); } static public HashMap<ReOrgOp, com.ibm.bi.dml.lops.Transform.OperationTypes> HopsTransf2Lops; static { HopsTransf2Lops = new HashMap<ReOrgOp, com.ibm.bi.dml.lops.Transform.OperationTypes>(); HopsTransf2Lops.put(ReOrgOp.TRANSPOSE, com.ibm.bi.dml.lops.Transform.OperationTypes.Transpose); HopsTransf2Lops.put(ReOrgOp.DIAG_V2M, com.ibm.bi.dml.lops.Transform.OperationTypes.VectortoDiagMatrix); //HopsTransf2Lops.put(ReorgOp.DIAG_M2V, dml.lops.Transform.OperationTypes.MatrixtoDiagVector); HopsTransf2Lops.put(ReOrgOp.RESHAPE, com.ibm.bi.dml.lops.Transform.OperationTypes.ReshapeMatrix); } static public HashMap<Hop.Direction, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes> HopsDirection2Lops; static { HopsDirection2Lops = new HashMap<Hop.Direction, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes>(); HopsDirection2Lops.put(Direction.RowCol, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes.RowCol); HopsDirection2Lops.put(Direction.Col, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes.Col); HopsDirection2Lops.put(Direction.Row, com.ibm.bi.dml.lops.PartialAggregate.DirectionTypes.Row); } static public HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Binary.OperationTypes> HopsOpOp2LopsB; static { HopsOpOp2LopsB = new HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Binary.OperationTypes>(); HopsOpOp2LopsB.put(OpOp2.PLUS, com.ibm.bi.dml.lops.Binary.OperationTypes.ADD); HopsOpOp2LopsB.put(OpOp2.MINUS, com.ibm.bi.dml.lops.Binary.OperationTypes.SUBTRACT); HopsOpOp2LopsB.put(OpOp2.MULT, com.ibm.bi.dml.lops.Binary.OperationTypes.MULTIPLY); HopsOpOp2LopsB.put(OpOp2.DIV, com.ibm.bi.dml.lops.Binary.OperationTypes.DIVIDE); HopsOpOp2LopsB.put(OpOp2.MODULUS, com.ibm.bi.dml.lops.Binary.OperationTypes.MODULUS); HopsOpOp2LopsB.put(OpOp2.LESS, com.ibm.bi.dml.lops.Binary.OperationTypes.LESS_THAN); HopsOpOp2LopsB.put(OpOp2.LESSEQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.LESS_THAN_OR_EQUALS); HopsOpOp2LopsB.put(OpOp2.GREATER, com.ibm.bi.dml.lops.Binary.OperationTypes.GREATER_THAN); HopsOpOp2LopsB.put(OpOp2.GREATEREQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.GREATER_THAN_OR_EQUALS); HopsOpOp2LopsB.put(OpOp2.EQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.EQUALS); HopsOpOp2LopsB.put(OpOp2.NOTEQUAL, com.ibm.bi.dml.lops.Binary.OperationTypes.NOT_EQUALS); HopsOpOp2LopsB.put(OpOp2.MIN, com.ibm.bi.dml.lops.Binary.OperationTypes.MIN); HopsOpOp2LopsB.put(OpOp2.MAX, com.ibm.bi.dml.lops.Binary.OperationTypes.MAX); HopsOpOp2LopsB.put(OpOp2.AND, com.ibm.bi.dml.lops.Binary.OperationTypes.OR); HopsOpOp2LopsB.put(OpOp2.OR, com.ibm.bi.dml.lops.Binary.OperationTypes.AND); HopsOpOp2LopsB.put(OpOp2.POW, com.ibm.bi.dml.lops.Binary.OperationTypes.NOTSUPPORTED); HopsOpOp2LopsB.put(OpOp2.LOG, com.ibm.bi.dml.lops.Binary.OperationTypes.NOTSUPPORTED); } static public HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.BinaryCP.OperationTypes> HopsOpOp2LopsBS; static { HopsOpOp2LopsBS = new HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.BinaryCP.OperationTypes>(); HopsOpOp2LopsBS.put(OpOp2.PLUS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.ADD); HopsOpOp2LopsBS.put(OpOp2.MINUS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.SUBTRACT); HopsOpOp2LopsBS.put(OpOp2.MULT, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MULTIPLY); HopsOpOp2LopsBS.put(OpOp2.DIV, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.DIVIDE); HopsOpOp2LopsBS.put(OpOp2.MODULUS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MODULUS); HopsOpOp2LopsBS.put(OpOp2.LESS, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.LESS_THAN); HopsOpOp2LopsBS.put(OpOp2.LESSEQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.LESS_THAN_OR_EQUALS); HopsOpOp2LopsBS.put(OpOp2.GREATER, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.GREATER_THAN); HopsOpOp2LopsBS.put(OpOp2.GREATEREQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.GREATER_THAN_OR_EQUALS); HopsOpOp2LopsBS.put(OpOp2.EQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.EQUALS); HopsOpOp2LopsBS.put(OpOp2.NOTEQUAL, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.NOT_EQUALS); HopsOpOp2LopsBS.put(OpOp2.MIN, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MIN); HopsOpOp2LopsBS.put(OpOp2.MAX, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.MAX); HopsOpOp2LopsBS.put(OpOp2.AND, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.AND); HopsOpOp2LopsBS.put(OpOp2.OR, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.OR); HopsOpOp2LopsBS.put(OpOp2.LOG, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.LOG); HopsOpOp2LopsBS.put(OpOp2.POW, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.POW); HopsOpOp2LopsBS.put(OpOp2.PRINT, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.PRINT); HopsOpOp2LopsBS.put(OpOp2.SEQINCR, com.ibm.bi.dml.lops.BinaryCP.OperationTypes.SEQINCR); } static public HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Unary.OperationTypes> HopsOpOp2LopsU; static { HopsOpOp2LopsU = new HashMap<Hop.OpOp2, com.ibm.bi.dml.lops.Unary.OperationTypes>(); HopsOpOp2LopsU.put(OpOp2.PLUS, com.ibm.bi.dml.lops.Unary.OperationTypes.ADD); HopsOpOp2LopsU.put(OpOp2.MINUS, com.ibm.bi.dml.lops.Unary.OperationTypes.SUBTRACT); HopsOpOp2LopsU.put(OpOp2.MULT, com.ibm.bi.dml.lops.Unary.OperationTypes.MULTIPLY); HopsOpOp2LopsU.put(OpOp2.DIV, com.ibm.bi.dml.lops.Unary.OperationTypes.DIVIDE); HopsOpOp2LopsU.put(OpOp2.MODULUS, com.ibm.bi.dml.lops.Unary.OperationTypes.MODULUS); HopsOpOp2LopsU.put(OpOp2.LESSEQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.LESS_THAN_OR_EQUALS); HopsOpOp2LopsU.put(OpOp2.LESS, com.ibm.bi.dml.lops.Unary.OperationTypes.LESS_THAN); HopsOpOp2LopsU.put(OpOp2.GREATEREQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.GREATER_THAN_OR_EQUALS); HopsOpOp2LopsU.put(OpOp2.GREATER, com.ibm.bi.dml.lops.Unary.OperationTypes.GREATER_THAN); HopsOpOp2LopsU.put(OpOp2.EQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.EQUALS); HopsOpOp2LopsU.put(OpOp2.NOTEQUAL, com.ibm.bi.dml.lops.Unary.OperationTypes.NOT_EQUALS); HopsOpOp2LopsU.put(OpOp2.AND, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); HopsOpOp2LopsU.put(OpOp2.OR, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); HopsOpOp2LopsU.put(OpOp2.MAX, com.ibm.bi.dml.lops.Unary.OperationTypes.MAX); HopsOpOp2LopsU.put(OpOp2.MIN, com.ibm.bi.dml.lops.Unary.OperationTypes.MIN); HopsOpOp2LopsU.put(OpOp2.LOG, com.ibm.bi.dml.lops.Unary.OperationTypes.LOG); HopsOpOp2LopsU.put(OpOp2.POW, com.ibm.bi.dml.lops.Unary.OperationTypes.POW); } static public HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.Unary.OperationTypes> HopsOpOp1LopsU; static { HopsOpOp1LopsU = new HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.Unary.OperationTypes>(); HopsOpOp1LopsU.put(OpOp1.MINUS, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); HopsOpOp1LopsU.put(OpOp1.NOT, com.ibm.bi.dml.lops.Unary.OperationTypes.NOT); HopsOpOp1LopsU.put(OpOp1.ABS, com.ibm.bi.dml.lops.Unary.OperationTypes.ABS); HopsOpOp1LopsU.put(OpOp1.SIN, com.ibm.bi.dml.lops.Unary.OperationTypes.SIN); HopsOpOp1LopsU.put(OpOp1.COS, com.ibm.bi.dml.lops.Unary.OperationTypes.COS); HopsOpOp1LopsU.put(OpOp1.TAN, com.ibm.bi.dml.lops.Unary.OperationTypes.TAN); HopsOpOp1LopsU.put(OpOp1.ASIN, com.ibm.bi.dml.lops.Unary.OperationTypes.ASIN); HopsOpOp1LopsU.put(OpOp1.ACOS, com.ibm.bi.dml.lops.Unary.OperationTypes.ACOS); HopsOpOp1LopsU.put(OpOp1.ATAN, com.ibm.bi.dml.lops.Unary.OperationTypes.ATAN); HopsOpOp1LopsU.put(OpOp1.SQRT, com.ibm.bi.dml.lops.Unary.OperationTypes.SQRT); HopsOpOp1LopsU.put(OpOp1.EXP, com.ibm.bi.dml.lops.Unary.OperationTypes.EXP); HopsOpOp1LopsU.put(OpOp1.LOG, com.ibm.bi.dml.lops.Unary.OperationTypes.LOG); HopsOpOp1LopsU.put(OpOp1.ROUND, com.ibm.bi.dml.lops.Unary.OperationTypes.ROUND); HopsOpOp1LopsU.put(OpOp1.CAST_AS_SCALAR, com.ibm.bi.dml.lops.Unary.OperationTypes.NOTSUPPORTED); } static public HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.UnaryCP.OperationTypes> HopsOpOp1LopsUS; static { HopsOpOp1LopsUS = new HashMap<Hop.OpOp1, com.ibm.bi.dml.lops.UnaryCP.OperationTypes>(); HopsOpOp1LopsUS.put(OpOp1.MINUS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NOTSUPPORTED); HopsOpOp1LopsUS.put(OpOp1.NOT, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NOT); HopsOpOp1LopsUS.put(OpOp1.ABS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ABS); HopsOpOp1LopsUS.put(OpOp1.SIN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.SIN); HopsOpOp1LopsUS.put(OpOp1.COS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.COS); HopsOpOp1LopsUS.put(OpOp1.TAN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.TAN); HopsOpOp1LopsUS.put(OpOp1.ASIN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ASIN); HopsOpOp1LopsUS.put(OpOp1.ACOS, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ACOS); HopsOpOp1LopsUS.put(OpOp1.ATAN, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ATAN); HopsOpOp1LopsUS.put(OpOp1.SQRT, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.SQRT); HopsOpOp1LopsUS.put(OpOp1.EXP, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.EXP); HopsOpOp1LopsUS.put(OpOp1.LOG, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.LOG); HopsOpOp1LopsUS.put(OpOp1.CAST_AS_SCALAR, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.CAST_AS_SCALAR); HopsOpOp1LopsUS.put(OpOp1.NROW, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NROW); HopsOpOp1LopsUS.put(OpOp1.NCOL, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.NCOL); HopsOpOp1LopsUS.put(OpOp1.LENGTH, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.LENGTH); HopsOpOp1LopsUS.put(OpOp1.PRINT, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.PRINT); HopsOpOp1LopsUS.put(OpOp1.PRINT2, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.PRINT2); HopsOpOp1LopsUS.put(OpOp1.ROUND, com.ibm.bi.dml.lops.UnaryCP.OperationTypes.ROUND); } static public HashMap<Hop.OpOp1, String> HopsOpOp12String; static { HopsOpOp12String = new HashMap<OpOp1, String>(); HopsOpOp12String.put(OpOp1.ABS, "abs"); HopsOpOp12String.put(OpOp1.CAST_AS_SCALAR, "castAsScalar"); HopsOpOp12String.put(OpOp1.COS, "cos"); HopsOpOp12String.put(OpOp1.EIGEN, "eigen"); HopsOpOp12String.put(OpOp1.EXP, "exp"); HopsOpOp12String.put(OpOp1.IQM, "iqm"); HopsOpOp12String.put(OpOp1.LENGTH, "length"); HopsOpOp12String.put(OpOp1.LOG, "log"); HopsOpOp12String.put(OpOp1.MINUS, "-"); HopsOpOp12String.put(OpOp1.NCOL, "ncol"); HopsOpOp12String.put(OpOp1.NOT, "!"); HopsOpOp12String.put(OpOp1.NROW, "nrow"); HopsOpOp12String.put(OpOp1.PRINT, "print"); HopsOpOp12String.put(OpOp1.PRINT2, "print2"); HopsOpOp12String.put(OpOp1.ROUND, "round"); HopsOpOp12String.put(OpOp1.SIN, "sin"); HopsOpOp12String.put(OpOp1.SQRT, "sqrt"); HopsOpOp12String.put(OpOp1.TAN, "tan"); HopsOpOp12String.put(OpOp1.ASIN, "asin"); HopsOpOp12String.put(OpOp1.ACOS, "acos"); HopsOpOp12String.put(OpOp1.ATAN, "atan"); } static public HashMap<Hop.ParamBuiltinOp, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes> HopsParameterizedBuiltinLops; static { HopsParameterizedBuiltinLops = new HashMap<Hop.ParamBuiltinOp, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes>(); HopsParameterizedBuiltinLops.put(ParamBuiltinOp.CDF, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes.CDF); HopsParameterizedBuiltinLops.put(ParamBuiltinOp.RMEMPTY, com.ibm.bi.dml.lops.ParameterizedBuiltin.OperationTypes.RMEMPTY); } static public HashMap<Hop.OpOp2, String> HopsOpOp2String; static { HopsOpOp2String = new HashMap<Hop.OpOp2, String>(); HopsOpOp2String.put(OpOp2.PLUS, "+"); HopsOpOp2String.put(OpOp2.MINUS, "-"); HopsOpOp2String.put(OpOp2.MULT, "*"); HopsOpOp2String.put(OpOp2.DIV, "/"); HopsOpOp2String.put(OpOp2.MIN, "min"); HopsOpOp2String.put(OpOp2.MAX, "max"); HopsOpOp2String.put(OpOp2.LESSEQUAL, "<="); HopsOpOp2String.put(OpOp2.LESS, "<"); HopsOpOp2String.put(OpOp2.GREATEREQUAL, ">="); HopsOpOp2String.put(OpOp2.GREATER, ">"); HopsOpOp2String.put(OpOp2.EQUAL, "="); HopsOpOp2String.put(OpOp2.NOTEQUAL, "!="); HopsOpOp2String.put(OpOp2.OR, "|"); HopsOpOp2String.put(OpOp2.AND, "&"); HopsOpOp2String.put(OpOp2.LOG, "log"); HopsOpOp2String.put(OpOp2.POW, "^"); HopsOpOp2String.put(OpOp2.CONCAT, "concat"); HopsOpOp2String.put(OpOp2.INVALID, "?"); HopsOpOp2String.put(OpOp2.QUANTILE, "quantile"); HopsOpOp2String.put(OpOp2.INTERQUANTILE, "interquantile"); HopsOpOp2String.put(OpOp2.IQM, "IQM"); HopsOpOp2String.put(OpOp2.CENTRALMOMENT, "centraMoment"); HopsOpOp2String.put(OpOp2.COVARIANCE, "cov"); HopsOpOp2String.put(OpOp2.APPEND, "APP"); } static public HashMap<Hop.OpOp3, String> HopsOpOp3String; static { HopsOpOp3String = new HashMap<Hop.OpOp3, String>(); HopsOpOp3String.put(OpOp3.QUANTILE, "quantile"); HopsOpOp3String.put(OpOp3.INTERQUANTILE, "interquantile"); HopsOpOp3String.put(OpOp3.CTABLE, "ctable"); HopsOpOp3String.put(OpOp3.CENTRALMOMENT, "centraMoment"); HopsOpOp3String.put(OpOp3.COVARIANCE, "cov"); } static public HashMap<Hop.Direction, String> HopsDirection2String; static { HopsDirection2String = new HashMap<Hop.Direction, String>(); HopsDirection2String.put(Direction.RowCol, "RC"); HopsDirection2String.put(Direction.Col, "C"); HopsDirection2String.put(Direction.Row, "R"); } static public HashMap<Hop.AggOp, String> HopsAgg2String; static { HopsAgg2String = new HashMap<Hop.AggOp, String>(); HopsAgg2String.put(AggOp.SUM, "+"); HopsAgg2String.put(AggOp.PROD, "*"); HopsAgg2String.put(AggOp.MIN, "min"); HopsAgg2String.put(AggOp.MAX, "max"); HopsAgg2String.put(AggOp.MAXINDEX, "maxindex"); HopsAgg2String.put(AggOp.TRACE, "trace"); HopsAgg2String.put(AggOp.MEAN, "mean"); } static public HashMap<Hop.ReOrgOp, String> HopsTransf2String; static { HopsTransf2String = new HashMap<ReOrgOp, String>(); HopsTransf2String.put(ReOrgOp.TRANSPOSE, "t"); HopsTransf2String.put(ReOrgOp.DIAG_M2V, "diagM2V"); HopsTransf2String.put(ReOrgOp.DIAG_V2M, "diagV2M"); HopsTransf2String.put(ReOrgOp.RESHAPE, "rshape"); } static public HashMap<DataOpTypes, String> HopsData2String; static { HopsData2String = new HashMap<Hop.DataOpTypes, String>(); HopsData2String.put(DataOpTypes.PERSISTENTREAD, "PRead"); HopsData2String.put(DataOpTypes.PERSISTENTWRITE, "PWrite"); HopsData2String.put(DataOpTypes.TRANSIENTWRITE, "TWrite"); HopsData2String.put(DataOpTypes.TRANSIENTREAD, "TRead"); } public static boolean isFunction(OpOp2 op) { return op == OpOp2.MIN || op == OpOp2.MAX || op == OpOp2.LOG;// || op == OpOp2.CONCAT; //concat is || in Netezza } public static boolean isSupported(OpOp2 op) { return op != OpOp2.INVALID && op != OpOp2.QUANTILE && op != OpOp2.INTERQUANTILE && op != OpOp2.IQM; } public static boolean isFunction(OpOp1 op) { return op == OpOp1.SIN || op == OpOp1.TAN || op == OpOp1.COS || op == OpOp1.ABS || op == OpOp1.EXP || op == OpOp1.LOG || op == OpOp1.ROUND || op == OpOp1.SQRT; } public static boolean isBooleanOperation(OpOp2 op) { return op == OpOp2.AND || op == OpOp2.EQUAL || op == OpOp2.GREATER || op == OpOp2.GREATEREQUAL || op == OpOp2.LESS || op == OpOp2.LESSEQUAL || op == OpOp2.OR; } public static ValueType getResultValueType(ValueType vt1, ValueType vt2) { if(vt1 == ValueType.STRING || vt2 == ValueType.STRING) return ValueType.STRING; else if(vt1 == ValueType.DOUBLE || vt2 == ValueType.DOUBLE) return ValueType.DOUBLE; else return ValueType.INT; } protected GENERATES determineGeneratesFlag() { //Check whether this is going to be an Insert or With GENERATES gen = GENERATES.SQL; if(this.getParent().size() > 1) gen = GENERATES.DML; else { boolean hasWriteOutput = false; for(Hop h : this.getParent()) if(h instanceof DataOp) { DataOp o = ((DataOp)h); if(o._dataop == DataOpTypes.PERSISTENTWRITE || o._dataop == DataOpTypes.TRANSIENTWRITE) { hasWriteOutput = true; break; } } else if(h instanceof UnaryOp && ((UnaryOp)h).get_op() == OpOp1.PRINT2) { hasWriteOutput = true; break; } if(hasWriteOutput) gen = GENERATES.DML; } if(BREAKONSCALARS && this.get_dataType() == DataType.SCALAR) gen = GENERATES.DML; return gen; } ///////////////////////////////////// // methods for dynamic re-compilation ///////////////////////////////////// /** * Indicates if dynamic recompilation is required for this hop. */ public boolean requiresRecompile() { return _requiresRecompile; } public void setRequiresRecompile() { _requiresRecompile = true; } public void unsetRequiresRecompile() { _requiresRecompile = false; } /** * Update the output size information for this hop. */ public abstract void refreshSizeInformation(); /** * Util function for refreshing scalar rows input parameter. */ protected void refreshRowsParameterInformation( Hop input ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim1(input.getInput().get(0).get_dim1()); else if ( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim1(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim1(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>()); if( dim != Long.MAX_VALUE ) //if known set_dim1( dim ); } } public void refreshRowsParameterInformation( Hop input, LocalVariableMap vars ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim1(input.getInput().get(0).get_dim1()); else if ( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim1(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim1(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>(), vars); if( dim != Long.MAX_VALUE ) //if known set_dim1( dim ); } else if( input instanceof DataOp ) { String name = input.get_name(); Data dat = vars.get(name); if( dat!=null && dat instanceof ScalarObject ) set_dim1( ((ScalarObject)dat).getLongValue() ); } } /** * Util function for refreshing scalar cols input parameter. */ protected void refreshColsParameterInformation( Hop input ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim2(input.getInput().get(0).get_dim1()); else if( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim2(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim2(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>()); if( dim != Long.MAX_VALUE ) //if known set_dim2( dim ); } } public void refreshColsParameterInformation( Hop input, LocalVariableMap vars ) { if( input instanceof UnaryOp ) { if( ((UnaryOp)input).get_op() == Hop.OpOp1.NROW ) set_dim2(input.getInput().get(0).get_dim1()); else if( ((UnaryOp)input).get_op() == Hop.OpOp1.NCOL ) set_dim2(input.getInput().get(0).get_dim2()); } else if ( input instanceof LiteralOp ) //TODO discuss with Doug { set_dim2(UtilFunctions.parseToLong(input.get_name())); } else if ( input instanceof BinaryOp ) { long dim = rEvalSimpleBinarySizeExpression(input, new HashMap<Long, Long>(), vars); if( dim != Long.MAX_VALUE ) //if known set_dim2( dim ); } else if( input instanceof DataOp ) { String name = input.get_name(); Data dat = vars.get(name); if( dat!=null && dat instanceof ScalarObject ) set_dim2( ((ScalarObject)dat).getLongValue() ); } } /** * Function to evaluate simple size expressions of binary operators * (plus, minus, mult, div, min, max) over literals and now/ncol. * * It returns the exact results of this expressions if known, otherwise * Long.MAX_VALUE if unknown. * * TODO: extend to memo table usage (for this, memo needs to contain min/max bounds, * other wise expressions like b-a might give not a worst-case estimate if a is overestimated) * * @param root * @return */ protected long rEvalSimpleBinarySizeExpression( Hop root, HashMap<Long, Long> memo ) { //memoization (prevent redundant computation of common subexpr) if( memo.containsKey(root.getHopID()) ) return memo.get(root.getHopID()); long ret = Long.MAX_VALUE; if( root instanceof LiteralOp ) { long dim = UtilFunctions.parseToLong(root.get_name()); if( dim != -1 ) //if known ret = dim; } else if( root instanceof UnaryOp ) { UnaryOp uroot = (UnaryOp) root; long dim = -1; if(uroot.get_op() == Hop.OpOp1.NROW) dim = uroot.getInput().get(0).get_dim1(); else if( uroot.get_op() == Hop.OpOp1.NCOL ) dim = uroot.getInput().get(0).get_dim2(); if( dim != -1 ) //if known ret = dim; } else if( root instanceof BinaryOp ) { if( OptimizerUtils.ALLOW_SIZE_EXPRESSION_EVALUATION ) { BinaryOp broot = (BinaryOp) root; long lret = rEvalSimpleBinarySizeExpression(broot.getInput().get(0), memo); long rret = rEvalSimpleBinarySizeExpression(broot.getInput().get(1), memo); //note: positive and negative values might be valid subexpressions if( lret!=Long.MAX_VALUE && rret!=Long.MAX_VALUE ) //if known { switch( broot.op ) { case PLUS: ret = lret + rret; break; case MINUS: ret = lret - rret; break; case MULT: ret = lret * rret; break; case DIV: ret = lret / rret; break; case MIN: ret = Math.min(lret, rret); break; case MAX: ret = Math.max(lret, rret); break; } } } } memo.put(root.getHopID(), ret); return ret; } protected long rEvalSimpleBinarySizeExpression( Hop root, HashMap<Long, Long> memo, LocalVariableMap vars ) { //memoization (prevent redundant computation of common subexpr) if( memo.containsKey(root.getHopID()) ) return memo.get(root.getHopID()); long ret = Long.MAX_VALUE; if( root instanceof LiteralOp ) { long dim = UtilFunctions.parseToLong(root.get_name()); if( dim != -1 ) //if known ret = dim; } else if( root instanceof UnaryOp ) { UnaryOp uroot = (UnaryOp) root; long dim = -1; if(uroot.get_op() == Hop.OpOp1.NROW) dim = uroot.getInput().get(0).get_dim1(); else if( uroot.get_op() == Hop.OpOp1.NCOL ) dim = uroot.getInput().get(0).get_dim2(); if( dim != -1 ) //if known ret = dim; } else if( root instanceof DataOp ) { String name = root.get_name(); Data dat = vars.get(name); if( dat!=null && dat instanceof ScalarObject ) ret = ((ScalarObject)dat).getLongValue(); } else if( root instanceof BinaryOp ) { if( OptimizerUtils.ALLOW_SIZE_EXPRESSION_EVALUATION ) { BinaryOp broot = (BinaryOp) root; long lret = rEvalSimpleBinarySizeExpression(broot.getInput().get(0), memo, vars); long rret = rEvalSimpleBinarySizeExpression(broot.getInput().get(1), memo, vars); //note: positive and negative values might be valid subexpressions if( lret!=Long.MAX_VALUE && rret!=Long.MAX_VALUE ) //if known { switch( broot.op ) { case PLUS: ret = lret + rret; break; case MINUS: ret = lret - rret; break; case MULT: ret = lret * rret; break; case DIV: ret = lret / rret; break; case MIN: ret = Math.min(lret, rret); break; case MAX: ret = Math.max(lret, rret); break; } } } } memo.put(root.getHopID(), ret); return ret; } protected void rConstantFoldingBinaryExpression( Hop root ) throws HopsException { if( root.get_visited() == VISIT_STATUS.DONE ) return; //recursively process childs (before replacement to allow bottom-recursion) //no iterator in order to prevent concurrent modification for( int i=0; i<root.getInput().size(); i++ ) { Hop h = root.getInput().get(i); rConstantFoldingBinaryExpression(h); } //fold binary op if both are literals if( root instanceof BinaryOp && root.getInput().get(0) instanceof LiteralOp && root.getInput().get(1) instanceof LiteralOp ) { BinaryOp broot = (BinaryOp) root; LiteralOp lit1 = (LiteralOp) root.getInput().get(0); LiteralOp lit2 = (LiteralOp) root.getInput().get(1); double ret = Double.MAX_VALUE; if( (lit1.get_valueType()==ValueType.DOUBLE || lit1.get_valueType()==ValueType.INT) && (lit2.get_valueType()==ValueType.DOUBLE || lit2.get_valueType()==ValueType.INT) ) { double lret = lit1.getDoubleValue(); double rret = lit2.getDoubleValue(); switch( broot.op ) { case PLUS: ret = lret + rret; break; case MINUS: ret = lret - rret; break; case MULT: ret = lret * rret; break; case DIV: ret = lret / rret; break; case MIN: ret = Math.min(lret, rret); break; case MAX: ret = Math.max(lret, rret); break; } } if( ret!=Double.MAX_VALUE ) { LiteralOp literal = null; if( broot.get_valueType()==ValueType.DOUBLE ) literal = new LiteralOp(String.valueOf(ret), ret); else if( broot.get_valueType()==ValueType.INT ) literal = new LiteralOp(String.valueOf((long)ret), (long)ret); //reverse replacement in order to keep common subexpression elimination for( int i=0; i<broot.getParent().size(); i++ ) //for all parents { Hop parent = broot.getParent().get(i); for( int j=0; j<parent.getInput().size(); j++ ) { Hop child = parent.getInput().get(j); if( broot == child ) { //replace operator parent.getInput().remove(j); parent.getInput().add(j, literal); } } } broot.getParent().clear(); } } //mark processed root.set_visited( VISIT_STATUS.DONE ); } /** * * @return */ public String constructBaseDir() { StringBuilder sb = new StringBuilder(); sb.append( ConfigurationManager.getConfig().getTextValue(DMLConfig.SCRATCH_SPACE) ); sb.append( Lop.FILE_SEPARATOR ); sb.append( Lop.PROCESS_PREFIX ); sb.append( DMLScript.getUUID() ); sb.append( Lop.FILE_SEPARATOR ); sb.append( Lop.FILE_SEPARATOR ); sb.append( ProgramConverter.CP_ROOT_THREAD_ID ); sb.append( Lop.FILE_SEPARATOR ); return sb.toString(); } /** * Clones the attributes of that and copies it over to this. * * @param that * @throws HopsException */ protected void clone( Hop that, boolean withRefs ) throws CloneNotSupportedException { if( withRefs ) throw new CloneNotSupportedException( "Hops deep copy w/ lops/inputs/parents not supported." ); ID = that.ID; _kind = that._kind; _name = that._name; _dataType = that._dataType; _valueType = that._valueType; _visited = that._visited; _dim1 = that._dim1; _dim2 = that._dim2; _rows_in_block = that._rows_in_block; _cols_in_block = that._cols_in_block; _nnz = that._nnz; //no copy of lops (regenerated) _parent = new ArrayList<Hop>(); _input = new ArrayList<Hop>(); _lops = null; _sqllops = null; _etype = that._etype; _etypeForced = that._etypeForced; _outputMemEstimate = that._outputMemEstimate; _memEstimate = that._memEstimate; _processingMemEstimate = that._processingMemEstimate; _requiresRecompile = that._requiresRecompile; _beginLine = that._beginLine; _beginColumn = that._beginColumn; _endLine = that._endLine; _endColumn = that._endColumn; } public abstract Object clone() throws CloneNotSupportedException; public abstract boolean compare( Hop that ); /////////////////////////////////////////////////////////////////////////// // store position information for Hops /////////////////////////////////////////////////////////////////////////// public int _beginLine, _beginColumn; public int _endLine, _endColumn; public void setBeginLine(int passed) { _beginLine = passed; } public void setBeginColumn(int passed) { _beginColumn = passed; } public void setEndLine(int passed) { _endLine = passed; } public void setEndColumn(int passed) { _endColumn = passed; } public void setAllPositions(int blp, int bcp, int elp, int ecp){ _beginLine = blp; _beginColumn = bcp; _endLine = elp; _endColumn = ecp; } public int getBeginLine() { return _beginLine; } public int getBeginColumn() { return _beginColumn; } public int getEndLine() { return _endLine; } public int getEndColumn() { return _endColumn; } public String printErrorLocation(){ return "ERROR: line " + _beginLine + ", column " + _beginColumn + " -- "; } public String printWarningLocation(){ return "WARNING: line " + _beginLine + ", column " + _beginColumn + " -- "; } } // end class
20969: Various Engine Enhancements - Fix unnecessary output of optimize mm chain
SystemML/DML/src/com/ibm/bi/dml/hops/Hop.java
20969: Various Engine Enhancements - Fix unnecessary output of optimize mm chain
<ide><path>ystemML/DML/src/com/ibm/bi/dml/hops/Hop.java <ide> // Step-4: Relink the hops using the optimal ordering (split[][]) found from DP. <ide> mmChainRelinkHops(mmOperators.get(0), 0, size - 1, mmChain, mmOperators, 1, split); <ide> } <del> System.out.println(" ."); <add> //System.out.println(" ."); <ide> } <ide> <ide> public void printMe() throws HopsException {
Java
agpl-3.0
d6f7fda044af1717c8ccc37ac611eec06e43be03
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.elki.algorithm.clustering.kmeans; /* This file is part of ELKI: Environment for Developing KDD-Applications Supported by Index-Structures Copyright (C) 2015 Ludwig-Maximilians-Universität München Lehr- und Forschungseinheit für Datenbanksysteme ELKI Development Team 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/>. */ import de.lmu.ifi.dbs.elki.algorithm.clustering.kmeans.initialization.KMedoidsInitialization; import de.lmu.ifi.dbs.elki.data.Cluster; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.model.MedoidModel; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableIntegerDataStore; import de.lmu.ifi.dbs.elki.database.ids.ArrayDBIDs; import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.DBIDArrayIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.math.random.RandomFactory; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.RandomParameter; /** * Clustering Large Applications (CLARA) is a clustering method for large data * sets based on PAM, partitioning around medoids ({@link KMedoidsPAM}) based on * sampling. * * Reference: * <p> * L. Kaufman, P. J. Rousseeuw<br /> * Clustering Large Data Sets (with discussion)<br /> * in: Pattern Recognition in Practice II * </p> * * @author Erich Schubert * * @param <V> Vector type */ @Reference(authors = "L. Kaufman, P. J. Rousseeuw", // title = "Clustering Large Data Sets (with discussion)", // booktitle = "Pattern Recognition in Practice II") public class CLARA<V> extends KMedoidsPAM<V> { /** * Class logger. */ private static final Logging LOG = Logging.getLogger(CLARA.class); /** * Sampling rate. If less than 1, it is considered to be a relative value. */ double sampling; /** * Number of samples to draw (i.e. iterations). */ int numsamples; /** * Random factory for initialization. */ RandomFactory random; /** * Constructor. * * @param distanceFunction Distance function to use * @param k Number of clusters to produce * @param maxiter Maximum number of iterations * @param initializer Initialization function * @param numsamples Number of samples (sampling iterations) * @param sampling Sampling rate (absolute or relative) * @param random Random generator */ public CLARA(DistanceFunction<? super V> distanceFunction, int k, int maxiter, KMedoidsInitialization<V> initializer, int numsamples, double sampling, RandomFactory random) { super(distanceFunction, k, maxiter, initializer); this.numsamples = numsamples; this.sampling = sampling; this.random = random; } @Override public Clustering<MedoidModel> run(Database database, Relation<V> relation) { if(relation.size() <= 0) { return new Clustering<>("CLARA Clustering", "clara-clustering"); } DBIDs ids = relation.getDBIDs(); int sampleSize = (int) ((sampling < 1.) ? sampling * ids.size() : sampling); DistanceQuery<V> distQ = database.getDistanceQuery(relation, getDistanceFunction()); double best = Double.POSITIVE_INFINITY; ArrayModifiableDBIDs bestmedoids = null; WritableIntegerDataStore bestclusters = null; FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Random samples.", numsamples, LOG) : null; for(int j = 0; j < numsamples; j++) { DBIDs rids = DBIDUtil.randomSample(ids, sampleSize, random); // Choose initial medoids ArrayModifiableDBIDs medoids = DBIDUtil.newArray(initializer.chooseInitialMedoids(k, rids, distQ)); // Setup cluster assignment store WritableIntegerDataStore assignment = DataStoreUtil.makeIntegerStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, -1); runPAMOptimization(distQ, rids, medoids, assignment); double score = assignRemainingToNearestCluster(medoids, ids, rids, assignment, distQ); if(score < best) { best = score; bestmedoids = medoids; bestclusters = assignment; } LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); // Rewrap result int[] sizes = new int[k]; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { sizes[bestclusters.intValue(iter)] += 1; } ArrayModifiableDBIDs[] clusters = new ArrayModifiableDBIDs[k]; for(int i = 0; i < k; i++) { clusters[i] = DBIDUtil.newArray(sizes[i]); } for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { clusters[bestclusters.intValue(iter)].add(iter); } // Wrap result Clustering<MedoidModel> result = new Clustering<>("CLARA Clustering", "clara-clustering"); for(DBIDArrayIter it = bestmedoids.iter(); it.valid(); it.advance()) { MedoidModel model = new MedoidModel(DBIDUtil.deref(it)); result.addToplevelCluster(new Cluster<>(clusters[it.getOffset()], model)); } return result; } /** * Returns a list of clusters. The k<sup>th</sup> cluster contains the ids of * those FeatureVectors, that are nearest to the k<sup>th</sup> mean. * * @param means Object centroids * @param ids Object ids * @param rids Sample that was already assigned * @param assignment cluster assignment * @param distQ distance query * @return Sum of distances. */ protected double assignRemainingToNearestCluster(ArrayDBIDs means, DBIDs ids, DBIDs rids, WritableIntegerDataStore assignment, DistanceQuery<V> distQ) { rids = DBIDUtil.ensureSet(rids); // Ensure we have fast contains double distsum = 0.; DBIDArrayIter miter = means.iter(); for(DBIDIter iditer = distQ.getRelation().iterDBIDs(); iditer.valid(); iditer.advance()) { if(rids.contains(iditer)) { continue; } double mindist = Double.POSITIVE_INFINITY; int minIndex = 0; miter.seek(0); // Reuse iterator. for(int i = 0; miter.valid(); miter.advance(), i++) { double dist = distQ.distance(iditer, miter); if(dist < mindist) { minIndex = i; mindist = dist; } } distsum += mindist; assignment.put(iditer, minIndex); } return distsum; } /** * Parameterization class. * * @author Erich Schubert * * @apiviz.exclude */ public static class Parameterizer<V> extends KMedoidsPAM.Parameterizer<V> { /** * The number of samples to run. */ public static final OptionID NUMSAMPLES_ID = new OptionID("clara.samples", "Number of samples (iterations) to run."); /** * The sample size. */ public static final OptionID SAMPLESIZE_ID = new OptionID("clara.samplesize", "The size of the sample."); /** * Random generator. */ public static final OptionID RANDOM_ID = new OptionID("clara.random", "Random generator seed."); /** * Sampling rate. If less than 1, it is considered to be a relative value. */ double sampling; /** * Number of samples to draw (i.e. iterations). */ int numsamples; /** * Random factory for initialization. */ RandomFactory random; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); IntParameter numsamplesP = new IntParameter(NUMSAMPLES_ID, 5) // .addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if(config.grab(numsamplesP)) { numsamples = numsamplesP.intValue(); } DoubleParameter samplingP = new DoubleParameter(SAMPLESIZE_ID) // .addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if(config.grab(samplingP)) { sampling = samplingP.doubleValue(); } RandomParameter randomP = new RandomParameter(RANDOM_ID); if(config.grab(randomP)) { random = randomP.getValue(); } } @Override protected CLARA<V> makeInstance() { return new CLARA<>(distanceFunction, k, maxiter, initializer, numsamples, sampling, random); } } }
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/CLARA.java
package de.lmu.ifi.dbs.elki.algorithm.clustering.kmeans; import de.lmu.ifi.dbs.elki.algorithm.clustering.kmeans.initialization.KMedoidsInitialization; import de.lmu.ifi.dbs.elki.data.Cluster; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.model.MedoidModel; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableIntegerDataStore; import de.lmu.ifi.dbs.elki.database.ids.ArrayDBIDs; import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.DBIDArrayIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.progress.FiniteProgress; import de.lmu.ifi.dbs.elki.math.random.RandomFactory; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.RandomParameter; /** * Clustering Large Applications (CLARA) is a clustering method for large data * sets based on PAM, partitioning around medoids ({@link KMedoidsPAM}) based on * sampling. * * Reference: * <p> * L. Kaufman, P. J. Rousseeuw<br /> * Clustering Large Data Sets (with discussion)<br /> * in: Pattern Recognition in Practice II * </p> * * @author Erich Schubert * * @param <V> Vector type */ @Reference(authors = "L. Kaufman, P. J. Rousseeuw", // title = "Clustering Large Data Sets (with discussion)", // booktitle = "Pattern Recognition in Practice II") public class CLARA<V> extends KMedoidsPAM<V> { /** * Class logger. */ private static final Logging LOG = Logging.getLogger(CLARA.class); /** * Sampling rate. If less than 1, it is considered to be a relative value. */ double sampling; /** * Number of samples to draw (i.e. iterations). */ int numsamples; /** * Random factory for initialization. */ RandomFactory random; /** * Constructor. * * @param distanceFunction Distance function to use * @param k Number of clusters to produce * @param maxiter Maximum number of iterations * @param initializer Initialization function * @param numsamples Number of samples (sampling iterations) * @param sampling Sampling rate (absolute or relative) * @param random Random generator */ public CLARA(DistanceFunction<? super V> distanceFunction, int k, int maxiter, KMedoidsInitialization<V> initializer, int numsamples, double sampling, RandomFactory random) { super(distanceFunction, k, maxiter, initializer); this.numsamples = numsamples; this.sampling = sampling; this.random = random; } @Override public Clustering<MedoidModel> run(Database database, Relation<V> relation) { if(relation.size() <= 0) { return new Clustering<>("CLARA Clustering", "clara-clustering"); } DBIDs ids = relation.getDBIDs(); int sampleSize = (int) ((sampling < 1.) ? sampling * ids.size() : sampling); DistanceQuery<V> distQ = database.getDistanceQuery(relation, getDistanceFunction()); double best = Double.POSITIVE_INFINITY; ArrayModifiableDBIDs bestmedoids = null; WritableIntegerDataStore bestclusters = null; FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Random samples.", numsamples, LOG) : null; for(int j = 0; j < numsamples; j++) { DBIDs rids = DBIDUtil.randomSample(ids, sampleSize, random); // Choose initial medoids ArrayModifiableDBIDs medoids = DBIDUtil.newArray(initializer.chooseInitialMedoids(k, rids, distQ)); // Setup cluster assignment store WritableIntegerDataStore assignment = DataStoreUtil.makeIntegerStorage(ids, DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, -1); runPAMOptimization(distQ, rids, medoids, assignment); double score = assignRemainingToNearestCluster(medoids, ids, rids, assignment, distQ); if(score < best) { best = score; bestmedoids = medoids; bestclusters = assignment; } LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); // Rewrap result int[] sizes = new int[k]; for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { sizes[bestclusters.intValue(iter)] += 1; } ArrayModifiableDBIDs[] clusters = new ArrayModifiableDBIDs[k]; for(int i = 0; i < k; i++) { clusters[i] = DBIDUtil.newArray(sizes[i]); } for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { clusters[bestclusters.intValue(iter)].add(iter); } // Wrap result Clustering<MedoidModel> result = new Clustering<>("CLARA Clustering", "clara-clustering"); for(DBIDArrayIter it = bestmedoids.iter(); it.valid(); it.advance()) { MedoidModel model = new MedoidModel(DBIDUtil.deref(it)); result.addToplevelCluster(new Cluster<>(clusters[it.getOffset()], model)); } return result; } /** * Returns a list of clusters. The k<sup>th</sup> cluster contains the ids of * those FeatureVectors, that are nearest to the k<sup>th</sup> mean. * * @param means Object centroids * @param ids Object ids * @param rids Sample that was already assigned * @param assignment cluster assignment * @param distQ distance query * @return Sum of distances. */ protected double assignRemainingToNearestCluster(ArrayDBIDs means, DBIDs ids, DBIDs rids, WritableIntegerDataStore assignment, DistanceQuery<V> distQ) { rids = DBIDUtil.ensureSet(rids); // Ensure we have fast contains double distsum = 0.; DBIDArrayIter miter = means.iter(); for(DBIDIter iditer = distQ.getRelation().iterDBIDs(); iditer.valid(); iditer.advance()) { if(rids.contains(iditer)) { continue; } double mindist = Double.POSITIVE_INFINITY; int minIndex = 0; miter.seek(0); // Reuse iterator. for(int i = 0; miter.valid(); miter.advance(), i++) { double dist = distQ.distance(iditer, miter); if(dist < mindist) { minIndex = i; mindist = dist; } } distsum += mindist; assignment.put(iditer, minIndex); } return distsum; } /** * Parameterization class. * * @author Erich Schubert * * @apiviz.exclude */ public static class Parameterizer<V> extends KMedoidsPAM.Parameterizer<V> { /** * The number of samples to run. */ public static final OptionID NUMSAMPLES_ID = new OptionID("clara.samples", "Number of samples (iterations) to run."); /** * The sample size. */ public static final OptionID SAMPLESIZE_ID = new OptionID("clara.samplesize", "The size of the sample."); /** * Random generator. */ public static final OptionID RANDOM_ID = new OptionID("clara.random", "Random generator seed."); /** * Sampling rate. If less than 1, it is considered to be a relative value. */ double sampling; /** * Number of samples to draw (i.e. iterations). */ int numsamples; /** * Random factory for initialization. */ RandomFactory random; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); IntParameter numsamplesP = new IntParameter(NUMSAMPLES_ID, 5) // .addConstraint(CommonConstraints.GREATER_EQUAL_ONE_INT); if(config.grab(numsamplesP)) { numsamples = numsamplesP.intValue(); } DoubleParameter samplingP = new DoubleParameter(SAMPLESIZE_ID) // .addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if(config.grab(samplingP)) { sampling = samplingP.doubleValue(); } RandomParameter randomP = new RandomParameter(RANDOM_ID); if(config.grab(randomP)) { random = randomP.getValue(); } } @Override protected CLARA<V> makeInstance() { return new CLARA<>(distanceFunction, k, maxiter, initializer, numsamples, sampling, random); } } }
Restore copyright banner that Eclipse removed automagically.
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/CLARA.java
Restore copyright banner that Eclipse removed automagically.
<ide><path>lki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/CLARA.java <ide> package de.lmu.ifi.dbs.elki.algorithm.clustering.kmeans; <add> <add>/* <add> This file is part of ELKI: <add> Environment for Developing KDD-Applications Supported by Index-Structures <add> <add> Copyright (C) 2015 <add> Ludwig-Maximilians-Universität München <add> Lehr- und Forschungseinheit für Datenbanksysteme <add> ELKI Development Team <add> <add> This program is free software: you can redistribute it and/or modify <add> it under the terms of the GNU Affero General Public License as published by <add> the Free Software Foundation, either version 3 of the License, or <add> (at your option) any later version. <add> <add> This program is distributed in the hope that it will be useful, <add> but WITHOUT ANY WARRANTY; without even the implied warranty of <add> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add> GNU Affero General Public License for more details. <add> <add> You should have received a copy of the GNU Affero General Public License <add> along with this program. If not, see <http://www.gnu.org/licenses/>. <add>*/ <ide> <ide> import de.lmu.ifi.dbs.elki.algorithm.clustering.kmeans.initialization.KMedoidsInitialization; <ide> import de.lmu.ifi.dbs.elki.data.Cluster;
Java
apache-2.0
a614ec9a5a0197c39a9b72488d99a993ceb8ce0e
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.provisioning; import com.yahoo.component.Version; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Capacity; import com.yahoo.config.provision.ClusterResources; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.flags.FlagSource; import com.yahoo.vespa.flags.PermanentFlags; import com.yahoo.vespa.hosted.provision.NodeRepository; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import static com.yahoo.config.provision.NodeResources.Architecture; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.PermanentFlags.ADMIN_CLUSTER_NODE_ARCHITECTURE; import static java.util.Objects.requireNonNull; /** * Defines the policies for assigning cluster capacity in various environments * * @author bratseth * @see NodeResourceLimits */ public class CapacityPolicies { private final Zone zone; private final Function<ClusterSpec.Type, Boolean> sharedHosts; private final FlagSource flagSource; public CapacityPolicies(NodeRepository nodeRepository) { this.zone = nodeRepository.zone(); this.sharedHosts = type -> PermanentFlags.SHARED_HOST.bindTo(nodeRepository.flagSource()).value().isEnabled(type.name()); this.flagSource = nodeRepository.flagSource(); } public Capacity applyOn(Capacity capacity, ApplicationId application) { return capacity.withLimits(applyOn(capacity.minResources(), capacity, application), applyOn(capacity.maxResources(), capacity, application)); } private ClusterResources applyOn(ClusterResources resources, Capacity capacity, ApplicationId application) { int nodes = decideSize(resources.nodes(), capacity.isRequired(), application.instance().isTester()); int groups = Math.min(resources.groups(), nodes); // cannot have more groups than nodes var nodeResources = decideNodeResources(resources.nodeResources(), capacity.isRequired()); return new ClusterResources(nodes, groups, nodeResources); } private int decideSize(int requested, boolean required, boolean isTester) { if (isTester) return 1; if (required) return requested; switch(zone.environment()) { case dev : case test : return 1; case perf : return Math.min(requested, 3); case staging: return requested <= 1 ? requested : Math.max(2, requested / 10); case prod : return requested; default : throw new IllegalArgumentException("Unsupported environment " + zone.environment()); } } private NodeResources decideNodeResources(NodeResources target, boolean required) { if (required) return target; if (target.isUnspecified()) return target; // Cannot be modified // Dev does not cap the cpu or network of containers since usage is spotty: Allocate just a small amount exclusively if (zone.environment() == Environment.dev && !zone.getCloud().dynamicProvisioning()) target = target.withVcpu(0.1).withBandwidthGbps(0.1); // Allow slow storage in zones which are not performance sensitive if (zone.system().isCd() || zone.environment() == Environment.dev || zone.environment() == Environment.test) target = target.with(NodeResources.DiskSpeed.any).with(NodeResources.StorageType.any).withBandwidthGbps(0.1); return target; } public NodeResources defaultNodeResources(ClusterSpec clusterSpec, ApplicationId applicationId) { if (clusterSpec.type() == ClusterSpec.Type.admin) { Architecture architecture = Architecture.valueOf( ADMIN_CLUSTER_NODE_ARCHITECTURE.bindTo(flagSource) .with(APPLICATION_ID, applicationId.serializedForm()) .value()); if (clusterSpec.id().value().equals("cluster-controllers")) { return versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.25, 1.14, 10, 0.3), new Version("7.586.50"), new NodeResources(0.25, 1.333, 10, 0.3), new Version("7.586.54"), new NodeResources(0.25, 1.14, 10, 0.3))) .with(architecture); } return (zone.getCloud().dynamicProvisioning() && ! sharedHosts.apply(clusterSpec.type()) ? versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.5, 4, 50, 0.3))) : versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.5, 2, 50, 0.3)))) .with(architecture); } return zone.getCloud().dynamicProvisioning() ? versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(2.0, 8, 50, 0.3))) : versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(1.5, 8, 50, 0.3))); } /** Returns the resources for the newest version not newer than that requested in the cluster spec. */ static NodeResources versioned(ClusterSpec spec, Map<Version, NodeResources> resources) { return requireNonNull(new TreeMap<>(resources).floorEntry(spec.vespaVersion()), "no default resources applicable for " + spec + " among: " + resources) .getValue(); } /** * Returns whether the nodes requested can share physical host with other applications. * A security feature which only makes sense for prod. */ public boolean decideExclusivity(Capacity capacity, boolean requestedExclusivity) { return requestedExclusivity && (capacity.isRequired() || zone.environment() == Environment.prod); } }
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/CapacityPolicies.java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.provisioning; import com.yahoo.component.Version; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Capacity; import com.yahoo.config.provision.ClusterResources; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.flags.FlagSource; import com.yahoo.vespa.flags.PermanentFlags; import com.yahoo.vespa.hosted.provision.NodeRepository; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; import static com.yahoo.config.provision.NodeResources.Architecture; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.PermanentFlags.ADMIN_CLUSTER_NODE_ARCHITECTURE; import static java.util.Objects.requireNonNull; /** * Defines the policies for assigning cluster capacity in various environments * * @author bratseth * @see NodeResourceLimits */ public class CapacityPolicies { private final Zone zone; private final Function<ClusterSpec.Type, Boolean> sharedHosts; private final FlagSource flagSource; public CapacityPolicies(NodeRepository nodeRepository) { this.zone = nodeRepository.zone(); this.sharedHosts = type -> PermanentFlags.SHARED_HOST.bindTo(nodeRepository.flagSource()).value().isEnabled(type.name()); this.flagSource = nodeRepository.flagSource(); } public Capacity applyOn(Capacity capacity, ApplicationId application) { return capacity.withLimits(applyOn(capacity.minResources(), capacity, application), applyOn(capacity.maxResources(), capacity, application)); } private ClusterResources applyOn(ClusterResources resources, Capacity capacity, ApplicationId application) { int nodes = decideSize(resources.nodes(), capacity.isRequired(), application.instance().isTester()); int groups = Math.min(resources.groups(), nodes); // cannot have more groups than nodes var nodeResources = decideNodeResources(resources.nodeResources(), capacity.isRequired()); return new ClusterResources(nodes, groups, nodeResources); } private int decideSize(int requested, boolean required, boolean isTester) { if (isTester) return 1; if (required) return requested; switch(zone.environment()) { case dev : case test : return 1; case perf : return Math.min(requested, 3); case staging: return requested <= 1 ? requested : Math.max(2, requested / 10); case prod : return requested; default : throw new IllegalArgumentException("Unsupported environment " + zone.environment()); } } private NodeResources decideNodeResources(NodeResources target, boolean required) { if (required) return target; if (target.isUnspecified()) return target; // Cannot be modified // Dev does not cap the cpu or network of containers since usage is spotty: Allocate just a small amount exclusively if (zone.environment() == Environment.dev && !zone.getCloud().dynamicProvisioning()) target = target.withVcpu(0.1).withBandwidthGbps(0.1); // Allow slow storage in zones which are not performance sensitive if (zone.system().isCd() || zone.environment() == Environment.dev || zone.environment() == Environment.test) target = target.with(NodeResources.DiskSpeed.any).with(NodeResources.StorageType.any).withBandwidthGbps(0.1); return target; } public NodeResources defaultNodeResources(ClusterSpec clusterSpec, ApplicationId applicationId) { if (clusterSpec.type() == ClusterSpec.Type.admin) { Architecture architecture = Architecture.valueOf( ADMIN_CLUSTER_NODE_ARCHITECTURE.bindTo(flagSource) .with(APPLICATION_ID, applicationId.serializedForm()) .value()); if (clusterSpec.id().value().equals("cluster-controllers")) { return versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.25, 1.14, 10, 0.3))) .with(architecture); } return (zone.getCloud().dynamicProvisioning() && ! sharedHosts.apply(clusterSpec.type()) ? versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.5, 4, 50, 0.3))) : versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.5, 2, 50, 0.3)))) .with(architecture); } return zone.getCloud().dynamicProvisioning() ? versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(2.0, 8, 50, 0.3))) : versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(1.5, 8, 50, 0.3))); } /** Returns the resources for the newest version not newer than that requested in the cluster spec. */ static NodeResources versioned(ClusterSpec spec, Map<Version, NodeResources> resources) { return requireNonNull(new TreeMap<>(resources).floorEntry(spec.vespaVersion()), "no default resources applicable for " + spec + " among: " + resources) .getValue(); } /** * Returns whether the nodes requested can share physical host with other applications. * A security feature which only makes sense for prod. */ public boolean decideExclusivity(Capacity capacity, boolean requestedExclusivity) { return requestedExclusivity && (capacity.isRequired() || zone.environment() == Environment.prod); } }
Assign larger CC flavours between in [7.586.50, 7.586.54)
node-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/CapacityPolicies.java
Assign larger CC flavours between in [7.586.50, 7.586.54)
<ide><path>ode-repository/src/main/java/com/yahoo/vespa/hosted/provision/provisioning/CapacityPolicies.java <ide> .value()); <ide> <ide> if (clusterSpec.id().value().equals("cluster-controllers")) { <del> return versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.25, 1.14, 10, 0.3))) <add> return versioned(clusterSpec, Map.of(new Version("0"), new NodeResources(0.25, 1.14, 10, 0.3), <add> new Version("7.586.50"), new NodeResources(0.25, 1.333, 10, 0.3), <add> new Version("7.586.54"), new NodeResources(0.25, 1.14, 10, 0.3))) <ide> .with(architecture); <ide> } <ide>
JavaScript
mit
3f8d7be253e8c72fa639cc487300c912ff50f046
0
dmurtari/mbu-online,dmurtari/mbu-online,dmurtari/mbu-online
var gulp = require('gulp'); var spawn = require('child_process').spawn; var mocha = require('gulp-mocha'); var log = require('fancy-log'); var ts = require('gulp-typescript'); var tsProject = ts.createProject('./tsconfig.json'); var node; var paths = { srcJs: './src/**/*.js', srcTs: './src/**/*.ts', srcUnit: './src/**/*Spec.js', srcIntegration: './tests/**/*.js' }; gulp.task('compile', () => { return tsProject.src() .pipe(tsProject()) .js.pipe(gulp.dest('dist')); }); gulp.task('src', gulp.series(['compile'], () => { startServer(); })); gulp.task('env:dev', (done) => { process.env.PORT = 3000; process.env.NODE_ENV = 'development'; done(); }); gulp.task('env:test', (done) => { process.env.PORT = 3001; process.env.NODE_ENV = 'test'; done(); }); gulp.task('env:prod', (done) => { process.env.NODE_ENV = 'production'; done(); }); gulp.task('serve', gulp.series(['env:dev', 'src'], () => { return gulp.watch([paths.srcJs, paths.srcTs], gulp.series(['src'])); })); gulp.task('test:unit', gulp.series(['env:test'], () => { return gulp.src([paths.srcUnit]) .pipe(mocha()) .on('error', log); })); gulp.task('test:api', gulp.series(['env:test'], () => { return gulp.src([paths.srcIntegration]) .pipe(mocha({ exit: true })); })); gulp.task('test:unit:watch', gulp.series(['test:unit'], () => { return gulp.watch([paths.srcUnit, paths.srcJs], gulp.series(['test:unit'])); })); gulp.task('test:api:watch', gulp.series(['test:api'], () => { return gulp.watch([paths.srcIntegration, paths.srcJs], gulp.series(['test:api'])); })); gulp.task('default', gulp.series(['serve'])); process.on('exit', () => { if (node) { node.kill(); } }); async function startServer() { if (node) { node.kill(); } node = await spawn('node', ['./dist/app.js'], { stdio: 'inherit' }); node.on('close', function (code) { if(code === 8) { console.log('Error detected, waiting for changes...'); } }); }
gulpfile.js
var gulp = require('gulp'); var spawn = require('child_process').spawn; var mocha = require('gulp-mocha'); var log = require('fancy-log'); var ts = require("gulp-typescript"); var tsProject = ts.createProject("tsconfig.json"); var node; var paths = { srcJs: './src/**/*.js', srcTs: './src/**/*.ts', srcUnit: './src/**/*Spec.js', srcIntegration: './tests/**/*.js' }; gulp.task('compile', function() { return tsProject.src() .pipe(tsProject()) .js.pipe(gulp.dest('dist')); }); gulp.task('src', gulp.series(['compile']), function() { if (node){ node.kill(); } node = spawn('node', ['./dist/app.js'], {stdio: 'inherit'}); node.on('close', function (code) { if (code === 8) { gulp.log('Error detected, waiting for changes...'); } }); }); gulp.task('env:dev', function(done) { process.env.PORT = 3000; process.env.NODE_ENV = 'development'; done(); }); gulp.task('env:test', function(done) { process.env.PORT = 3001; process.env.NODE_ENV = 'test'; done(); }); gulp.task('env:prod', function(done) { process.env.NODE_ENV = 'production'; done(); }); gulp.task('serve', gulp.series(['env:dev', 'src'], function() { return gulp.watch([paths.srcJs, paths.srcTs], gulp.series(['src'])); })); gulp.task('test:unit', gulp.series(['env:test'], function() { return gulp.src([paths.srcUnit]) .pipe(mocha()) .on('error', log); })); gulp.task('test:api', gulp.series(['env:test'], function() { return gulp.src([paths.srcIntegration]) .pipe(mocha({ exit: true })); })); gulp.task('test:unit:watch', gulp.series(['test:unit'], function() { return gulp.watch([paths.srcUnit, paths.srcJs], gulp.series(['test:unit'])); })); gulp.task('test:api:watch', gulp.series(['test:api'], function() { return gulp.watch([paths.srcIntegration, paths.srcJs], gulp.series(['test:api'])); })); gulp.task('default', gulp.series(['serve'])); process.on('exit', function() { if (node) { node.kill(); } });
Fix gulp task
gulpfile.js
Fix gulp task
<ide><path>ulpfile.js <ide> var spawn = require('child_process').spawn; <ide> var mocha = require('gulp-mocha'); <ide> var log = require('fancy-log'); <del>var ts = require("gulp-typescript"); <del>var tsProject = ts.createProject("tsconfig.json"); <add>var ts = require('gulp-typescript'); <add>var tsProject = ts.createProject('./tsconfig.json'); <ide> <ide> var node; <ide> var paths = { <ide> srcIntegration: './tests/**/*.js' <ide> }; <ide> <del>gulp.task('compile', function() { <add>gulp.task('compile', () => { <ide> return tsProject.src() <ide> .pipe(tsProject()) <ide> .js.pipe(gulp.dest('dist')); <ide> }); <ide> <del>gulp.task('src', gulp.series(['compile']), function() { <del> if (node){ <del> node.kill(); <del> } <del> node = spawn('node', ['./dist/app.js'], {stdio: 'inherit'}); <del> node.on('close', function (code) { <del> if (code === 8) { <del> gulp.log('Error detected, waiting for changes...'); <del> } <del> }); <del>}); <add>gulp.task('src', gulp.series(['compile'], () => { <add> startServer(); <add>})); <ide> <del>gulp.task('env:dev', function(done) { <add>gulp.task('env:dev', (done) => { <ide> process.env.PORT = 3000; <ide> process.env.NODE_ENV = 'development'; <ide> done(); <ide> }); <ide> <del>gulp.task('env:test', function(done) { <add>gulp.task('env:test', (done) => { <ide> process.env.PORT = 3001; <ide> process.env.NODE_ENV = 'test'; <ide> done(); <ide> }); <ide> <ide> <del>gulp.task('env:prod', function(done) { <add>gulp.task('env:prod', (done) => { <ide> process.env.NODE_ENV = 'production'; <ide> done(); <ide> }); <ide> <del>gulp.task('serve', gulp.series(['env:dev', 'src'], function() { <add>gulp.task('serve', gulp.series(['env:dev', 'src'], () => { <ide> return gulp.watch([paths.srcJs, paths.srcTs], gulp.series(['src'])); <ide> })); <ide> <del>gulp.task('test:unit', gulp.series(['env:test'], function() { <add>gulp.task('test:unit', gulp.series(['env:test'], () => { <ide> return gulp.src([paths.srcUnit]) <ide> .pipe(mocha()) <ide> .on('error', log); <ide> })); <ide> <del>gulp.task('test:api', gulp.series(['env:test'], function() { <add>gulp.task('test:api', gulp.series(['env:test'], () => { <ide> return gulp.src([paths.srcIntegration]) <ide> .pipe(mocha({ exit: true })); <ide> })); <ide> <del>gulp.task('test:unit:watch', gulp.series(['test:unit'], function() { <add>gulp.task('test:unit:watch', gulp.series(['test:unit'], () => { <ide> return gulp.watch([paths.srcUnit, paths.srcJs], gulp.series(['test:unit'])); <ide> })); <ide> <del>gulp.task('test:api:watch', gulp.series(['test:api'], function() { <add>gulp.task('test:api:watch', gulp.series(['test:api'], () => { <ide> return gulp.watch([paths.srcIntegration, paths.srcJs], gulp.series(['test:api'])); <ide> })); <ide> <ide> gulp.task('default', gulp.series(['serve'])); <ide> <del>process.on('exit', function() { <add>process.on('exit', () => { <ide> if (node) { <ide> node.kill(); <ide> } <ide> }); <add> <add>async function startServer() { <add> if (node) { <add> node.kill(); <add> } <add> <add> node = await spawn('node', ['./dist/app.js'], { stdio: 'inherit' }); <add> <add> node.on('close', function (code) { <add> if(code === 8) { <add> console.log('Error detected, waiting for changes...'); <add> } <add> }); <add>}
JavaScript
mit
4c864671a80ca4f3257768b8f3a6a9d361b9f63c
0
cdiezmoran/AlphaStage-desktop,cdiezmoran/AlphaStage-desktop,cdiezmoran/playgrounds-desktop,cdiezmoran/playgrounds-desktop
// @flow import { combineReducers } from 'redux'; import { routerReducer as router } from 'react-router-redux'; import game from './game'; import feedback from './feedback'; import auth from './auth'; import devGame from './devGame'; import userGame from './userGame'; import download from './download'; import upload from './upload'; import type { Action } from '../actions/types'; const appReducer = combineReducers({ game, feedback, auth, devGame, userGame, download, upload, router, }); const rootReducer = (state?: Object, action: Action) => { if (action.type === 'LOGOUT_SUCCESS') { return appReducer(undefined, action); } return appReducer(state, action); }; export default rootReducer;
app/reducers/index.js
// @flow import { combineReducers } from 'redux'; import { routerReducer as router } from 'react-router-redux'; import auth from './auth'; import download from './download'; import game from './game'; import userGame from './userGame'; import type { Action } from '../actions/types'; const appReducer = combineReducers({ auth, download, game, userGame, router, }); const rootReducer = (state?: Object, action: Action) => { if (action.type === 'LOGOUT_SUCCESS') { return appReducer(undefined, action); } return appReducer(state, action); }; export default rootReducer;
Update reducers index
app/reducers/index.js
Update reducers index
<ide><path>pp/reducers/index.js <ide> // @flow <ide> import { combineReducers } from 'redux'; <ide> import { routerReducer as router } from 'react-router-redux'; <add> <add>import game from './game'; <add>import feedback from './feedback'; <ide> import auth from './auth'; <add>import devGame from './devGame'; <add>import userGame from './userGame'; <ide> import download from './download'; <del>import game from './game'; <del>import userGame from './userGame'; <add>import upload from './upload'; <ide> <ide> import type { Action } from '../actions/types'; <ide> <ide> const appReducer = combineReducers({ <add> game, <add> feedback, <ide> auth, <add> devGame, <add> userGame, <ide> download, <del> game, <del> userGame, <add> upload, <ide> router, <ide> }); <ide>
Java
apache-2.0
32262041a228e15c6db99581f22636ad1a78de4b
0
0359xiaodong/AutoCompleteBubbleText,FrederickRider/AutoCompleteBubbleText,bestwpw/AutoCompleteBubbleText,AndroidBase/AutoCompleteBubbleText
package com.mycardboarddreams.autocompletebubbletext.samplelist; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SampleEditText extends MultiSelectEditText<SampleItem> { List<SampleItem> sampleItems; public SampleEditText(Context context) { super(context); } public SampleEditText(Context context, AttributeSet attrs) { super(context, attrs); } public SampleEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void filterData(String lastCommaValue) { sampleItems = Arrays.asList( new SampleItem("Aaron LastName"), new SampleItem("Cameron Chimes"), new SampleItem("Tim Gibbons"), new SampleItem("Gary Styles") ); clearAllItems(); if(TextUtils.isEmpty(lastCommaValue)){ addAllItems(sampleItems); return; } List<SampleItem> filtered = new ArrayList<SampleItem>(); for(SampleItem item : sampleItems){ if(item.getReadableName().toLowerCase().startsWith(lastCommaValue.toLowerCase())) filtered.add(item); } addAllItems(filtered); } }
samplelist/src/main/java/com/mycardboarddreams/autocompletebubbletext/samplelist/SampleEditText.java
package com.mycardboarddreams.autocompletebubbletext.samplelist; import android.content.Context; import android.util.AttributeSet; import com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText; import java.util.Arrays; import java.util.List; public class SampleEditText extends MultiSelectEditText<SampleItem> { List<SampleItem> sampleItems; public SampleEditText(Context context) { super(context); } public SampleEditText(Context context, AttributeSet attrs) { super(context, attrs); } public SampleEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void filterData(String lastCommaValue) { sampleItems = Arrays.asList( new SampleItem("Aaron LastName"), new SampleItem("Cameron Chimes"), new SampleItem("Tim Gibbons"), new SampleItem("Gary Styles") ); clearAllItems(); addAllItems(sampleItems); } }
Added filtering to list
samplelist/src/main/java/com/mycardboarddreams/autocompletebubbletext/samplelist/SampleEditText.java
Added filtering to list
<ide><path>amplelist/src/main/java/com/mycardboarddreams/autocompletebubbletext/samplelist/SampleEditText.java <ide> package com.mycardboarddreams.autocompletebubbletext.samplelist; <ide> <ide> import android.content.Context; <add>import android.text.TextUtils; <ide> import android.util.AttributeSet; <ide> <ide> import com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText; <ide> <add>import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <ide> <ide> clearAllItems(); <ide> <del> addAllItems(sampleItems); <add> if(TextUtils.isEmpty(lastCommaValue)){ <add> addAllItems(sampleItems); <add> return; <add> } <add> <add> List<SampleItem> filtered = new ArrayList<SampleItem>(); <add> for(SampleItem item : sampleItems){ <add> if(item.getReadableName().toLowerCase().startsWith(lastCommaValue.toLowerCase())) <add> filtered.add(item); <add> } <add> <add> addAllItems(filtered); <ide> } <ide> }
Java
mit
0e10c055eb33063c4ed496641710275d7add73b2
0
jmanrocks152/SNAKEEAT
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by jmanrocks152 on 5/22/17. */ public class Main { private static int numberOfSnakes, currentQuery, largestSnakeLength = 0, numberOfPassingSnakes = 0, queries = 0; public static void main(String[] args) throws IOException { //Variable initialization BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int testCases = Integer.parseInt(reader.readLine()); for(int i = 0; i < testCases; i++) { processTestCase(reader); } } private static void processTestCase(BufferedReader reader) throws IOException { String delims = "[ ]+"; ArrayList<Integer> nqArrayList = new ArrayList<>(); ArrayList<Integer> snakeLengthsArrayList = new ArrayList<>(); ArrayList<Integer> results = new ArrayList<>(); String nqString = reader.readLine(); String[] nqArray = nqString.split(delims); String snakeLengthsString = reader.readLine(); String[] snakeLengthsArray = snakeLengthsString.split(delims); try { for (String s : nqArray) { nqArrayList.add(Integer.parseInt(s)); } queries = nqArrayList.get(1); for (String s : snakeLengthsArray) { snakeLengthsArrayList.add(Integer.parseInt(s)); } } catch (NumberFormatException e) { e.printStackTrace(); } //For loop that ensures the program only activates for as many test cases there are for(int x = 0; x < queries; x++) { currentQuery = Integer.parseInt(reader.readLine()); for(int i2 = 0; i2 < snakeLengthsArrayList.size(); i2++) { if(snakeLengthsArrayList.get(i2) >= currentQuery) { numberOfPassingSnakes++; snakeLengthsArrayList.remove(i2); } } for(int z = 0; z < snakeLengthsArrayList.size(); z++) { if(z == 0) { largestSnakeLength = snakeLengthsArrayList.get(0); } if(snakeLengthsArrayList.get(z) > largestSnakeLength) { largestSnakeLength = snakeLengthsArrayList.get(z); } if(largestSnakeLength + (snakeLengthsArrayList.size() - 1) > currentQuery) { numberOfPassingSnakes++; } } results.add(numberOfPassingSnakes); } numberOfPassingSnakes = 0; results.forEach(System.out::println); // Print out results } }
src/Main.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; /** * Created by jmanrocks152 on 5/22/17. */ public class Main { public static void main(String[] args) throws IOException { //Variable initialization BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int testCases = Integer.parseInt(reader.readLine()); String delims = "[ ]+"; int numberOfSnakes, currentQuery, largestSnakeLength = 0, numberOfPassingSnakes = 0, queries = 0; int arrayListOffset = 0; ArrayList<Integer> nqArrayList = new ArrayList<>(); ArrayList<Integer> snakeLengthsArrayList = new ArrayList<>(); ArrayList<Integer> results = new ArrayList<>(); for(int i = 0; i < testCases; i++) { String nqString = reader.readLine(); String[] nqArray = nqString.split(delims); String snakeLengthsString = reader.readLine(); String[] snakeLengthsArray = snakeLengthsString.split(delims); try { for (String s : nqArray) { nqArrayList.add(Integer.parseInt(s)); } queries = nqArrayList.get(1); for (String s : snakeLengthsArray) { snakeLengthsArrayList.add(Integer.parseInt(s)); } }catch (NumberFormatException e) { e.printStackTrace(); } //For loop that ensures the program only activates for as many test cases there are for(int x = 0; x < queries; x++) { currentQuery = Integer.parseInt(reader.readLine()); for(int i2 = 0; i2 < snakeLengthsArrayList.size(); i2++) { if(snakeLengthsArrayList.get(i2) >= currentQuery) { numberOfPassingSnakes++; snakeLengthsArrayList.remove(i2); } } for(int z = 0; z < snakeLengthsArrayList.size(); z++) { if(z == 0) { largestSnakeLength = snakeLengthsArrayList.get(0); } if(snakeLengthsArrayList.get(z) > largestSnakeLength) { largestSnakeLength = snakeLengthsArrayList.get(z); } if(largestSnakeLength + (snakeLengthsArrayList.size() - 1) > currentQuery) { numberOfPassingSnakes++; } } results.add(numberOfPassingSnakes); } arrayListOffset = 0; numberOfPassingSnakes = 0; } for(Integer i : results) { System.out.println(results.get(i)); } } }
Attempt to reorganize stuff.
src/Main.java
Attempt to reorganize stuff.
<ide><path>rc/Main.java <ide> import java.io.IOException; <ide> import java.io.InputStreamReader; <ide> import java.util.ArrayList; <add>import java.util.List; <ide> import java.util.Scanner; <ide> <ide> /** <ide> * Created by jmanrocks152 on 5/22/17. <ide> */ <ide> public class Main { <add> private static int numberOfSnakes, currentQuery, largestSnakeLength = 0, numberOfPassingSnakes = 0, queries = 0; <add> <ide> public static void main(String[] args) throws IOException { <ide> //Variable initialization <ide> BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); <ide> int testCases = Integer.parseInt(reader.readLine()); <add> <add> for(int i = 0; i < testCases; i++) { <add> processTestCase(reader); <add> } <add> } <add> <add> private static void processTestCase(BufferedReader reader) throws IOException { <ide> String delims = "[ ]+"; <del> int numberOfSnakes, currentQuery, largestSnakeLength = 0, numberOfPassingSnakes = 0, queries = 0; <del> int arrayListOffset = 0; <add> <ide> ArrayList<Integer> nqArrayList = new ArrayList<>(); <ide> ArrayList<Integer> snakeLengthsArrayList = new ArrayList<>(); <ide> ArrayList<Integer> results = new ArrayList<>(); <ide> <del> for(int i = 0; i < testCases; i++) { <del> String nqString = reader.readLine(); <del> String[] nqArray = nqString.split(delims); <del> String snakeLengthsString = reader.readLine(); <del> String[] snakeLengthsArray = snakeLengthsString.split(delims); <add> String nqString = reader.readLine(); <add> String[] nqArray = nqString.split(delims); <add> String snakeLengthsString = reader.readLine(); <add> String[] snakeLengthsArray = snakeLengthsString.split(delims); <ide> <del> try { <del> for (String s : nqArray) { <del> nqArrayList.add(Integer.parseInt(s)); <del> } <del> <del> queries = nqArrayList.get(1); <del> <del> for (String s : snakeLengthsArray) { <del> snakeLengthsArrayList.add(Integer.parseInt(s)); <del> } <del> }catch (NumberFormatException e) { <del> e.printStackTrace(); <add> try { <add> for (String s : nqArray) { <add> nqArrayList.add(Integer.parseInt(s)); <ide> } <ide> <del> //For loop that ensures the program only activates for as many test cases there are <add> queries = nqArrayList.get(1); <ide> <del> for(int x = 0; x < queries; x++) { <del> currentQuery = Integer.parseInt(reader.readLine()); <del> for(int i2 = 0; i2 < snakeLengthsArrayList.size(); i2++) { <del> if(snakeLengthsArrayList.get(i2) >= currentQuery) { <del> numberOfPassingSnakes++; <del> snakeLengthsArrayList.remove(i2); <del> } <del> } <del> for(int z = 0; z < snakeLengthsArrayList.size(); z++) { <del> if(z == 0) { <del> largestSnakeLength = snakeLengthsArrayList.get(0); <del> } <del> if(snakeLengthsArrayList.get(z) > largestSnakeLength) { <del> largestSnakeLength = snakeLengthsArrayList.get(z); <del> } <del> if(largestSnakeLength + (snakeLengthsArrayList.size() - 1) > currentQuery) { <del> numberOfPassingSnakes++; <del> } <del> } <del> results.add(numberOfPassingSnakes); <add> for (String s : snakeLengthsArray) { <add> snakeLengthsArrayList.add(Integer.parseInt(s)); <ide> } <del> arrayListOffset = 0; <del> numberOfPassingSnakes = 0; <add> } catch (NumberFormatException e) { <add> e.printStackTrace(); <ide> } <ide> <del> for(Integer i : results) { <del> System.out.println(results.get(i)); <add> //For loop that ensures the program only activates for as many test cases there are <add> <add> for(int x = 0; x < queries; x++) { <add> currentQuery = Integer.parseInt(reader.readLine()); <add> for(int i2 = 0; i2 < snakeLengthsArrayList.size(); i2++) { <add> if(snakeLengthsArrayList.get(i2) >= currentQuery) { <add> numberOfPassingSnakes++; <add> snakeLengthsArrayList.remove(i2); <add> } <add> } <add> for(int z = 0; z < snakeLengthsArrayList.size(); z++) { <add> if(z == 0) { <add> largestSnakeLength = snakeLengthsArrayList.get(0); <add> } <add> if(snakeLengthsArrayList.get(z) > largestSnakeLength) { <add> largestSnakeLength = snakeLengthsArrayList.get(z); <add> } <add> if(largestSnakeLength + (snakeLengthsArrayList.size() - 1) > currentQuery) { <add> numberOfPassingSnakes++; <add> } <add> } <add> results.add(numberOfPassingSnakes); <ide> } <add> numberOfPassingSnakes = 0; <add> <add> results.forEach(System.out::println); // Print out results <ide> } <ide> }
Java
agpl-3.0
d0a85b04636d154f6e303a2da262bfc40b775dd1
0
Levis92/proton-text
package edu.chl.proton.model; import javafx.scene.text.Text; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * @author Mickaela * Created by Mickaela on 2017-05-01. */ public class Markdown implements DocTypeInterface{ private List<String> lines = new ArrayList<String>(); private List<Parts> parts = new ArrayList<Parts>(); public Markdown(List<String> lines, List<Parts> parts){ this.lines = lines; this.parts = parts; } public Markdown(File file){ getCursor().setPosition(0,0); this.setFile(file); } public Cursor getCursor(){ return null; } public void setCursor(Cursor cursor){ } public File getFile(){ return null; } public void setFile(File file){ } public void addFile(){ } public void addParts(Parts parts){ } public void removeParts(int index){ } public void removeAllParts(){ } public void addLines(String str){ } public void removeLines(int index){ } public void removeAllLines(){ } public void save(){ } // getHTML() returns a List with the resulting HTML from the Markdown text protected List<Parts> getHTML(){ Parts part; for(String str : lines){ part = checkForMarkdown(str); parts.add(part); } return parts; } protected Parts checkForMarkdown(String str){ String tmp = checkPosture(str); tmp = checkHeading(tmp); tmp = checkLink(tmp); tmp = checkList(tmp); Parts part = new Parts(tmp); return part; } protected String checkPosture(String str){ Pattern bold; Pattern italic; Pattern boldItalic; Pattern quote; try { boldItalic = Pattern.compile("\\*{3}([\\w\\d\\W\\D]+)\\*{3}"); bold = Pattern.compile("\\*{2}([\\w\\d\\W\\D]+)\\*{2}"); italic = Pattern.compile("\\*([\\w\\d]+)\\*"); quote = Pattern.compile("\\>(?<text>[^\\>]*)\\\r"); } catch (PatternSyntaxException ex) { System.out.println("checkPosture" + ex); // remove in later version throw(ex); } // Check for italic and bold Matcher match = boldItalic.matcher(str); StringBuffer sb = new StringBuffer(); while (match.find()) { match.appendReplacement(sb, "<i><b>$1</b></i>"); } match.appendTail(sb); String tmp = sb.toString(); // check for bold match = bold.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<b>$1</b>"); } match.appendTail(sb); tmp = sb.toString(); // check for italic match = italic.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<i>$1</i>"); } match.appendTail(sb); tmp = sb.toString(); // check for quotes match = quote.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<blockquote>$1</blockquote>"); } match.appendTail(sb); tmp = sb.toString(); return tmp; } protected String checkHeading(String str){ Pattern h1; Pattern h2; Pattern h3; Pattern h4; Pattern h5; Pattern h6; try{ h1 = Pattern.compile("\\#(?<text>[^\\#]*)\\\r"); h2 = Pattern.compile("\\#{2}(?<text>[^\\#]*)\\\r"); h3 = Pattern.compile("\\#{3}(?<text>[^\\#]*)\\\r"); h4 = Pattern.compile("\\#{4}(?<text>[^\\#]*)\\\r"); h5 = Pattern.compile("\\#{5}(?<text>[^\\#]*)\\\r"); h6 = Pattern.compile("\\#{6}(?<text>[^\\#]*)\\\r"); } catch (PatternSyntaxException ex){ System.out.println("checkHeading: " + ex); // remove in later version throw(ex); } // Check for h6 Matcher match = h6.matcher(str); StringBuffer sb = new StringBuffer(); while (match.find()) { match.appendReplacement(sb, "<h6>$1</h6>"); } match.appendTail(sb); String tmp = sb.toString(); // Check for h5 match = h5.matcher(str); sb = new StringBuffer(); while (match.find()) { match.appendReplacement(sb, "<h5>$1</h5>"); } match.appendTail(sb); tmp = sb.toString(); // check for h4 match = h4.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<h4>$1</h4>"); } match.appendTail(sb); tmp = sb.toString(); // check for h3 match = h3.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<h3>$1</h3>"); } match.appendTail(sb); tmp = sb.toString(); // check for h2 match = h2.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<h2>$1</h2>"); } match.appendTail(sb); tmp = sb.toString(); // check for h1 match = h1.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<h1>$1</h1>"); } match.appendTail(sb); tmp = sb.toString(); return tmp; } protected String checkLink(String str){ Pattern textLink; Pattern picLink; try{ textLink = Pattern.compile("\\[(?<text>[^\\]]*)\\]\\((?<link>[^\\)]*)\\)"); picLink = Pattern.compile("\\!\\[(?<text>[^\\]]*)\\]\\((?<link>[^\\)]*)\\)"); } catch (PatternSyntaxException ex){ System.out.println("checkLink" + ex); // remove in later version throw(ex); } // Check for h5 Matcher match = picLink.matcher(str); StringBuffer sb = new StringBuffer(); while (match.find()) { match.appendReplacement(sb, "<img src=\"$2\" alt=\"$1\">"); } match.appendTail(sb); String tmp = sb.toString(); // check for h4 match = textLink.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<a href=\"$2\">$1</a>"); } match.appendTail(sb); tmp = sb.toString(); return tmp; } protected String checkList(String str){ Pattern unorderedList; Pattern orderedList; Pattern list; try{ orderedList = Pattern.compile("(\\d\\.\\u0020|\\d\\.|\\d{2}\\.\\u0020|\\d{2}\\.)([\\w\\d\\W\\D]+)(\\\r)"); unorderedList = Pattern.compile("(\\*\\u0020|\\*|\\-\\u0020|\\-)([\\w\\d\\W\\D]+)(\\\r)"); list = Pattern.compile("(\\d\\.\\u0020|\\d\\.|\\d{2}\\.\\u0020|\\d{2}\\.|\\*\\u0020|\\*|\\-\\u0020|\\-)((?:(?!\\d\\.|\\d{2}\\.|\\*|\\-).)*?)\\\r"); } catch (PatternSyntaxException ex){ System.out.println("checkList" + ex); // remove in later version throw(ex); } // Check for ordered list Matcher match = orderedList.matcher(str); StringBuffer sb = new StringBuffer(); while (match.find()) { match.appendReplacement(sb, "<ol>$1$2$3</ol>"); } match.appendTail(sb); String tmp = sb.toString(); // check for unordered list match = unorderedList.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<ul>$1$2$3</ul>"); } match.appendTail(sb); tmp = sb.toString(); // check for unordered list match = list.matcher(tmp); sb = new StringBuffer(); while(match.find()){ match.appendReplacement(sb, "<li>$2</li>"); } match.appendTail(sb); tmp = sb.toString(); return tmp; } // Returns a formatted List, where every list item is a row // in the document and every character gets a style. public List<Text> getText(){ List<Text> text = new ArrayList<Text>(); Text newText = new Text("Bä, bä, vita lamm, har du någon ull?\n" + "Ja, ja, lilla barn, jag har säcken full.\n" + "Helgdagsrock åt far och söndagskjol åt mor\n" + "och två par strumpor åt lille, lille bror."); text.add(newText); return text; } public void setText(){ } }
src/main/java/edu/chl/proton/model/Markdown.java
package edu.chl.proton.model; import javafx.scene.text.Text; import java.util.ArrayList; import java.util.List; /** * @author Mickaela * Created by Mickaela on 2017-05-01. */ public class Markdown extends Document{ public Markdown(){ } public Markdown(File file){ getCursor().setPosition(0,0); this.setFile(file); } // getHTML() returns a List with the resulting HTML from the Markdown text protected void getHTML(){ } // Returns a formatted List, where every list item is a row // in the document and every character gets a style. @Override protected List<Text> getText(){ List<Text> text = new ArrayList<Text>(); Text newText = new Text("Bä, bä, vita lamm, har du någon ull?\n" + "Ja, ja, lilla barn, jag har säcken full.\n" + "Helgdagsrock åt far och söndagskjol åt mor\n" + "och två par strumpor åt lille, lille bror."); text.add(newText); return text; } }
Implemented getHTML(), checkForMarkdown() and help-methods in Markdown
src/main/java/edu/chl/proton/model/Markdown.java
Implemented getHTML(), checkForMarkdown() and help-methods in Markdown
<ide><path>rc/main/java/edu/chl/proton/model/Markdown.java <ide> import javafx.scene.text.Text; <ide> import java.util.ArrayList; <ide> import java.util.List; <add>import java.util.regex.Matcher; <add>import java.util.regex.Pattern; <add>import java.util.regex.PatternSyntaxException; <ide> <ide> /** <ide> * @author Mickaela <ide> * Created by Mickaela on 2017-05-01. <ide> */ <del>public class Markdown extends Document{ <del> <del> <del> public Markdown(){ <del> <add>public class Markdown implements DocTypeInterface{ <add> <add> private List<String> lines = new ArrayList<String>(); <add> private List<Parts> parts = new ArrayList<Parts>(); <add> <add> public Markdown(List<String> lines, List<Parts> parts){ <add> this.lines = lines; <add> this.parts = parts; <ide> } <ide> <ide> public Markdown(File file){ <ide> getCursor().setPosition(0,0); <ide> this.setFile(file); <add> <add> } <add> <add> public Cursor getCursor(){ <add> return null; <add> } <add> <add> public void setCursor(Cursor cursor){ <add> <add> } <add> <add> public File getFile(){ <add> return null; <add> } <add> <add> public void setFile(File file){ <add> <add> } <add> <add> public void addFile(){ <add> <add> } <add> <add> public void addParts(Parts parts){ <add> <add> } <add> <add> public void removeParts(int index){ <add> <add> } <add> <add> public void removeAllParts(){ <add> <add> } <add> <add> public void addLines(String str){ <add> <add> } <add> <add> public void removeLines(int index){ <add> <add> } <add> <add> public void removeAllLines(){ <add> <add> } <add> <add> public void save(){ <add> <ide> } <ide> <ide> // getHTML() returns a List with the resulting HTML from the Markdown text <del> protected void getHTML(){ <del> <add> protected List<Parts> getHTML(){ <add> Parts part; <add> for(String str : lines){ <add> part = checkForMarkdown(str); <add> parts.add(part); <add> } <add> return parts; <add> } <add> <add> protected Parts checkForMarkdown(String str){ <add> String tmp = checkPosture(str); <add> tmp = checkHeading(tmp); <add> tmp = checkLink(tmp); <add> tmp = checkList(tmp); <add> Parts part = new Parts(tmp); <add> return part; <add> } <add> <add> protected String checkPosture(String str){ <add> Pattern bold; <add> Pattern italic; <add> Pattern boldItalic; <add> Pattern quote; <add> <add> try { <add> boldItalic = Pattern.compile("\\*{3}([\\w\\d\\W\\D]+)\\*{3}"); <add> bold = Pattern.compile("\\*{2}([\\w\\d\\W\\D]+)\\*{2}"); <add> italic = Pattern.compile("\\*([\\w\\d]+)\\*"); <add> quote = Pattern.compile("\\>(?<text>[^\\>]*)\\\r"); <add> } catch (PatternSyntaxException ex) { <add> System.out.println("checkPosture" + ex); // remove in later version <add> throw(ex); <add> } <add> <add> // Check for italic and bold <add> Matcher match = boldItalic.matcher(str); <add> StringBuffer sb = new StringBuffer(); <add> while (match.find()) { <add> match.appendReplacement(sb, "<i><b>$1</b></i>"); <add> } <add> match.appendTail(sb); <add> String tmp = sb.toString(); <add> <add> // check for bold <add> match = bold.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<b>$1</b>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for italic <add> match = italic.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<i>$1</i>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for quotes <add> match = quote.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<blockquote>$1</blockquote>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> return tmp; <add> } <add> <add> protected String checkHeading(String str){ <add> Pattern h1; <add> Pattern h2; <add> Pattern h3; <add> Pattern h4; <add> Pattern h5; <add> Pattern h6; <add> <add> try{ <add> h1 = Pattern.compile("\\#(?<text>[^\\#]*)\\\r"); <add> h2 = Pattern.compile("\\#{2}(?<text>[^\\#]*)\\\r"); <add> h3 = Pattern.compile("\\#{3}(?<text>[^\\#]*)\\\r"); <add> h4 = Pattern.compile("\\#{4}(?<text>[^\\#]*)\\\r"); <add> h5 = Pattern.compile("\\#{5}(?<text>[^\\#]*)\\\r"); <add> h6 = Pattern.compile("\\#{6}(?<text>[^\\#]*)\\\r"); <add> } catch (PatternSyntaxException ex){ <add> System.out.println("checkHeading: " + ex); // remove in later version <add> throw(ex); <add> } <add> <add> // Check for h6 <add> Matcher match = h6.matcher(str); <add> StringBuffer sb = new StringBuffer(); <add> while (match.find()) { <add> match.appendReplacement(sb, "<h6>$1</h6>"); <add> } <add> match.appendTail(sb); <add> String tmp = sb.toString(); <add> <add> // Check for h5 <add> match = h5.matcher(str); <add> sb = new StringBuffer(); <add> while (match.find()) { <add> match.appendReplacement(sb, "<h5>$1</h5>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for h4 <add> match = h4.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<h4>$1</h4>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for h3 <add> match = h3.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<h3>$1</h3>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for h2 <add> match = h2.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<h2>$1</h2>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for h1 <add> match = h1.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<h1>$1</h1>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> return tmp; <add> } <add> <add> protected String checkLink(String str){ <add> Pattern textLink; <add> Pattern picLink; <add> try{ <add> textLink = Pattern.compile("\\[(?<text>[^\\]]*)\\]\\((?<link>[^\\)]*)\\)"); <add> picLink = Pattern.compile("\\!\\[(?<text>[^\\]]*)\\]\\((?<link>[^\\)]*)\\)"); <add> } catch (PatternSyntaxException ex){ <add> System.out.println("checkLink" + ex); // remove in later version <add> throw(ex); <add> } <add> <add> // Check for h5 <add> Matcher match = picLink.matcher(str); <add> StringBuffer sb = new StringBuffer(); <add> while (match.find()) { <add> match.appendReplacement(sb, "<img src=\"$2\" alt=\"$1\">"); <add> } <add> match.appendTail(sb); <add> String tmp = sb.toString(); <add> <add> // check for h4 <add> match = textLink.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<a href=\"$2\">$1</a>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> return tmp; <add> } <add> <add> protected String checkList(String str){ <add> Pattern unorderedList; <add> Pattern orderedList; <add> Pattern list; <add> try{ <add> orderedList = Pattern.compile("(\\d\\.\\u0020|\\d\\.|\\d{2}\\.\\u0020|\\d{2}\\.)([\\w\\d\\W\\D]+)(\\\r)"); <add> unorderedList = Pattern.compile("(\\*\\u0020|\\*|\\-\\u0020|\\-)([\\w\\d\\W\\D]+)(\\\r)"); <add> list = Pattern.compile("(\\d\\.\\u0020|\\d\\.|\\d{2}\\.\\u0020|\\d{2}\\.|\\*\\u0020|\\*|\\-\\u0020|\\-)((?:(?!\\d\\.|\\d{2}\\.|\\*|\\-).)*?)\\\r"); <add> } catch (PatternSyntaxException ex){ <add> System.out.println("checkList" + ex); // remove in later version <add> throw(ex); <add> } <add> // Check for ordered list <add> Matcher match = orderedList.matcher(str); <add> StringBuffer sb = new StringBuffer(); <add> while (match.find()) { <add> match.appendReplacement(sb, "<ol>$1$2$3</ol>"); <add> } <add> match.appendTail(sb); <add> String tmp = sb.toString(); <add> <add> // check for unordered list <add> match = unorderedList.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<ul>$1$2$3</ul>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> <add> // check for unordered list <add> match = list.matcher(tmp); <add> sb = new StringBuffer(); <add> while(match.find()){ <add> match.appendReplacement(sb, "<li>$2</li>"); <add> } <add> match.appendTail(sb); <add> tmp = sb.toString(); <add> return tmp; <ide> } <ide> <ide> // Returns a formatted List, where every list item is a row <ide> // in the document and every character gets a style. <del> @Override <del> protected List<Text> getText(){ <add> public List<Text> getText(){ <ide> List<Text> text = new ArrayList<Text>(); <ide> Text newText = new Text("Bä, bä, vita lamm, har du någon ull?\n" + <ide> "Ja, ja, lilla barn, jag har säcken full.\n" + <ide> <ide> } <ide> <add> public void setText(){ <add> <add> } <add> <ide> }
JavaScript
mit
9b9b94aa7a47caeaf2099ac0ac19f5ef2633ab0f
0
YappyBots/YappyGitLab,YappyBots/YappyGitLab
const Collection = require('discord.js').Collection; const bot = require('../Discord/index.js'); const fs = require('fs'); const path = require('path'); const Log = require('../Util/Log'); class Events { constructor() { this.events = {}; this.eventDir = path.resolve(__dirname, './Events'); this.eventsList = new Collection(); this.bot = bot; this.setup(); } setGitlab(gitlab) { this.gitlab = gitlab; } setup() { fs.readdir(this.eventDir, (err, files) => { if (err) throw err; files.forEach(file => { let eventName = file.replace(`.js`, ``); try { let event = require(`./Events/${eventName}`); this.eventsList.set(eventName, new event(this.gitlab, this.bot)); Log.debug(`GitHub | Loading Event ${eventName.replace(`-`, `/`)} ��`); } catch (e) { Log.error(`GitHub | Loading Event ${eventName} ❌`); Log.error(e); } }); return; }); } use(data, eventName) { const action = data.object_attributes ? data.object_attributes.action : ''; const noteableType = data.object_attributes && data.object_attributes.noteable_type ? data.object_attributes.noteable_type.toLowerCase() : ''; eventName = eventName.replace(` Hook`, '').replace(/ /g, '_').toLowerCase(); let event = action || noteableType ? `${eventName}-${action || noteableType}` : eventName; try { event = this.eventsList.get(event) || this.eventsList.get('Unknown'); let text = event.text(data, eventName, action); return { embed: this.parseEmbed(event.embed(data, eventName, action), data), text: Array.isArray(text) ? text.join('\n') : text, }; } catch (e) { Log.error(e); } } parseEmbed(embed, data) { if (!embed) return null; switch (embed.color) { case 'success': embed.color = 0x3CA553; break; case 'warning': embed.color = 0xFB5432; break; case 'danger': case 'error': embed.color = 0xCE0814; break; default: if (embed.color) embed.color = typeof embed.color === 'string' ? parseInt(`0x${embed.color.replace(`0x`, ``)}`, 16) : embed.color; break; } const avatar = data.user ? data.user.avatar_url : data.user_avatar; embed.author = { name: data.user ? data.user.username : data.user_name, icon_url: avatar && avatar.startsWith('/') ? `https://gitlab.com${avatar}` : avatar, }; embed.footer = { text: data.project.path_with_namespace, }; embed.url = embed.url || (data.object_attributes && data.object_attributes.url) || (data.project && data.project.web_url); embed.timestamp = new Date(); if (embed.description) embed.description = embed.description.slice(0, 1000) + (embed.description.length > 1000 ? '...' : ''); return embed; } } module.exports = new Events();
lib/Gitlab/EventHandler.js
const Collection = require('discord.js').Collection; const bot = require('../Discord/index.js'); const fs = require('fs'); const path = require('path'); const Log = require('../Util/Log'); class Events { constructor() { this.events = {}; this.eventDir = path.resolve(__dirname, './Events'); this.eventsList = new Collection(); this.bot = bot; this.setup(); } setGitlab(gitlab) { this.gitlab = gitlab; } setup() { fs.readdir(this.eventDir, (err, files) => { if (err) throw err; files.forEach(file => { let eventName = file.replace(`.js`, ``); try { let event = require(`./Events/${eventName}`); this.eventsList.set(eventName, new event(this.gitlab, this.bot)); Log.debug(`GitHub | Loading Event ${eventName.replace(`-`, `/`)} ��`); } catch (e) { Log.error(`GitHub | Loading Event ${eventName} ❌`); Log.error(e); } }); return; }); } use(data, eventName) { const action = data.object_attributes ? data.object_attributes.action : ''; const noteableType = data.object_attributes && data.object_attributes.noteable_type ? data.object_attributes.noteable_type.toLowerCase() : ''; eventName = eventName.replace(` Hook`, '').replace(/ /g, '_').toLowerCase(); let event = action || noteableType ? `${eventName}-${action || noteableType}` : eventName; try { event = this.eventsList.get(event) || this.eventsList.get('Unknown'); let text = event.text(data, eventName, action); return { embed: this.parseEmbed(event.embed(data, eventName, action), data), text: Array.isArray(text) ? text.join('\n') : text, }; } catch (e) { Log.error(e); } } parseEmbed(embed, data) { if (!embed) return null; switch (embed.color) { case 'success': embed.color = 0x3CA553; break; case 'warning': embed.color = 0xFB5432; break; case 'danger': case 'error': embed.color = 0xCE0814; break; default: if (embed.color) embed.color = typeof embed.color === 'string' ? parseInt(`0x${embed.color.replace(`0x`, ``)}`, 16) : embed.color; break; } const avatar = data.user ? data.user.avatar_url : data.user_avatar; embed.author = { name: data.user ? data.user.username : data.user_name, icon_url: avatar && avatar.startsWith('/') ? `https://gitlab.com${avatar}` : avatar, }; embed.footer = { text: data.project.path_with_namespace, }; embed.url = embed.url || (data.object_attributes && data.object_attributes.url) || data.project.web_url; embed.timestamp = new Date(); embed.description = embed.description.slice(0, 1000) + (embed.description.length > 1000 ? '...' : ''); return embed; } } module.exports = new Events();
fix(gitlab: events): fix event handler getting property from undefined
lib/Gitlab/EventHandler.js
fix(gitlab: events): fix event handler getting property from undefined
<ide><path>ib/Gitlab/EventHandler.js <ide> embed.footer = { <ide> text: data.project.path_with_namespace, <ide> }; <del> embed.url = embed.url || (data.object_attributes && data.object_attributes.url) || data.project.web_url; <add> embed.url = embed.url || (data.object_attributes && data.object_attributes.url) || (data.project && data.project.web_url); <ide> embed.timestamp = new Date(); <ide> <del> embed.description = embed.description.slice(0, 1000) + (embed.description.length > 1000 ? '...' : ''); <add> if (embed.description) embed.description = embed.description.slice(0, 1000) + (embed.description.length > 1000 ? '...' : ''); <ide> <ide> return embed; <ide> }
Java
apache-2.0
cd715e3afcfa9454a35fcfaf96fe2aa9071bcd1b
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.ria.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @author Josh Adam <[email protected]> */ @Configuration @EnableWebMvc @ComponentScan(basePackages = { "ca.corefacility.bioinformatics.irida.ria" }) public class WebConfigurer extends WebMvcConfigurerAdapter { public static final String SPRING_PROFILE_PRODUCTION = "prod"; @Autowired private Environment env; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // CSS: default location "/static/styles" during development and production. registry.addResourceHandler("/styles/**").addResourceLocations("/static/styles/"); // Bower injects need components into the index.html. For development, // these files need to be served as is. In production these files will // be minified, concatenated, and moved into the /static/js/ folder. if (!env.acceptsProfiles(SPRING_PROFILE_PRODUCTION)) { registry.addResourceHandler("/bower_components/**").addResourceLocations("/bower_components/"); registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/"); } else { // Scripts are concatenated and minified during build process. registry.addResourceHandler("/scripts/**").addResourceLocations("/static/scripts/"); } } }
src/main/java/ca/corefacility/bioinformatics/irida/ria/config/WebConfigurer.java
package ca.corefacility.bioinformatics.irida.ria.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @author Josh Adam <[email protected]> */ @Configuration @EnableWebMvc @ComponentScan(basePackages = { "ca.corefacility.bioinformatics.irida.ria" }) public class WebConfigurer extends WebMvcConfigurerAdapter { public static final String SPRING_PROFILE_PRODUCTION = "prod"; @Autowired private Environment env; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/styles/**").addResourceLocations("/static/styles/"); registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/js/"); // Bower injects need components into the index.html. For development, // these files need to be served as is. In production these files will // be minified, concatenated, and moved into the /static/js/ folder. if (!env.acceptsProfiles(SPRING_PROFILE_PRODUCTION)) { registry.addResourceHandler("/bower_components/**").addResourceLocations("/bower_components/"); } } }
Documentation and resource handling for scripts. Scripts during development are left alone so need to be served from the scripts folder. During production they are compressed and concatenated and added to the static folder.
src/main/java/ca/corefacility/bioinformatics/irida/ria/config/WebConfigurer.java
Documentation and resource handling for scripts.
<ide><path>rc/main/java/ca/corefacility/bioinformatics/irida/ria/config/WebConfigurer.java <ide> <ide> @Override <ide> public void addResourceHandlers(ResourceHandlerRegistry registry) { <add> // CSS: default location "/static/styles" during development and production. <ide> registry.addResourceHandler("/styles/**").addResourceLocations("/static/styles/"); <del> registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/js/"); <ide> <ide> // Bower injects need components into the index.html. For development, <ide> // these files need to be served as is. In production these files will <ide> // be minified, concatenated, and moved into the /static/js/ folder. <ide> if (!env.acceptsProfiles(SPRING_PROFILE_PRODUCTION)) { <ide> registry.addResourceHandler("/bower_components/**").addResourceLocations("/bower_components/"); <add> registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/"); <add> } <add> else { <add> // Scripts are concatenated and minified during build process. <add> registry.addResourceHandler("/scripts/**").addResourceLocations("/static/scripts/"); <ide> } <ide> } <ide> }
JavaScript
mit
b3554049b5dcf0ff07ae0a119550d588ddf6ab05
0
jcoleman/ada-keyboard
include("switch.jscad"); include("keyboard.jscad"); include("csg_dependency_graph.jscad"); function getParameterDefinitions() { return [ { name: "hand", type: "choice", values: ["left", "right"], captions: ["Left hand", "Right hand"], caption: "Half to render", initial: "left", }, { name: "part", type: "choice", values: ["switchPlate", "base"], captions: ["Switch Plate", "Base"], caption: "Part to render", initial: "switchPlate", }, { name: "center", type: "checkbox", checked: "checked", caption: "Center the result", }, { name: "addCutoutForHDMIConnector", type: "checkbox", checked: "checked", caption: "Add cutout for the HDMI connector (to connect the other half)", }, { name: "addCutoutForUSBConnector", type: "checkbox", checked: "checked", caption: "Add cutout for the USB connector", }, { name: "displayKeyCapsForDebugging", type: "checkbox", checked: "", caption: "Display key caps to debug for overlapping caps", }, { name: "displayDebuggingCoordinateLabels", type: "checkbox", checked: "", caption: "Display +/- X/Y coordinate labels for debugging purposes", }, ]; } function main(params) { include("extensions/csg.js"); var plateParams = {}; var plateParamNames = [ "displayKeyCapsForDebugging", "addCutoutForHDMIConnector", "addCutoutForUSBConnector", ]; for (var i = 0; i < plateParamNames.length; ++i) { plateParams[plateParamNames[i]] = params[plateParamNames[i]]; } var keyboard = new Keyboard(plateParams); var result = keyboard.buildCSG(); if (params.hand == "right") { result = result.mirroredX(); } if (params.center) { result = result.center('x', 'y'); } if (params.displayDebuggingCoordinateLabels) { var textVectors = [ vector_text(-130, 0, "-x"), vector_text(0, -100, "-y"), vector_text(90, 0, "x"), vector_text(0, 100, "y"), ]; for (var h = 0; h < textVectors.length; ++h) { for (var i = 0; i < textVectors[h].length; ++i) { result = result.union( rectangular_extrude(textVectors[h][i], {w: 2, h: 1}) ) } } } return result; }
case/main.jscad
include("switch.jscad"); include("keyboard.jscad"); include("csg_dependency_graph.jscad"); function getParameterDefinitions() { return [ { name: "hand", type: "choice", values: ["left", "right"], captions: ["Left hand", "Right hand"], caption: "Half to render", initial: "left", }, { name: "part", type: "choice", values: ["switchPlate", "base"], captions: ["Switch Plate", "Base"], caption: "Part to render", initial: "switchPlate", }, { name: "center", type: "checkbox", checked: "checked", caption: "Center the result", }, { name: "addCutoutForHDMIConnector", type: "checkbox", checked: "checked", caption: "Add cutout for the HDMI connector (to connect the other half)", }, { name: "addCutoutForUSBConnector", type: "checkbox", checked: "checked", caption: "Add cutout for the USB connector", }, { name: "displayKeyCapsForDebugging", type: "checkbox", checked: "", caption: "Display key caps to debug for overlapping caps", }, { name: "displayDebuggingCoordinateLabels", type: "checkbox", checked: "", caption: "Display +/- X/Y coordinate labels for debugging purposes", }, ]; } function main(params) { include("csg.js"); var plateParams = {}; var plateParamNames = [ "displayKeyCapsForDebugging", "addCutoutForHDMIConnector", "addCutoutForUSBConnector", ]; for (var i = 0; i < plateParamNames.length; ++i) { plateParams[plateParamNames[i]] = params[plateParamNames[i]]; } var keyboard = new Keyboard(plateParams); var result = keyboard.buildCSG(); if (params.hand == "right") { result = result.mirroredX(); } if (params.center) { result = result.center('x', 'y'); } if (params.displayDebuggingCoordinateLabels) { var textVectors = [ vector_text(-130, 0, "-x"), vector_text(0, -100, "-y"), vector_text(90, 0, "x"), vector_text(0, 100, "y"), ]; for (var h = 0; h < textVectors.length; ++h) { for (var i = 0; i < textVectors[h].length; ++i) { result = result.union( rectangular_extrude(textVectors[h][i], {w: 2, h: 1}) ) } } } return result; }
Use relative links for include paths.
case/main.jscad
Use relative links for include paths.
<ide><path>ase/main.jscad <ide> } <ide> <ide> function main(params) { <del> include("csg.js"); <add> include("extensions/csg.js"); <ide> <ide> var plateParams = {}; <ide> var plateParamNames = [
Java
epl-1.0
c456d1c918a90a72dba632019cbc6a66e714c1ab
0
Itema-as/eclipse-marketplace-server,Itema-as/dawn-marketplace-server,belkassaby/dawn-marketplace-server,Itema-as/dawn-marketplace-server,belkassaby/dawn-marketplace-server,belkassaby/dawn-marketplace-server,belkassaby/dawn-marketplace-server,Itema-as/dawn-marketplace-server,Itema-as/eclipse-marketplace-server,Itema-as/eclipse-marketplace-server
/** */ package org.dawnsci.marketplace.impl; import javax.xml.bind.annotation.XmlRootElement; import org.dawnsci.marketplace.Categories; import org.dawnsci.marketplace.Ius; import org.dawnsci.marketplace.Marketplace; import org.dawnsci.marketplace.MarketplacePackage; import org.dawnsci.marketplace.Node; import org.dawnsci.marketplace.Platforms; import org.dawnsci.marketplace.Tags; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; /** * <!-- begin-user-doc --> An implementation of the model object ' * <em><b>Node</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getId <em>Id</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getName <em>Name</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getType <em>Type</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getCategories <em>Categories</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getTags <em>Tags</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getOwner <em>Owner</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getFavorited <em>Favorited</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getInstallstotal <em>Installstotal</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getInstallsrecent <em>Installsrecent</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getShortdescription <em>Shortdescription</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getBody <em>Body</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getCreated <em>Created</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getChanged <em>Changed</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getFoundationmember <em>Foundationmember</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getHomepageurl <em>Homepageurl</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getImage <em>Image</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getLicense <em>License</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getCompanyname <em>Companyname</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getStatus <em>Status</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getSupporturl <em>Supporturl</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getVersion <em>Version</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getEclipseversion <em>Eclipseversion</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getUpdateurl <em>Updateurl</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getIus <em>Ius</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getPlatforms <em>Platforms</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getUrl <em>Url</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getScreenshot <em>Screenshot</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getRawBody <em>Raw Body</em>}</li> * </ul> * * @generated */ @XmlRootElement(name = "Node") public class NodeImpl extends MinimalEObjectImpl.Container implements Node { /** * The default value of the '{@link #getId() <em>Id</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getId() * @generated * @ordered */ protected static final Long ID_EDEFAULT = null; /** * The cached value of the '{@link #getId() <em>Id</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getId() * @generated * @ordered */ protected Long id = ID_EDEFAULT; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected static final String TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected String type = TYPE_EDEFAULT; /** * The cached value of the '{@link #getCategories() <em>Categories</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCategories() * @generated * @ordered */ protected Categories categories; /** * The cached value of the '{@link #getTags() <em>Tags</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTags() * @generated * @ordered */ protected Tags tags; /** * The default value of the '{@link #getOwner() <em>Owner</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getOwner() * @generated * @ordered */ protected static final String OWNER_EDEFAULT = null; /** * The cached value of the '{@link #getOwner() <em>Owner</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getOwner() * @generated * @ordered */ protected String owner = OWNER_EDEFAULT; /** * The default value of the '{@link #getFavorited() <em>Favorited</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getFavorited() * @generated * @ordered */ protected static final Integer FAVORITED_EDEFAULT = null; /** * The cached value of the '{@link #getFavorited() <em>Favorited</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getFavorited() * @generated * @ordered */ protected Integer favorited = FAVORITED_EDEFAULT; /** * The default value of the '{@link #getInstallstotal() <em>Installstotal</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallstotal() * @generated * @ordered */ protected static final Integer INSTALLSTOTAL_EDEFAULT = null; /** * The cached value of the '{@link #getInstallstotal() <em>Installstotal</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallstotal() * @generated * @ordered */ protected Integer installstotal = INSTALLSTOTAL_EDEFAULT; /** * The default value of the '{@link #getInstallsrecent() <em>Installsrecent</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallsrecent() * @generated * @ordered */ protected static final Integer INSTALLSRECENT_EDEFAULT = null; /** * The cached value of the '{@link #getInstallsrecent() <em>Installsrecent</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallsrecent() * @generated * @ordered */ protected Integer installsrecent = INSTALLSRECENT_EDEFAULT; /** * The default value of the '{@link #getShortdescription() <em>Shortdescription</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getShortdescription() * @generated * @ordered */ protected static final String SHORTDESCRIPTION_EDEFAULT = null; /** * The cached value of the '{@link #getShortdescription() <em>Shortdescription</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getShortdescription() * @generated * @ordered */ protected String shortdescription = SHORTDESCRIPTION_EDEFAULT; /** * The default value of the '{@link #getBody() <em>Body</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getBody() * @generated * @ordered */ protected static final String BODY_EDEFAULT = null; /** * The cached value of the '{@link #getBody() <em>Body</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getBody() * @generated * @ordered */ protected String body = BODY_EDEFAULT; /** * The default value of the '{@link #getCreated() <em>Created</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCreated() * @generated * @ordered */ protected static final Long CREATED_EDEFAULT = null; /** * The cached value of the '{@link #getCreated() <em>Created</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCreated() * @generated * @ordered */ protected Long created = CREATED_EDEFAULT; /** * The default value of the '{@link #getChanged() <em>Changed</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getChanged() * @generated * @ordered */ protected static final Long CHANGED_EDEFAULT = null; /** * The cached value of the '{@link #getChanged() <em>Changed</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getChanged() * @generated * @ordered */ protected Long changed = CHANGED_EDEFAULT; /** * The default value of the '{@link #getFoundationmember() <em>Foundationmember</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getFoundationmember() * @generated * @ordered */ protected static final Integer FOUNDATIONMEMBER_EDEFAULT = null; /** * The cached value of the '{@link #getFoundationmember() <em>Foundationmember</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getFoundationmember() * @generated * @ordered */ protected Integer foundationmember = FOUNDATIONMEMBER_EDEFAULT; /** * The default value of the '{@link #getHomepageurl() <em>Homepageurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getHomepageurl() * @generated * @ordered */ protected static final String HOMEPAGEURL_EDEFAULT = null; /** * The cached value of the '{@link #getHomepageurl() <em>Homepageurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getHomepageurl() * @generated * @ordered */ protected String homepageurl = HOMEPAGEURL_EDEFAULT; /** * The default value of the '{@link #getImage() <em>Image</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getImage() * @generated * @ordered */ protected static final String IMAGE_EDEFAULT = null; /** * The cached value of the '{@link #getImage() <em>Image</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getImage() * @generated * @ordered */ protected String image = IMAGE_EDEFAULT; /** * The default value of the '{@link #getLicense() <em>License</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getLicense() * @generated * @ordered */ protected static final String LICENSE_EDEFAULT = null; /** * The cached value of the '{@link #getLicense() <em>License</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getLicense() * @generated * @ordered */ protected String license = LICENSE_EDEFAULT; /** * The default value of the '{@link #getCompanyname() <em>Companyname</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCompanyname() * @generated * @ordered */ protected static final String COMPANYNAME_EDEFAULT = null; /** * The cached value of the '{@link #getCompanyname() <em>Companyname</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCompanyname() * @generated * @ordered */ protected String companyname = COMPANYNAME_EDEFAULT; /** * The default value of the '{@link #getStatus() <em>Status</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected static final String STATUS_EDEFAULT = null; /** * The cached value of the '{@link #getStatus() <em>Status</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected String status = STATUS_EDEFAULT; /** * The default value of the '{@link #getSupporturl() <em>Supporturl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getSupporturl() * @generated * @ordered */ protected static final String SUPPORTURL_EDEFAULT = null; /** * The cached value of the '{@link #getSupporturl() <em>Supporturl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getSupporturl() * @generated * @ordered */ protected String supporturl = SUPPORTURL_EDEFAULT; /** * The default value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected static final String VERSION_EDEFAULT = null; /** * The cached value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected String version = VERSION_EDEFAULT; /** * The default value of the '{@link #getEclipseversion() <em>Eclipseversion</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getEclipseversion() * @generated * @ordered */ protected static final String ECLIPSEVERSION_EDEFAULT = null; /** * The cached value of the '{@link #getEclipseversion() <em>Eclipseversion</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getEclipseversion() * @generated * @ordered */ protected String eclipseversion = ECLIPSEVERSION_EDEFAULT; /** * The default value of the '{@link #getUpdateurl() <em>Updateurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getUpdateurl() * @generated * @ordered */ protected static final String UPDATEURL_EDEFAULT = null; /** * The cached value of the '{@link #getUpdateurl() <em>Updateurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getUpdateurl() * @generated * @ordered */ protected String updateurl = UPDATEURL_EDEFAULT; /** * The cached value of the '{@link #getIus() <em>Ius</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getIus() * @generated * @ordered */ protected Ius ius; /** * The cached value of the '{@link #getPlatforms() <em>Platforms</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getPlatforms() * @generated * @ordered */ protected Platforms platforms; /** * The default value of the '{@link #getUrl() <em>Url</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getUrl() * @generated * @ordered */ protected static final String URL_EDEFAULT = ""; /** * The default value of the '{@link #getScreenshot() <em>Screenshot</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getScreenshot() * @generated * @ordered */ protected static final String SCREENSHOT_EDEFAULT = null; /** * The cached value of the '{@link #getScreenshot() <em>Screenshot</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getScreenshot() * @generated * @ordered */ protected String screenshot = SCREENSHOT_EDEFAULT; /** * The default value of the '{@link #getRawBody() <em>Raw Body</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRawBody() * @generated * @ordered */ protected static final String RAW_BODY_EDEFAULT = null; /** * The cached value of the '{@link #getRawBody() <em>Raw Body</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRawBody() * @generated * @ordered */ protected String rawBody = RAW_BODY_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected NodeImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MarketplacePackage.Literals.NODE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Long getId() { return id; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setId(Long newId) { Long oldId = id; id = newId; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__ID, oldId, id)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getFavorited() { return favorited; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFavorited(Integer newFavorited) { Integer oldFavorited = favorited; favorited = newFavorited; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__FAVORITED, oldFavorited, favorited)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getInstallstotal() { return installstotal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInstallstotal(Integer newInstallstotal) { Integer oldInstallstotal = installstotal; installstotal = newInstallstotal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__INSTALLSTOTAL, oldInstallstotal, installstotal)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getInstallsrecent() { return installsrecent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInstallsrecent(Integer newInstallsrecent) { Integer oldInstallsrecent = installsrecent; installsrecent = newInstallsrecent; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__INSTALLSRECENT, oldInstallsrecent, installsrecent)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getShortdescription() { return shortdescription; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setShortdescription(String newShortdescription) { String oldShortdescription = shortdescription; shortdescription = newShortdescription; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__SHORTDESCRIPTION, oldShortdescription, shortdescription)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getBody() { return body; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setBody(String newBody) { String oldBody = body; body = newBody; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__BODY, oldBody, body)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Long getCreated() { return created; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCreated(Long newCreated) { Long oldCreated = created; created = newCreated; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CREATED, oldCreated, created)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Long getChanged() { return changed; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setChanged(Long newChanged) { Long oldChanged = changed; changed = newChanged; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CHANGED, oldChanged, changed)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getFoundationmember() { return foundationmember; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFoundationmember(Integer newFoundationmember) { Integer oldFoundationmember = foundationmember; foundationmember = newFoundationmember; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__FOUNDATIONMEMBER, oldFoundationmember, foundationmember)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getHomepageurl() { return homepageurl; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setHomepageurl(String newHomepageurl) { String oldHomepageurl = homepageurl; homepageurl = newHomepageurl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__HOMEPAGEURL, oldHomepageurl, homepageurl)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public String getImage() { if (image == null || image.isEmpty()) { return null; } if (getBaseUrl() == null) { return image; } return getBaseUrl()+"/files/" + getId() + "/" + image; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setImage(String newImage) { String oldImage = image; image = newImage; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__IMAGE, oldImage, image)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getLicense() { return license; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setLicense(String newLicense) { String oldLicense = license; license = newLicense; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__LICENSE, oldLicense, license)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getCompanyname() { return companyname; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCompanyname(String newCompanyname) { String oldCompanyname = companyname; companyname = newCompanyname; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__COMPANYNAME, oldCompanyname, companyname)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getStatus() { return status; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setStatus(String newStatus) { String oldStatus = status; status = newStatus; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__STATUS, oldStatus, status)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getSupporturl() { return supporturl; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setSupporturl(String newSupporturl) { String oldSupporturl = supporturl; supporturl = newSupporturl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__SUPPORTURL, oldSupporturl, supporturl)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getVersion() { return version; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setVersion(String newVersion) { String oldVersion = version; version = newVersion; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__VERSION, oldVersion, version)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getEclipseversion() { return eclipseversion; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setEclipseversion(String newEclipseversion) { String oldEclipseversion = eclipseversion; eclipseversion = newEclipseversion; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__ECLIPSEVERSION, oldEclipseversion, eclipseversion)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated Not */ public String getUpdateurl() { if (getBaseUrl() == null) { return updateurl; } return getBaseUrl()+"/files/" + getId() + "/" + updateurl; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setUpdateurl(String newUpdateurl) { String oldUpdateurl = updateurl; updateurl = newUpdateurl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__UPDATEURL, oldUpdateurl, updateurl)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Ius getIus() { return ius; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetIus(Ius newIus, NotificationChain msgs) { Ius oldIus = ius; ius = newIus; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__IUS, oldIus, newIus); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setIus(Ius newIus) { if (newIus != ius) { NotificationChain msgs = null; if (ius != null) msgs = ((InternalEObject)ius).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__IUS, null, msgs); if (newIus != null) msgs = ((InternalEObject)newIus).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__IUS, null, msgs); msgs = basicSetIus(newIus, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__IUS, newIus, newIus)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Platforms getPlatforms() { return platforms; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetPlatforms(Platforms newPlatforms, NotificationChain msgs) { Platforms oldPlatforms = platforms; platforms = newPlatforms; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__PLATFORMS, oldPlatforms, newPlatforms); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setPlatforms(Platforms newPlatforms) { if (newPlatforms != platforms) { NotificationChain msgs = null; if (platforms != null) msgs = ((InternalEObject)platforms).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__PLATFORMS, null, msgs); if (newPlatforms != null) msgs = ((InternalEObject)newPlatforms).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__PLATFORMS, null, msgs); msgs = basicSetPlatforms(newPlatforms, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__PLATFORMS, newPlatforms, newPlatforms)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public String getUrl() { if (getBaseUrl() == null) { return ""; } return getBaseUrl() + "/content/" + getId(); } /** * Used to calculate the base URL of URL's relative to the marketplace * server. This can only be found if this instance is contained within an * object which root container is a Marketplace instance. * * @return the base URL or <code>null</code> */ private String getBaseUrl() { EObject rootContainer = EcoreUtil.getRootContainer(this); if (rootContainer != null && rootContainer instanceof Marketplace) { String baseUrl = ((Marketplace) rootContainer).getBaseUrl(); if (baseUrl != null) { return baseUrl; } } return null; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public void setUrl(String newUrl) { } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public String getScreenshot() { if (screenshot == null || screenshot.isEmpty()) { return null; } if (getBaseUrl() == null) { return screenshot; } return getBaseUrl()+"/files/" + getId() + "/" + screenshot; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setScreenshot(String newScreenshot) { String oldScreenshot = screenshot; screenshot = newScreenshot; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__SCREENSHOT, oldScreenshot, screenshot)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getRawBody() { return rawBody; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRawBody(String newRawBody) { String oldRawBody = rawBody; rawBody = newRawBody; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__RAW_BODY, oldRawBody, rawBody)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MarketplacePackage.NODE__CATEGORIES: return basicSetCategories(null, msgs); case MarketplacePackage.NODE__TAGS: return basicSetTags(null, msgs); case MarketplacePackage.NODE__IUS: return basicSetIus(null, msgs); case MarketplacePackage.NODE__PLATFORMS: return basicSetPlatforms(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getType() { return type; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setType(String newType) { String oldType = type; type = newType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__TYPE, oldType, type)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Categories getCategories() { return categories; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCategories(Categories newCategories, NotificationChain msgs) { Categories oldCategories = categories; categories = newCategories; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CATEGORIES, oldCategories, newCategories); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCategories(Categories newCategories) { if (newCategories != categories) { NotificationChain msgs = null; if (categories != null) msgs = ((InternalEObject)categories).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__CATEGORIES, null, msgs); if (newCategories != null) msgs = ((InternalEObject)newCategories).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__CATEGORIES, null, msgs); msgs = basicSetCategories(newCategories, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CATEGORIES, newCategories, newCategories)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Tags getTags() { return tags; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTags(Tags newTags, NotificationChain msgs) { Tags oldTags = tags; tags = newTags; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__TAGS, oldTags, newTags); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setTags(Tags newTags) { if (newTags != tags) { NotificationChain msgs = null; if (tags != null) msgs = ((InternalEObject)tags).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__TAGS, null, msgs); if (newTags != null) msgs = ((InternalEObject)newTags).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__TAGS, null, msgs); msgs = basicSetTags(newTags, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__TAGS, newTags, newTags)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getOwner() { return owner; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setOwner(String newOwner) { String oldOwner = owner; owner = newOwner; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__OWNER, oldOwner, owner)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MarketplacePackage.NODE__ID: return getId(); case MarketplacePackage.NODE__NAME: return getName(); case MarketplacePackage.NODE__TYPE: return getType(); case MarketplacePackage.NODE__CATEGORIES: return getCategories(); case MarketplacePackage.NODE__TAGS: return getTags(); case MarketplacePackage.NODE__OWNER: return getOwner(); case MarketplacePackage.NODE__FAVORITED: return getFavorited(); case MarketplacePackage.NODE__INSTALLSTOTAL: return getInstallstotal(); case MarketplacePackage.NODE__INSTALLSRECENT: return getInstallsrecent(); case MarketplacePackage.NODE__SHORTDESCRIPTION: return getShortdescription(); case MarketplacePackage.NODE__BODY: return getBody(); case MarketplacePackage.NODE__CREATED: return getCreated(); case MarketplacePackage.NODE__CHANGED: return getChanged(); case MarketplacePackage.NODE__FOUNDATIONMEMBER: return getFoundationmember(); case MarketplacePackage.NODE__HOMEPAGEURL: return getHomepageurl(); case MarketplacePackage.NODE__IMAGE: return getImage(); case MarketplacePackage.NODE__LICENSE: return getLicense(); case MarketplacePackage.NODE__COMPANYNAME: return getCompanyname(); case MarketplacePackage.NODE__STATUS: return getStatus(); case MarketplacePackage.NODE__SUPPORTURL: return getSupporturl(); case MarketplacePackage.NODE__VERSION: return getVersion(); case MarketplacePackage.NODE__ECLIPSEVERSION: return getEclipseversion(); case MarketplacePackage.NODE__UPDATEURL: return getUpdateurl(); case MarketplacePackage.NODE__IUS: return getIus(); case MarketplacePackage.NODE__PLATFORMS: return getPlatforms(); case MarketplacePackage.NODE__URL: return getUrl(); case MarketplacePackage.NODE__SCREENSHOT: return getScreenshot(); case MarketplacePackage.NODE__RAW_BODY: return getRawBody(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MarketplacePackage.NODE__ID: setId((Long)newValue); return; case MarketplacePackage.NODE__NAME: setName((String)newValue); return; case MarketplacePackage.NODE__TYPE: setType((String)newValue); return; case MarketplacePackage.NODE__CATEGORIES: setCategories((Categories)newValue); return; case MarketplacePackage.NODE__TAGS: setTags((Tags)newValue); return; case MarketplacePackage.NODE__OWNER: setOwner((String)newValue); return; case MarketplacePackage.NODE__FAVORITED: setFavorited((Integer)newValue); return; case MarketplacePackage.NODE__INSTALLSTOTAL: setInstallstotal((Integer)newValue); return; case MarketplacePackage.NODE__INSTALLSRECENT: setInstallsrecent((Integer)newValue); return; case MarketplacePackage.NODE__SHORTDESCRIPTION: setShortdescription((String)newValue); return; case MarketplacePackage.NODE__BODY: setBody((String)newValue); return; case MarketplacePackage.NODE__CREATED: setCreated((Long)newValue); return; case MarketplacePackage.NODE__CHANGED: setChanged((Long)newValue); return; case MarketplacePackage.NODE__FOUNDATIONMEMBER: setFoundationmember((Integer)newValue); return; case MarketplacePackage.NODE__HOMEPAGEURL: setHomepageurl((String)newValue); return; case MarketplacePackage.NODE__IMAGE: setImage((String)newValue); return; case MarketplacePackage.NODE__LICENSE: setLicense((String)newValue); return; case MarketplacePackage.NODE__COMPANYNAME: setCompanyname((String)newValue); return; case MarketplacePackage.NODE__STATUS: setStatus((String)newValue); return; case MarketplacePackage.NODE__SUPPORTURL: setSupporturl((String)newValue); return; case MarketplacePackage.NODE__VERSION: setVersion((String)newValue); return; case MarketplacePackage.NODE__ECLIPSEVERSION: setEclipseversion((String)newValue); return; case MarketplacePackage.NODE__UPDATEURL: setUpdateurl((String)newValue); return; case MarketplacePackage.NODE__IUS: setIus((Ius)newValue); return; case MarketplacePackage.NODE__PLATFORMS: setPlatforms((Platforms)newValue); return; case MarketplacePackage.NODE__URL: setUrl((String)newValue); return; case MarketplacePackage.NODE__SCREENSHOT: setScreenshot((String)newValue); return; case MarketplacePackage.NODE__RAW_BODY: setRawBody((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MarketplacePackage.NODE__ID: setId(ID_EDEFAULT); return; case MarketplacePackage.NODE__NAME: setName(NAME_EDEFAULT); return; case MarketplacePackage.NODE__TYPE: setType(TYPE_EDEFAULT); return; case MarketplacePackage.NODE__CATEGORIES: setCategories((Categories)null); return; case MarketplacePackage.NODE__TAGS: setTags((Tags)null); return; case MarketplacePackage.NODE__OWNER: setOwner(OWNER_EDEFAULT); return; case MarketplacePackage.NODE__FAVORITED: setFavorited(FAVORITED_EDEFAULT); return; case MarketplacePackage.NODE__INSTALLSTOTAL: setInstallstotal(INSTALLSTOTAL_EDEFAULT); return; case MarketplacePackage.NODE__INSTALLSRECENT: setInstallsrecent(INSTALLSRECENT_EDEFAULT); return; case MarketplacePackage.NODE__SHORTDESCRIPTION: setShortdescription(SHORTDESCRIPTION_EDEFAULT); return; case MarketplacePackage.NODE__BODY: setBody(BODY_EDEFAULT); return; case MarketplacePackage.NODE__CREATED: setCreated(CREATED_EDEFAULT); return; case MarketplacePackage.NODE__CHANGED: setChanged(CHANGED_EDEFAULT); return; case MarketplacePackage.NODE__FOUNDATIONMEMBER: setFoundationmember(FOUNDATIONMEMBER_EDEFAULT); return; case MarketplacePackage.NODE__HOMEPAGEURL: setHomepageurl(HOMEPAGEURL_EDEFAULT); return; case MarketplacePackage.NODE__IMAGE: setImage(IMAGE_EDEFAULT); return; case MarketplacePackage.NODE__LICENSE: setLicense(LICENSE_EDEFAULT); return; case MarketplacePackage.NODE__COMPANYNAME: setCompanyname(COMPANYNAME_EDEFAULT); return; case MarketplacePackage.NODE__STATUS: setStatus(STATUS_EDEFAULT); return; case MarketplacePackage.NODE__SUPPORTURL: setSupporturl(SUPPORTURL_EDEFAULT); return; case MarketplacePackage.NODE__VERSION: setVersion(VERSION_EDEFAULT); return; case MarketplacePackage.NODE__ECLIPSEVERSION: setEclipseversion(ECLIPSEVERSION_EDEFAULT); return; case MarketplacePackage.NODE__UPDATEURL: setUpdateurl(UPDATEURL_EDEFAULT); return; case MarketplacePackage.NODE__IUS: setIus((Ius)null); return; case MarketplacePackage.NODE__PLATFORMS: setPlatforms((Platforms)null); return; case MarketplacePackage.NODE__URL: setUrl(URL_EDEFAULT); return; case MarketplacePackage.NODE__SCREENSHOT: setScreenshot(SCREENSHOT_EDEFAULT); return; case MarketplacePackage.NODE__RAW_BODY: setRawBody(RAW_BODY_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MarketplacePackage.NODE__ID: return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id); case MarketplacePackage.NODE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case MarketplacePackage.NODE__TYPE: return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type); case MarketplacePackage.NODE__CATEGORIES: return categories != null; case MarketplacePackage.NODE__TAGS: return tags != null; case MarketplacePackage.NODE__OWNER: return OWNER_EDEFAULT == null ? owner != null : !OWNER_EDEFAULT.equals(owner); case MarketplacePackage.NODE__FAVORITED: return FAVORITED_EDEFAULT == null ? favorited != null : !FAVORITED_EDEFAULT.equals(favorited); case MarketplacePackage.NODE__INSTALLSTOTAL: return INSTALLSTOTAL_EDEFAULT == null ? installstotal != null : !INSTALLSTOTAL_EDEFAULT.equals(installstotal); case MarketplacePackage.NODE__INSTALLSRECENT: return INSTALLSRECENT_EDEFAULT == null ? installsrecent != null : !INSTALLSRECENT_EDEFAULT.equals(installsrecent); case MarketplacePackage.NODE__SHORTDESCRIPTION: return SHORTDESCRIPTION_EDEFAULT == null ? shortdescription != null : !SHORTDESCRIPTION_EDEFAULT.equals(shortdescription); case MarketplacePackage.NODE__BODY: return BODY_EDEFAULT == null ? body != null : !BODY_EDEFAULT.equals(body); case MarketplacePackage.NODE__CREATED: return CREATED_EDEFAULT == null ? created != null : !CREATED_EDEFAULT.equals(created); case MarketplacePackage.NODE__CHANGED: return CHANGED_EDEFAULT == null ? changed != null : !CHANGED_EDEFAULT.equals(changed); case MarketplacePackage.NODE__FOUNDATIONMEMBER: return FOUNDATIONMEMBER_EDEFAULT == null ? foundationmember != null : !FOUNDATIONMEMBER_EDEFAULT.equals(foundationmember); case MarketplacePackage.NODE__HOMEPAGEURL: return HOMEPAGEURL_EDEFAULT == null ? homepageurl != null : !HOMEPAGEURL_EDEFAULT.equals(homepageurl); case MarketplacePackage.NODE__IMAGE: return IMAGE_EDEFAULT == null ? image != null : !IMAGE_EDEFAULT.equals(image); case MarketplacePackage.NODE__LICENSE: return LICENSE_EDEFAULT == null ? license != null : !LICENSE_EDEFAULT.equals(license); case MarketplacePackage.NODE__COMPANYNAME: return COMPANYNAME_EDEFAULT == null ? companyname != null : !COMPANYNAME_EDEFAULT.equals(companyname); case MarketplacePackage.NODE__STATUS: return STATUS_EDEFAULT == null ? status != null : !STATUS_EDEFAULT.equals(status); case MarketplacePackage.NODE__SUPPORTURL: return SUPPORTURL_EDEFAULT == null ? supporturl != null : !SUPPORTURL_EDEFAULT.equals(supporturl); case MarketplacePackage.NODE__VERSION: return VERSION_EDEFAULT == null ? version != null : !VERSION_EDEFAULT.equals(version); case MarketplacePackage.NODE__ECLIPSEVERSION: return ECLIPSEVERSION_EDEFAULT == null ? eclipseversion != null : !ECLIPSEVERSION_EDEFAULT.equals(eclipseversion); case MarketplacePackage.NODE__UPDATEURL: return UPDATEURL_EDEFAULT == null ? updateurl != null : !UPDATEURL_EDEFAULT.equals(updateurl); case MarketplacePackage.NODE__IUS: return ius != null; case MarketplacePackage.NODE__PLATFORMS: return platforms != null; case MarketplacePackage.NODE__URL: return URL_EDEFAULT == null ? getUrl() != null : !URL_EDEFAULT.equals(getUrl()); case MarketplacePackage.NODE__SCREENSHOT: return SCREENSHOT_EDEFAULT == null ? screenshot != null : !SCREENSHOT_EDEFAULT.equals(screenshot); case MarketplacePackage.NODE__RAW_BODY: return RAW_BODY_EDEFAULT == null ? rawBody != null : !RAW_BODY_EDEFAULT.equals(rawBody); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (id: "); result.append(id); result.append(", name: "); result.append(name); result.append(", type: "); result.append(type); result.append(", owner: "); result.append(owner); result.append(", favorited: "); result.append(favorited); result.append(", installstotal: "); result.append(installstotal); result.append(", installsrecent: "); result.append(installsrecent); result.append(", shortdescription: "); result.append(shortdescription); result.append(", body: "); result.append(body); result.append(", created: "); result.append(created); result.append(", changed: "); result.append(changed); result.append(", foundationmember: "); result.append(foundationmember); result.append(", homepageurl: "); result.append(homepageurl); result.append(", image: "); result.append(image); result.append(", license: "); result.append(license); result.append(", companyname: "); result.append(companyname); result.append(", status: "); result.append(status); result.append(", supporturl: "); result.append(supporturl); result.append(", version: "); result.append(version); result.append(", eclipseversion: "); result.append(eclipseversion); result.append(", updateurl: "); result.append(updateurl); result.append(", screenshot: "); result.append(screenshot); result.append(", rawBody: "); result.append(rawBody); result.append(')'); return result.toString(); } } // NodeImpl
org.dawnsci.marketplace.core/src-gen/org/dawnsci/marketplace/impl/NodeImpl.java
/** */ package org.dawnsci.marketplace.impl; import javax.xml.bind.annotation.XmlRootElement; import org.dawnsci.marketplace.Categories; import org.dawnsci.marketplace.Ius; import org.dawnsci.marketplace.Marketplace; import org.dawnsci.marketplace.MarketplacePackage; import org.dawnsci.marketplace.Node; import org.dawnsci.marketplace.Platforms; import org.dawnsci.marketplace.Tags; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; /** * <!-- begin-user-doc --> An implementation of the model object ' * <em><b>Node</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getId <em>Id</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getName <em>Name</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getType <em>Type</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getCategories <em>Categories</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getTags <em>Tags</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getOwner <em>Owner</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getFavorited <em>Favorited</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getInstallstotal <em>Installstotal</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getInstallsrecent <em>Installsrecent</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getShortdescription <em>Shortdescription</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getBody <em>Body</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getCreated <em>Created</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getChanged <em>Changed</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getFoundationmember <em>Foundationmember</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getHomepageurl <em>Homepageurl</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getImage <em>Image</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getLicense <em>License</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getCompanyname <em>Companyname</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getStatus <em>Status</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getSupporturl <em>Supporturl</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getVersion <em>Version</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getEclipseversion <em>Eclipseversion</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getUpdateurl <em>Updateurl</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getIus <em>Ius</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getPlatforms <em>Platforms</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getUrl <em>Url</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getScreenshot <em>Screenshot</em>}</li> * <li>{@link org.dawnsci.marketplace.impl.NodeImpl#getRawBody <em>Raw Body</em>}</li> * </ul> * * @generated */ @XmlRootElement(name = "Node") public class NodeImpl extends MinimalEObjectImpl.Container implements Node { /** * The default value of the '{@link #getId() <em>Id</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getId() * @generated * @ordered */ protected static final Long ID_EDEFAULT = null; /** * The cached value of the '{@link #getId() <em>Id</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getId() * @generated * @ordered */ protected Long id = ID_EDEFAULT; /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected static final String TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected String type = TYPE_EDEFAULT; /** * The cached value of the '{@link #getCategories() <em>Categories</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCategories() * @generated * @ordered */ protected Categories categories; /** * The cached value of the '{@link #getTags() <em>Tags</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTags() * @generated * @ordered */ protected Tags tags; /** * The default value of the '{@link #getOwner() <em>Owner</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getOwner() * @generated * @ordered */ protected static final String OWNER_EDEFAULT = null; /** * The cached value of the '{@link #getOwner() <em>Owner</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getOwner() * @generated * @ordered */ protected String owner = OWNER_EDEFAULT; /** * The default value of the '{@link #getFavorited() <em>Favorited</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getFavorited() * @generated * @ordered */ protected static final Integer FAVORITED_EDEFAULT = null; /** * The cached value of the '{@link #getFavorited() <em>Favorited</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getFavorited() * @generated * @ordered */ protected Integer favorited = FAVORITED_EDEFAULT; /** * The default value of the '{@link #getInstallstotal() <em>Installstotal</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallstotal() * @generated * @ordered */ protected static final Integer INSTALLSTOTAL_EDEFAULT = null; /** * The cached value of the '{@link #getInstallstotal() <em>Installstotal</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallstotal() * @generated * @ordered */ protected Integer installstotal = INSTALLSTOTAL_EDEFAULT; /** * The default value of the '{@link #getInstallsrecent() <em>Installsrecent</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallsrecent() * @generated * @ordered */ protected static final Integer INSTALLSRECENT_EDEFAULT = null; /** * The cached value of the '{@link #getInstallsrecent() <em>Installsrecent</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getInstallsrecent() * @generated * @ordered */ protected Integer installsrecent = INSTALLSRECENT_EDEFAULT; /** * The default value of the '{@link #getShortdescription() <em>Shortdescription</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getShortdescription() * @generated * @ordered */ protected static final String SHORTDESCRIPTION_EDEFAULT = null; /** * The cached value of the '{@link #getShortdescription() <em>Shortdescription</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getShortdescription() * @generated * @ordered */ protected String shortdescription = SHORTDESCRIPTION_EDEFAULT; /** * The default value of the '{@link #getBody() <em>Body</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getBody() * @generated * @ordered */ protected static final String BODY_EDEFAULT = null; /** * The cached value of the '{@link #getBody() <em>Body</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getBody() * @generated * @ordered */ protected String body = BODY_EDEFAULT; /** * The default value of the '{@link #getCreated() <em>Created</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCreated() * @generated * @ordered */ protected static final Long CREATED_EDEFAULT = null; /** * The cached value of the '{@link #getCreated() <em>Created</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCreated() * @generated * @ordered */ protected Long created = CREATED_EDEFAULT; /** * The default value of the '{@link #getChanged() <em>Changed</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getChanged() * @generated * @ordered */ protected static final Long CHANGED_EDEFAULT = null; /** * The cached value of the '{@link #getChanged() <em>Changed</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getChanged() * @generated * @ordered */ protected Long changed = CHANGED_EDEFAULT; /** * The default value of the '{@link #getFoundationmember() <em>Foundationmember</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getFoundationmember() * @generated * @ordered */ protected static final Integer FOUNDATIONMEMBER_EDEFAULT = null; /** * The cached value of the '{@link #getFoundationmember() <em>Foundationmember</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getFoundationmember() * @generated * @ordered */ protected Integer foundationmember = FOUNDATIONMEMBER_EDEFAULT; /** * The default value of the '{@link #getHomepageurl() <em>Homepageurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getHomepageurl() * @generated * @ordered */ protected static final String HOMEPAGEURL_EDEFAULT = null; /** * The cached value of the '{@link #getHomepageurl() <em>Homepageurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getHomepageurl() * @generated * @ordered */ protected String homepageurl = HOMEPAGEURL_EDEFAULT; /** * The default value of the '{@link #getImage() <em>Image</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getImage() * @generated * @ordered */ protected static final String IMAGE_EDEFAULT = null; /** * The cached value of the '{@link #getImage() <em>Image</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getImage() * @generated * @ordered */ protected String image = IMAGE_EDEFAULT; /** * The default value of the '{@link #getLicense() <em>License</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getLicense() * @generated * @ordered */ protected static final String LICENSE_EDEFAULT = null; /** * The cached value of the '{@link #getLicense() <em>License</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getLicense() * @generated * @ordered */ protected String license = LICENSE_EDEFAULT; /** * The default value of the '{@link #getCompanyname() <em>Companyname</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCompanyname() * @generated * @ordered */ protected static final String COMPANYNAME_EDEFAULT = null; /** * The cached value of the '{@link #getCompanyname() <em>Companyname</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getCompanyname() * @generated * @ordered */ protected String companyname = COMPANYNAME_EDEFAULT; /** * The default value of the '{@link #getStatus() <em>Status</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected static final String STATUS_EDEFAULT = null; /** * The cached value of the '{@link #getStatus() <em>Status</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected String status = STATUS_EDEFAULT; /** * The default value of the '{@link #getSupporturl() <em>Supporturl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getSupporturl() * @generated * @ordered */ protected static final String SUPPORTURL_EDEFAULT = null; /** * The cached value of the '{@link #getSupporturl() <em>Supporturl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getSupporturl() * @generated * @ordered */ protected String supporturl = SUPPORTURL_EDEFAULT; /** * The default value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected static final String VERSION_EDEFAULT = null; /** * The cached value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected String version = VERSION_EDEFAULT; /** * The default value of the '{@link #getEclipseversion() <em>Eclipseversion</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getEclipseversion() * @generated * @ordered */ protected static final String ECLIPSEVERSION_EDEFAULT = null; /** * The cached value of the '{@link #getEclipseversion() <em>Eclipseversion</em>}' attribute. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @see #getEclipseversion() * @generated * @ordered */ protected String eclipseversion = ECLIPSEVERSION_EDEFAULT; /** * The default value of the '{@link #getUpdateurl() <em>Updateurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getUpdateurl() * @generated * @ordered */ protected static final String UPDATEURL_EDEFAULT = null; /** * The cached value of the '{@link #getUpdateurl() <em>Updateurl</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getUpdateurl() * @generated * @ordered */ protected String updateurl = UPDATEURL_EDEFAULT; /** * The cached value of the '{@link #getIus() <em>Ius</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getIus() * @generated * @ordered */ protected Ius ius; /** * The cached value of the '{@link #getPlatforms() <em>Platforms</em>}' containment reference. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getPlatforms() * @generated * @ordered */ protected Platforms platforms; /** * The default value of the '{@link #getUrl() <em>Url</em>}' attribute. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getUrl() * @generated * @ordered */ protected static final String URL_EDEFAULT = ""; /** * The default value of the '{@link #getScreenshot() <em>Screenshot</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getScreenshot() * @generated * @ordered */ protected static final String SCREENSHOT_EDEFAULT = null; /** * The cached value of the '{@link #getScreenshot() <em>Screenshot</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getScreenshot() * @generated * @ordered */ protected String screenshot = SCREENSHOT_EDEFAULT; /** * The default value of the '{@link #getRawBody() <em>Raw Body</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRawBody() * @generated * @ordered */ protected static final String RAW_BODY_EDEFAULT = null; /** * The cached value of the '{@link #getRawBody() <em>Raw Body</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRawBody() * @generated * @ordered */ protected String rawBody = RAW_BODY_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected NodeImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MarketplacePackage.Literals.NODE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Long getId() { return id; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setId(Long newId) { Long oldId = id; id = newId; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__ID, oldId, id)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getFavorited() { return favorited; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFavorited(Integer newFavorited) { Integer oldFavorited = favorited; favorited = newFavorited; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__FAVORITED, oldFavorited, favorited)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getInstallstotal() { return installstotal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInstallstotal(Integer newInstallstotal) { Integer oldInstallstotal = installstotal; installstotal = newInstallstotal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__INSTALLSTOTAL, oldInstallstotal, installstotal)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getInstallsrecent() { return installsrecent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInstallsrecent(Integer newInstallsrecent) { Integer oldInstallsrecent = installsrecent; installsrecent = newInstallsrecent; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__INSTALLSRECENT, oldInstallsrecent, installsrecent)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getShortdescription() { return shortdescription; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setShortdescription(String newShortdescription) { String oldShortdescription = shortdescription; shortdescription = newShortdescription; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__SHORTDESCRIPTION, oldShortdescription, shortdescription)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getBody() { return body; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setBody(String newBody) { String oldBody = body; body = newBody; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__BODY, oldBody, body)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Long getCreated() { return created; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCreated(Long newCreated) { Long oldCreated = created; created = newCreated; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CREATED, oldCreated, created)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Long getChanged() { return changed; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setChanged(Long newChanged) { Long oldChanged = changed; changed = newChanged; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CHANGED, oldChanged, changed)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Integer getFoundationmember() { return foundationmember; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFoundationmember(Integer newFoundationmember) { Integer oldFoundationmember = foundationmember; foundationmember = newFoundationmember; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__FOUNDATIONMEMBER, oldFoundationmember, foundationmember)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getHomepageurl() { return homepageurl; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setHomepageurl(String newHomepageurl) { String oldHomepageurl = homepageurl; homepageurl = newHomepageurl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__HOMEPAGEURL, oldHomepageurl, homepageurl)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public String getImage() { if (image == null || image.isEmpty()) { return null; } if (getBaseUrl() == null) { return image; } return getBaseUrl()+"/files/" + getId() + "/" + image; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setImage(String newImage) { String oldImage = image; image = newImage; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__IMAGE, oldImage, image)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getLicense() { return license; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setLicense(String newLicense) { String oldLicense = license; license = newLicense; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__LICENSE, oldLicense, license)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getCompanyname() { return companyname; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCompanyname(String newCompanyname) { String oldCompanyname = companyname; companyname = newCompanyname; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__COMPANYNAME, oldCompanyname, companyname)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getStatus() { return status; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setStatus(String newStatus) { String oldStatus = status; status = newStatus; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__STATUS, oldStatus, status)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getSupporturl() { return supporturl; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setSupporturl(String newSupporturl) { String oldSupporturl = supporturl; supporturl = newSupporturl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__SUPPORTURL, oldSupporturl, supporturl)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getVersion() { return version; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setVersion(String newVersion) { String oldVersion = version; version = newVersion; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__VERSION, oldVersion, version)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getEclipseversion() { return eclipseversion; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setEclipseversion(String newEclipseversion) { String oldEclipseversion = eclipseversion; eclipseversion = newEclipseversion; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__ECLIPSEVERSION, oldEclipseversion, eclipseversion)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated Not */ public String getUpdateurl() { if (getBaseUrl() == null) { return updateurl; } return getBaseUrl()+"/files/" + getId() + "/" + updateurl; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setUpdateurl(String newUpdateurl) { String oldUpdateurl = updateurl; updateurl = newUpdateurl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__UPDATEURL, oldUpdateurl, updateurl)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Ius getIus() { return ius; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetIus(Ius newIus, NotificationChain msgs) { Ius oldIus = ius; ius = newIus; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__IUS, oldIus, newIus); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setIus(Ius newIus) { if (newIus != ius) { NotificationChain msgs = null; if (ius != null) msgs = ((InternalEObject)ius).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__IUS, null, msgs); if (newIus != null) msgs = ((InternalEObject)newIus).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__IUS, null, msgs); msgs = basicSetIus(newIus, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__IUS, newIus, newIus)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Platforms getPlatforms() { return platforms; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public NotificationChain basicSetPlatforms(Platforms newPlatforms, NotificationChain msgs) { Platforms oldPlatforms = platforms; platforms = newPlatforms; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__PLATFORMS, oldPlatforms, newPlatforms); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setPlatforms(Platforms newPlatforms) { if (newPlatforms != platforms) { NotificationChain msgs = null; if (platforms != null) msgs = ((InternalEObject)platforms).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__PLATFORMS, null, msgs); if (newPlatforms != null) msgs = ((InternalEObject)newPlatforms).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__PLATFORMS, null, msgs); msgs = basicSetPlatforms(newPlatforms, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__PLATFORMS, newPlatforms, newPlatforms)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public String getUrl() { if (getBaseUrl() == null) { return ""; } return getBaseUrl() + "/" + getId(); } /** * Used to calculate the base URL of URL's relative to the marketplace * server. This can only be found if this instance is contained within an * object which root container is a Marketplace instance. * * @return the base URL or <code>null</code> */ private String getBaseUrl() { EObject rootContainer = EcoreUtil.getRootContainer(this); if (rootContainer != null && rootContainer instanceof Marketplace) { String baseUrl = ((Marketplace) rootContainer).getBaseUrl(); if (baseUrl != null) { return baseUrl; } } return null; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public void setUrl(String newUrl) { } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated Not */ public String getScreenshot() { if (screenshot == null || screenshot.isEmpty()) { return null; } if (getBaseUrl() == null) { return screenshot; } return getBaseUrl()+"/files/" + getId() + "/" + screenshot; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setScreenshot(String newScreenshot) { String oldScreenshot = screenshot; screenshot = newScreenshot; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__SCREENSHOT, oldScreenshot, screenshot)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getRawBody() { return rawBody; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRawBody(String newRawBody) { String oldRawBody = rawBody; rawBody = newRawBody; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__RAW_BODY, oldRawBody, rawBody)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MarketplacePackage.NODE__CATEGORIES: return basicSetCategories(null, msgs); case MarketplacePackage.NODE__TAGS: return basicSetTags(null, msgs); case MarketplacePackage.NODE__IUS: return basicSetIus(null, msgs); case MarketplacePackage.NODE__PLATFORMS: return basicSetPlatforms(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getType() { return type; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setType(String newType) { String oldType = type; type = newType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__TYPE, oldType, type)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Categories getCategories() { return categories; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCategories(Categories newCategories, NotificationChain msgs) { Categories oldCategories = categories; categories = newCategories; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CATEGORIES, oldCategories, newCategories); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setCategories(Categories newCategories) { if (newCategories != categories) { NotificationChain msgs = null; if (categories != null) msgs = ((InternalEObject)categories).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__CATEGORIES, null, msgs); if (newCategories != null) msgs = ((InternalEObject)newCategories).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__CATEGORIES, null, msgs); msgs = basicSetCategories(newCategories, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__CATEGORIES, newCategories, newCategories)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Tags getTags() { return tags; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTags(Tags newTags, NotificationChain msgs) { Tags oldTags = tags; tags = newTags; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__TAGS, oldTags, newTags); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setTags(Tags newTags) { if (newTags != tags) { NotificationChain msgs = null; if (tags != null) msgs = ((InternalEObject)tags).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__TAGS, null, msgs); if (newTags != null) msgs = ((InternalEObject)newTags).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MarketplacePackage.NODE__TAGS, null, msgs); msgs = basicSetTags(newTags, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__TAGS, newTags, newTags)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getOwner() { return owner; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setOwner(String newOwner) { String oldOwner = owner; owner = newOwner; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MarketplacePackage.NODE__OWNER, oldOwner, owner)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MarketplacePackage.NODE__ID: return getId(); case MarketplacePackage.NODE__NAME: return getName(); case MarketplacePackage.NODE__TYPE: return getType(); case MarketplacePackage.NODE__CATEGORIES: return getCategories(); case MarketplacePackage.NODE__TAGS: return getTags(); case MarketplacePackage.NODE__OWNER: return getOwner(); case MarketplacePackage.NODE__FAVORITED: return getFavorited(); case MarketplacePackage.NODE__INSTALLSTOTAL: return getInstallstotal(); case MarketplacePackage.NODE__INSTALLSRECENT: return getInstallsrecent(); case MarketplacePackage.NODE__SHORTDESCRIPTION: return getShortdescription(); case MarketplacePackage.NODE__BODY: return getBody(); case MarketplacePackage.NODE__CREATED: return getCreated(); case MarketplacePackage.NODE__CHANGED: return getChanged(); case MarketplacePackage.NODE__FOUNDATIONMEMBER: return getFoundationmember(); case MarketplacePackage.NODE__HOMEPAGEURL: return getHomepageurl(); case MarketplacePackage.NODE__IMAGE: return getImage(); case MarketplacePackage.NODE__LICENSE: return getLicense(); case MarketplacePackage.NODE__COMPANYNAME: return getCompanyname(); case MarketplacePackage.NODE__STATUS: return getStatus(); case MarketplacePackage.NODE__SUPPORTURL: return getSupporturl(); case MarketplacePackage.NODE__VERSION: return getVersion(); case MarketplacePackage.NODE__ECLIPSEVERSION: return getEclipseversion(); case MarketplacePackage.NODE__UPDATEURL: return getUpdateurl(); case MarketplacePackage.NODE__IUS: return getIus(); case MarketplacePackage.NODE__PLATFORMS: return getPlatforms(); case MarketplacePackage.NODE__URL: return getUrl(); case MarketplacePackage.NODE__SCREENSHOT: return getScreenshot(); case MarketplacePackage.NODE__RAW_BODY: return getRawBody(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MarketplacePackage.NODE__ID: setId((Long)newValue); return; case MarketplacePackage.NODE__NAME: setName((String)newValue); return; case MarketplacePackage.NODE__TYPE: setType((String)newValue); return; case MarketplacePackage.NODE__CATEGORIES: setCategories((Categories)newValue); return; case MarketplacePackage.NODE__TAGS: setTags((Tags)newValue); return; case MarketplacePackage.NODE__OWNER: setOwner((String)newValue); return; case MarketplacePackage.NODE__FAVORITED: setFavorited((Integer)newValue); return; case MarketplacePackage.NODE__INSTALLSTOTAL: setInstallstotal((Integer)newValue); return; case MarketplacePackage.NODE__INSTALLSRECENT: setInstallsrecent((Integer)newValue); return; case MarketplacePackage.NODE__SHORTDESCRIPTION: setShortdescription((String)newValue); return; case MarketplacePackage.NODE__BODY: setBody((String)newValue); return; case MarketplacePackage.NODE__CREATED: setCreated((Long)newValue); return; case MarketplacePackage.NODE__CHANGED: setChanged((Long)newValue); return; case MarketplacePackage.NODE__FOUNDATIONMEMBER: setFoundationmember((Integer)newValue); return; case MarketplacePackage.NODE__HOMEPAGEURL: setHomepageurl((String)newValue); return; case MarketplacePackage.NODE__IMAGE: setImage((String)newValue); return; case MarketplacePackage.NODE__LICENSE: setLicense((String)newValue); return; case MarketplacePackage.NODE__COMPANYNAME: setCompanyname((String)newValue); return; case MarketplacePackage.NODE__STATUS: setStatus((String)newValue); return; case MarketplacePackage.NODE__SUPPORTURL: setSupporturl((String)newValue); return; case MarketplacePackage.NODE__VERSION: setVersion((String)newValue); return; case MarketplacePackage.NODE__ECLIPSEVERSION: setEclipseversion((String)newValue); return; case MarketplacePackage.NODE__UPDATEURL: setUpdateurl((String)newValue); return; case MarketplacePackage.NODE__IUS: setIus((Ius)newValue); return; case MarketplacePackage.NODE__PLATFORMS: setPlatforms((Platforms)newValue); return; case MarketplacePackage.NODE__URL: setUrl((String)newValue); return; case MarketplacePackage.NODE__SCREENSHOT: setScreenshot((String)newValue); return; case MarketplacePackage.NODE__RAW_BODY: setRawBody((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MarketplacePackage.NODE__ID: setId(ID_EDEFAULT); return; case MarketplacePackage.NODE__NAME: setName(NAME_EDEFAULT); return; case MarketplacePackage.NODE__TYPE: setType(TYPE_EDEFAULT); return; case MarketplacePackage.NODE__CATEGORIES: setCategories((Categories)null); return; case MarketplacePackage.NODE__TAGS: setTags((Tags)null); return; case MarketplacePackage.NODE__OWNER: setOwner(OWNER_EDEFAULT); return; case MarketplacePackage.NODE__FAVORITED: setFavorited(FAVORITED_EDEFAULT); return; case MarketplacePackage.NODE__INSTALLSTOTAL: setInstallstotal(INSTALLSTOTAL_EDEFAULT); return; case MarketplacePackage.NODE__INSTALLSRECENT: setInstallsrecent(INSTALLSRECENT_EDEFAULT); return; case MarketplacePackage.NODE__SHORTDESCRIPTION: setShortdescription(SHORTDESCRIPTION_EDEFAULT); return; case MarketplacePackage.NODE__BODY: setBody(BODY_EDEFAULT); return; case MarketplacePackage.NODE__CREATED: setCreated(CREATED_EDEFAULT); return; case MarketplacePackage.NODE__CHANGED: setChanged(CHANGED_EDEFAULT); return; case MarketplacePackage.NODE__FOUNDATIONMEMBER: setFoundationmember(FOUNDATIONMEMBER_EDEFAULT); return; case MarketplacePackage.NODE__HOMEPAGEURL: setHomepageurl(HOMEPAGEURL_EDEFAULT); return; case MarketplacePackage.NODE__IMAGE: setImage(IMAGE_EDEFAULT); return; case MarketplacePackage.NODE__LICENSE: setLicense(LICENSE_EDEFAULT); return; case MarketplacePackage.NODE__COMPANYNAME: setCompanyname(COMPANYNAME_EDEFAULT); return; case MarketplacePackage.NODE__STATUS: setStatus(STATUS_EDEFAULT); return; case MarketplacePackage.NODE__SUPPORTURL: setSupporturl(SUPPORTURL_EDEFAULT); return; case MarketplacePackage.NODE__VERSION: setVersion(VERSION_EDEFAULT); return; case MarketplacePackage.NODE__ECLIPSEVERSION: setEclipseversion(ECLIPSEVERSION_EDEFAULT); return; case MarketplacePackage.NODE__UPDATEURL: setUpdateurl(UPDATEURL_EDEFAULT); return; case MarketplacePackage.NODE__IUS: setIus((Ius)null); return; case MarketplacePackage.NODE__PLATFORMS: setPlatforms((Platforms)null); return; case MarketplacePackage.NODE__URL: setUrl(URL_EDEFAULT); return; case MarketplacePackage.NODE__SCREENSHOT: setScreenshot(SCREENSHOT_EDEFAULT); return; case MarketplacePackage.NODE__RAW_BODY: setRawBody(RAW_BODY_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MarketplacePackage.NODE__ID: return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id); case MarketplacePackage.NODE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case MarketplacePackage.NODE__TYPE: return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type); case MarketplacePackage.NODE__CATEGORIES: return categories != null; case MarketplacePackage.NODE__TAGS: return tags != null; case MarketplacePackage.NODE__OWNER: return OWNER_EDEFAULT == null ? owner != null : !OWNER_EDEFAULT.equals(owner); case MarketplacePackage.NODE__FAVORITED: return FAVORITED_EDEFAULT == null ? favorited != null : !FAVORITED_EDEFAULT.equals(favorited); case MarketplacePackage.NODE__INSTALLSTOTAL: return INSTALLSTOTAL_EDEFAULT == null ? installstotal != null : !INSTALLSTOTAL_EDEFAULT.equals(installstotal); case MarketplacePackage.NODE__INSTALLSRECENT: return INSTALLSRECENT_EDEFAULT == null ? installsrecent != null : !INSTALLSRECENT_EDEFAULT.equals(installsrecent); case MarketplacePackage.NODE__SHORTDESCRIPTION: return SHORTDESCRIPTION_EDEFAULT == null ? shortdescription != null : !SHORTDESCRIPTION_EDEFAULT.equals(shortdescription); case MarketplacePackage.NODE__BODY: return BODY_EDEFAULT == null ? body != null : !BODY_EDEFAULT.equals(body); case MarketplacePackage.NODE__CREATED: return CREATED_EDEFAULT == null ? created != null : !CREATED_EDEFAULT.equals(created); case MarketplacePackage.NODE__CHANGED: return CHANGED_EDEFAULT == null ? changed != null : !CHANGED_EDEFAULT.equals(changed); case MarketplacePackage.NODE__FOUNDATIONMEMBER: return FOUNDATIONMEMBER_EDEFAULT == null ? foundationmember != null : !FOUNDATIONMEMBER_EDEFAULT.equals(foundationmember); case MarketplacePackage.NODE__HOMEPAGEURL: return HOMEPAGEURL_EDEFAULT == null ? homepageurl != null : !HOMEPAGEURL_EDEFAULT.equals(homepageurl); case MarketplacePackage.NODE__IMAGE: return IMAGE_EDEFAULT == null ? image != null : !IMAGE_EDEFAULT.equals(image); case MarketplacePackage.NODE__LICENSE: return LICENSE_EDEFAULT == null ? license != null : !LICENSE_EDEFAULT.equals(license); case MarketplacePackage.NODE__COMPANYNAME: return COMPANYNAME_EDEFAULT == null ? companyname != null : !COMPANYNAME_EDEFAULT.equals(companyname); case MarketplacePackage.NODE__STATUS: return STATUS_EDEFAULT == null ? status != null : !STATUS_EDEFAULT.equals(status); case MarketplacePackage.NODE__SUPPORTURL: return SUPPORTURL_EDEFAULT == null ? supporturl != null : !SUPPORTURL_EDEFAULT.equals(supporturl); case MarketplacePackage.NODE__VERSION: return VERSION_EDEFAULT == null ? version != null : !VERSION_EDEFAULT.equals(version); case MarketplacePackage.NODE__ECLIPSEVERSION: return ECLIPSEVERSION_EDEFAULT == null ? eclipseversion != null : !ECLIPSEVERSION_EDEFAULT.equals(eclipseversion); case MarketplacePackage.NODE__UPDATEURL: return UPDATEURL_EDEFAULT == null ? updateurl != null : !UPDATEURL_EDEFAULT.equals(updateurl); case MarketplacePackage.NODE__IUS: return ius != null; case MarketplacePackage.NODE__PLATFORMS: return platforms != null; case MarketplacePackage.NODE__URL: return URL_EDEFAULT == null ? getUrl() != null : !URL_EDEFAULT.equals(getUrl()); case MarketplacePackage.NODE__SCREENSHOT: return SCREENSHOT_EDEFAULT == null ? screenshot != null : !SCREENSHOT_EDEFAULT.equals(screenshot); case MarketplacePackage.NODE__RAW_BODY: return RAW_BODY_EDEFAULT == null ? rawBody != null : !RAW_BODY_EDEFAULT.equals(rawBody); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (id: "); result.append(id); result.append(", name: "); result.append(name); result.append(", type: "); result.append(type); result.append(", owner: "); result.append(owner); result.append(", favorited: "); result.append(favorited); result.append(", installstotal: "); result.append(installstotal); result.append(", installsrecent: "); result.append(installsrecent); result.append(", shortdescription: "); result.append(shortdescription); result.append(", body: "); result.append(body); result.append(", created: "); result.append(created); result.append(", changed: "); result.append(changed); result.append(", foundationmember: "); result.append(foundationmember); result.append(", homepageurl: "); result.append(homepageurl); result.append(", image: "); result.append(image); result.append(", license: "); result.append(license); result.append(", companyname: "); result.append(companyname); result.append(", status: "); result.append(status); result.append(", supporturl: "); result.append(supporturl); result.append(", version: "); result.append(version); result.append(", eclipseversion: "); result.append(eclipseversion); result.append(", updateurl: "); result.append(updateurl); result.append(", screenshot: "); result.append(screenshot); result.append(", rawBody: "); result.append(rawBody); result.append(')'); return result.toString(); } } // NodeImpl
Fix URL linking to solution page on the marketplace.
org.dawnsci.marketplace.core/src-gen/org/dawnsci/marketplace/impl/NodeImpl.java
Fix URL linking to solution page on the marketplace.
<ide><path>rg.dawnsci.marketplace.core/src-gen/org/dawnsci/marketplace/impl/NodeImpl.java <ide> if (getBaseUrl() == null) { <ide> return ""; <ide> } <del> return getBaseUrl() + "/" + getId(); <del> } <del> <add> return getBaseUrl() + "/content/" + getId(); <add> } <add> <ide> /** <ide> * Used to calculate the base URL of URL's relative to the marketplace <ide> * server. This can only be found if this instance is contained within an
JavaScript
mit
b6bd18babae847d8533ae008208c669f3b8b29bb
0
britishgas-engineering/ya-done-appium
/* eslint-disable */ /* global featureFile, scenarios, steps */ const Yadda = require('yadda'); const wd = require('wd'); function buildDriver(server) { const configServer = server || { host: 'localhost', port: 4723, }; return wd.promiseChainRemote(configServer); }; function setBaseSteps(library, device) { library.define( 'a mobile app', function setWindowSize(done) { this.driver.init(device).then((built) => { if (device.deviceLogs) { this.log('set-up device', built); } done(); }); } ) .define( 'end the test', function endTest() { this.driver .quit(); } ); return library; } function buildYadda(library, device, server, logVerbose) { if (library === null || library === undefined) { throw new Error('step library has not been defined please write some steps'); } Yadda.plugins.mocha.StepLevelPlugin.init(); const features = new Yadda.FeatureFileSearch('features'); const builtLibrary = setBaseSteps(library, device); if (logVerbose) { require("./log").configure(driver); } return features .each( file => featureFile( file, (feature) => { const yadda = Yadda.createInstance( builtLibrary, { ctx: {}, driver: buildDriver(server), log: (label, data) => console.log(label, data) } ); scenarios( feature.scenarios, (scenario) => { steps( scenario.steps, (step, done) => { yadda.run(step, done); } ); } ); } ) ); } module.exports = buildYadda;
dist/lib/yadda-core.js
/* eslint-disable */ /* global featureFile, scenarios, steps */ const Yadda = require('yadda'); const wd = require('wd'); function buildDriver(server) { const configServer = server || { host: 'localhost', port: 4723, }; return wd.promiseChainRemote(configServer); }; function setBaseSteps(library, device, deviceLogs) { library.define( 'a mobile app', function setWindowSize(done) { console.log(deviceLogs) this.driver.init(device).then((built) => { if (deviceLogs === true) { this.log('set-up device', built); } done(); }); } ) .define( 'end the test', function endTest() { this.driver .quit(); } ); return library; } function buildYadda(library, device, server, logVerbose, deviceLogs) { if (library === null || library === undefined) { throw new Error('step library has not been defined please write some steps'); } Yadda.plugins.mocha.StepLevelPlugin.init(); const features = new Yadda.FeatureFileSearch('features'); const builtLibrary = setBaseSteps(library, device, deviceLogs); if (logVerbose) { require("./log").configure(driver); } return features .each( file => featureFile( file, (feature) => { const yadda = Yadda.createInstance( builtLibrary, { ctx: {}, driver: buildDriver(server), log: (label, data) => console.log(label, data) } ); scenarios( feature.scenarios, (scenario) => { steps( scenario.steps, (step, done) => { yadda.run(step, done); } ); } ); } ) ); } module.exports = buildYadda;
add if statement for logging
dist/lib/yadda-core.js
add if statement for logging
<ide><path>ist/lib/yadda-core.js <ide> return wd.promiseChainRemote(configServer); <ide> }; <ide> <del>function setBaseSteps(library, device, deviceLogs) { <add>function setBaseSteps(library, device) { <ide> library.define( <ide> 'a mobile app', <ide> function setWindowSize(done) { <del> console.log(deviceLogs) <ide> this.driver.init(device).then((built) => { <del> if (deviceLogs === true) { <add> if (device.deviceLogs) { <ide> this.log('set-up device', built); <ide> } <ide> done(); <ide> return library; <ide> } <ide> <del>function buildYadda(library, device, server, logVerbose, deviceLogs) { <add>function buildYadda(library, device, server, logVerbose) { <ide> if (library === null || library === undefined) { <ide> throw new Error('step library has not been defined please write some steps'); <ide> } <ide> Yadda.plugins.mocha.StepLevelPlugin.init(); <ide> const features = new Yadda.FeatureFileSearch('features'); <del> const builtLibrary = setBaseSteps(library, device, deviceLogs); <add> const builtLibrary = setBaseSteps(library, device); <ide> if (logVerbose) { <ide> require("./log").configure(driver); <ide> }
Java
apache-2.0
36fb343ac5e08a6659f319b768f1f6e4dea73ddf
0
cherryhill/collectionspace-application
/* Copyright 2010 University of Cambridge * Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in * compliance with this License. * * You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.chain.csp.webui.userdetails; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.collectionspace.chain.csp.config.ConfigException; import org.collectionspace.chain.csp.schema.AdminData; import org.collectionspace.chain.csp.schema.EmailData; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.Operation; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.collectionspace.csp.api.ui.UISession; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * receive JSON: { email: "[email protected]" } * test if valid user * if valid user: create token and email to user * if not send back exception * * user gets email: goes to url in email and sets new password * we check that the email and token submitted with the password match * if so change password * if not send back exception * @author csm22 * */ public class UserDetailsReset implements WebMethod { private static final Logger log=LoggerFactory.getLogger(UserDetailsReset.class); boolean setnewpassword = false; String base = "users"; Spec spec; private static String tokensalt = "74102328UserDetailsReset"; public UserDetailsReset(Boolean setnewpassword, Spec spec) { this.setnewpassword = setnewpassword; this.spec = spec; } private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails) throws UIException, JSONException { String token = createToken(csid); EmailData ed = spec.getEmailData(); String[] recipients = new String[1]; /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */ String messagebase = ed.getPasswordResetMessage(); String link = ed.getBaseURL() + ed.getLoginUrl() + "?token="+token+"&email="+ emailparam; String message = messagebase.replaceAll("\\{\\{link\\}\\}", link); String greeting = userdetails.getJSONObject("fields").getString("screenName"); message = message.replaceAll("\\{\\{greeting\\}\\}", greeting); message = message.replaceAll("\\\\n", "\\\n"); message = message.replaceAll("\\\\r", "\\\r"); String SMTP_HOST_NAME = ed.getSMTPHost(); String SMTP_PORT = ed.getSMTPPort(); String subject = ed.getPasswordResetSubject(); String from = ed.getFromAddress(); if(ed.getToAddress().isEmpty()){ recipients[0] = emailparam; } else{ recipients[0] = ed.getToAddress(); } Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", ed.doSMTPAuth()); props.put("mail.debug", ed.doSMTPDebug()); props.put("mail.smtp.port", SMTP_PORT); Session session = Session.getDefaultInstance(props); // XXX fix to allow authpassword /username session.setDebug(debug); Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message); Transport.send(msg); } catch (AddressException e) { throw new UIException("AddressException: "+e.getMessage()); } catch (MessagingException e) { throw new UIException("MessagingException: "+e.getMessage()); } return true; } private String createHash(String csid) throws UIException { try { byte[] buffer = csid.getBytes(); byte[] result = null; StringBuffer buf = null; MessageDigest md5 = MessageDigest.getInstance("MD5"); result = new byte[md5.getDigestLength()]; md5.reset(); md5.update(buffer); result = md5.digest(tokensalt.getBytes()); //create hex string from the 16-byte hash buf = new StringBuffer(result.length * 2); for (int i = 0; i < result.length; i++) { int intVal = result[i] & 0xff; if (intVal < 0x10) { buf.append("0"); } buf.append(Integer.toHexString(intVal).toUpperCase()); } return buf.toString().substring(0,5); } catch (NoSuchAlgorithmException e) { throw new UIException("There were problems with the algorithum"); } } /* create a token that holds date information */ private String createToken(String csid) throws UIException { String hash = createHash(csid); Long token = Long.parseLong(hash,16) * (System.currentTimeMillis() / 100000); return token.toString(); } private long daysBetween(Date startDate, Date endDate) throws UIException { long daysBetween = 0; while (startDate.before(endDate)) { startDate.setTime(startDate.getTime() + (24*60*60*1000)); daysBetween++; } return daysBetween; } private boolean tokenExpired(String token, String match) throws UIException{ EmailData ed = spec.getEmailData(); Integer lengthTokenIsValidFor = ed.getTokenValidForLength(); //token is what we got from the user, match is what we created //Get the date from when the token was created by dividing token by match Long dateFromToken = (Long.parseLong(token)*100000) / Long.parseLong(match, 16); Date oldDate = new Date(dateFromToken); //Date oldDate = new Date(dateFromToken - (8*24*60*60*1000)); //String old = dateFormat.format(oldDate); //Get the current date Date date = new Date(); //lengthTokenIsValidFor defaults to 7 days if(daysBetween(oldDate, date) > lengthTokenIsValidFor) return true; else return false; } private Boolean testToken(String csid, String token) throws UIException { String match = createHash(csid); if(!tokenExpired(token, match)){ log.debug("token matches"); return true; } log.debug("token expired"); return false; } private String sendJSON(Storage storage,String path,JSONObject data) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject fields=data.optJSONObject("fields"); if(path!=null) { // Update if(fields!=null) storage.updateJSON(base+"/"+path,fields); } //else { // Create SHOULDN"T EVER HAPPEN //if(fields!=null) // path=storage.autocreateJSON(base,fields); //} return path; } private JSONObject getcsID(Storage storage,String emailparam) throws UIException { JSONObject restriction=new JSONObject(); JSONObject failedJSON = new JSONObject(); try { failedJSON.put("isError",true); if(emailparam!=null && emailparam!="") { restriction.put("email",emailparam); restriction.put("pageSize","40"); int resultsize =1; int pagenum = 0; String checkpagination = ""; while(resultsize >0){ restriction.put("pageNum",pagenum); /* XXX need to force it to only do an exact match */ JSONObject data = storage.getPathsJSON(base,restriction); String[] paths = (String[]) data.get("listItems"); pagenum++; if(paths.length==0 || checkpagination.equals(paths[0])){ resultsize=0; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = paths[0]; /* make sure it is an exact match */ for(int i=0;i<paths.length;i++) { //GET full details JSONObject fields = storage.retrieveJSON(base+"/"+paths[i], new JSONObject()); String emailtest = fields.getString("email"); if(emailtest.equals(emailparam)){ JSONObject outputJSON = new JSONObject(); outputJSON.put("fields",fields); outputJSON.put("isError",false); outputJSON.put("csid",paths[i]); return outputJSON; } } } } failedJSON.put("message","Could not find a user with email " + emailparam); } else{ failedJSON.put("message","No email specified "); } return failedJSON; } catch (JSONException e) { throw new UIException("JSONException during search on email address",e); } catch (ExistException e) { throw new UIException("ExistException during search on email address",e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during search on email address",e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x); return uiexception.getJSON(); } } private boolean testSuccess(Storage storage) { for(Record r : this.spec.getAllRecords()) { if(!r.isType("record")) continue; try { storage.getPathsJSON(r.getID(),null); return true; } catch (Exception e) { return false; } } return false; } /* find csid for email, create token, email token to the user */ private void send_reset_email(Storage storage,UIRequest request, Request in) throws UIException { JSONObject data = null; data=request.getJSONBody(); //mock login else service layer gets upset = not working // XXX ARGH AdminData ad = spec.getAdminData(); request.getSession().setValue(UISession.USERID,ad.getAuthUser()); request.getSession().setValue(UISession.PASSWORD,ad.getAuthPass()); in.reset(); JSONObject outputJSON = new JSONObject(); if(testSuccess(in.getStorage())) { String emailparam = ""; /* get csid of email address */ try { emailparam = data.getString("email"); JSONObject userdetails = getcsID(storage,emailparam); if(!userdetails.getBoolean("isError")){ String csid = userdetails.getString("csid"); /* for debug purposes */ if(data.has("debug") && data.getBoolean("debug")){ //only send email if debug is false/null see unit test TestGeneral testPasswordReset outputJSON.put("token",createToken(csid)); outputJSON.put("email", emailparam); } else{ doEmail(csid,emailparam,in,userdetails); } outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "Password reset sent to " + emailparam); messages.put("severity", "info"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } else { outputJSON = userdetails; } request.getSession().setValue(UISession.USERID,""); request.getSession().setValue(UISession.PASSWORD,""); in.reset(); } catch (UIException e) { //throw new UIException("Failed to send email",e); try { outputJSON.put("isError", true); JSONObject messages = new JSONObject(); messages.put("message", "Failed to send email: "+e.getMessage()); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException e1) { throw new UIException("JSONException during error messaging",e); } } catch (JSONException e) { throw new UIException("JSONException during search on email address",e); } } else{ try { outputJSON.put("isError", true); JSONObject messages = new JSONObject(); messages.put("message", "The admin details in cspace-config.xml failed"); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } } request.sendJSONResponse(outputJSON); request.setOperationPerformed(Operation.CREATE); } /* check token and if matches csid then reset password * */ private void reset_password(Storage storage,UIRequest request, Request in) throws UIException { //mock login else service layer gets upset // XXX ARGH AdminData ad = spec.getAdminData(); request.getSession().setValue(UISession.USERID,ad.getAuthUser()); request.getSession().setValue(UISession.PASSWORD,ad.getAuthPass()); in.reset(); JSONObject outputJSON = new JSONObject(); if(testSuccess(in.getStorage())) { JSONObject data = null; data=request.getJSONBody(); String token; try { token = data.getString("token"); String password=data.getString("password"); String email=data.getString("email"); JSONObject userdetails = getcsID(storage,email); if(!userdetails.getBoolean("isError")){ String csid = userdetails.getString("csid"); if(testToken(csid,token)){ /* update userdetails */ String path = csid; JSONObject fields = userdetails.getJSONObject("fields"); try { JSONObject changedata = new JSONObject(); JSONObject updatefields = fields; updatefields.put("password",password); changedata.put("fields",updatefields); changedata.put("csid",csid); sendJSON(storage,path,changedata); outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "Your Password has been succesfully changed, Please login"); messages.put("severity", "info"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } catch (ExistException x) { throw new UIException("Existence exception: ",x); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: ",x); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x); outputJSON = uiexception.getJSON(); } } else{ outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "Token was not valid"); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } } else{ outputJSON = userdetails; } request.getSession().setValue(UISession.USERID,""); request.getSession().setValue(UISession.PASSWORD,""); in.reset(); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } } else{ try { outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "The admin details in cspace-config.xml failed"); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } } /* should we automagically log them in or let them do that?, * I think we should let them login, it has the advantage * that they find out straight away if they can't remember the new password */ request.sendJSONResponse(outputJSON); request.setOperationPerformed(Operation.CREATE); } public void run(Object in, String[] tail) throws UIException { Request q=(Request)in; if(setnewpassword){ reset_password(q.getStorage(),q.getUIRequest(),q); } else{ send_reset_email(q.getStorage(),q.getUIRequest(),q); } } public void configure() throws ConfigException {} public void configure(WebUI ui,Spec spec) {} }
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/userdetails/UserDetailsReset.java
/* Copyright 2010 University of Cambridge * Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in * compliance with this License. * * You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt */ package org.collectionspace.chain.csp.webui.userdetails; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.collectionspace.chain.csp.config.ConfigException; import org.collectionspace.chain.csp.schema.AdminData; import org.collectionspace.chain.csp.schema.EmailData; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.Operation; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.collectionspace.csp.api.ui.UISession; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * receive JSON: { email: "[email protected]" } * test if valid user * if valid user: create token and email to user * if not send back exception * * user gets email: goes to url in email and sets new password * we check that the email and token submitted with the password match * if so change password * if not send back exception * @author csm22 * */ public class UserDetailsReset implements WebMethod { private static final Logger log=LoggerFactory.getLogger(UserDetailsReset.class); boolean setnewpassword = false; String base = "users"; Spec spec; private static String tokensalt = "74102328UserDetailsReset"; public UserDetailsReset(Boolean setnewpassword, Spec spec) { this.setnewpassword = setnewpassword; this.spec = spec; } private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails) throws UIException, JSONException { String token = createToken(csid); EmailData ed = spec.getEmailData(); String[] recipients = new String[1]; /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */ String messagebase = ed.getPasswordResetMessage(); String link = ed.getBaseURL() + ed.getLoginUrl() + "?token="+token+"&email="+ emailparam; String message = messagebase.replaceAll("\\{\\{link\\}\\}", link); String greeting = userdetails.getJSONObject("fields").getString("screenName"); message = message.replaceAll("\\{\\{greeting\\}\\}", greeting); message = message.replaceAll("\\\\n", "\\\n"); message = message.replaceAll("\\\\r", "\\\r"); String SMTP_HOST_NAME = ed.getSMTPHost(); String SMTP_PORT = ed.getSMTPPort(); String subject = ed.getPasswordResetSubject(); String from = ed.getFromAddress(); if(ed.getToAddress().isEmpty()){ recipients[0] = emailparam; } else{ recipients[0] = ed.getToAddress(); } Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", ed.doSMTPAuth()); props.put("mail.debug", ed.doSMTPDebug()); props.put("mail.smtp.port", SMTP_PORT); Session session = Session.getDefaultInstance(props); // XXX fix to allow authpassword /username session.setDebug(debug); Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message); // msg.setContent(message, "text/plain"); Transport.send(msg); } catch (AddressException e) { throw new UIException("AddressException: "+e.getMessage()); } catch (MessagingException e) { throw new UIException("MessagingException: "+e.getMessage()); } return true; } private String createHash(String csid) throws UIException { try { byte[] buffer = csid.getBytes(); byte[] result = null; StringBuffer buf = null; MessageDigest md5 = MessageDigest.getInstance("MD5"); result = new byte[md5.getDigestLength()]; md5.reset(); md5.update(buffer); result = md5.digest(tokensalt.getBytes()); //create hex string from the 16-byte hash buf = new StringBuffer(result.length * 2); for (int i = 0; i < result.length; i++) { int intVal = result[i] & 0xff; if (intVal < 0x10) { buf.append("0"); } buf.append(Integer.toHexString(intVal).toUpperCase()); } return buf.toString().substring(0,5); } catch (NoSuchAlgorithmException e) { throw new UIException("There were problems with the algorithum"); } } /* create a token that holds date information */ private String createToken(String csid) throws UIException { String hash = createHash(csid); Long token = Long.parseLong(hash,16) * (System.currentTimeMillis() / 100000); return token.toString(); } private long daysBetween(Date startDate, Date endDate) throws UIException { long daysBetween = 0; while (startDate.before(endDate)) { startDate.setTime(startDate.getTime() + (24*60*60*1000)); daysBetween++; } return daysBetween; } private boolean tokenExpired(String token, String match) throws UIException{ EmailData ed = spec.getEmailData(); Integer lengthTokenIsValidFor = ed.getTokenValidForLength(); //token is what we got from the user, match is what we created //Get the date from when the token was created by dividing token by match Long dateFromToken = (Long.parseLong(token)*100000) / Long.parseLong(match, 16); Date oldDate = new Date(dateFromToken); //Date oldDate = new Date(dateFromToken - (8*24*60*60*1000)); //String old = dateFormat.format(oldDate); //Get the current date Date date = new Date(); //lengthTokenIsValidFor defaults to 7 days if(daysBetween(oldDate, date) > lengthTokenIsValidFor) return true; else return false; } private Boolean testToken(String csid, String token) throws UIException { String match = createHash(csid); if(!tokenExpired(token, match)){ log.debug("token matches"); return true; } log.debug("token expired"); return false; } private String sendJSON(Storage storage,String path,JSONObject data) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject fields=data.optJSONObject("fields"); if(path!=null) { // Update if(fields!=null) storage.updateJSON(base+"/"+path,fields); } //else { // Create SHOULDN"T EVER HAPPEN //if(fields!=null) // path=storage.autocreateJSON(base,fields); //} return path; } private JSONObject getcsID(Storage storage,String emailparam) throws UIException { JSONObject restriction=new JSONObject(); JSONObject failedJSON = new JSONObject(); try { failedJSON.put("isError",true); if(emailparam!=null && emailparam!="") { restriction.put("email",emailparam); restriction.put("pageSize","40"); int resultsize =1; int pagenum = 0; String checkpagination = ""; while(resultsize >0){ restriction.put("pageNum",pagenum); /* XXX need to force it to only do an exact match */ JSONObject data = storage.getPathsJSON(base,restriction); String[] paths = (String[]) data.get("listItems"); pagenum++; if(paths.length==0 || checkpagination.equals(paths[0])){ resultsize=0; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = paths[0]; /* make sure it is an exact match */ for(int i=0;i<paths.length;i++) { //GET full details JSONObject fields = storage.retrieveJSON(base+"/"+paths[i], new JSONObject()); String emailtest = fields.getString("email"); if(emailtest.equals(emailparam)){ JSONObject outputJSON = new JSONObject(); outputJSON.put("fields",fields); outputJSON.put("isError",false); outputJSON.put("csid",paths[i]); return outputJSON; } } } } failedJSON.put("message","Could not find a user with email " + emailparam); } else{ failedJSON.put("message","No email specified "); } return failedJSON; } catch (JSONException e) { throw new UIException("JSONException during search on email address",e); } catch (ExistException e) { throw new UIException("ExistException during search on email address",e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during search on email address",e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x); return uiexception.getJSON(); } } private boolean testSuccess(Storage storage) { for(Record r : this.spec.getAllRecords()) { if(!r.isType("record")) continue; try { storage.getPathsJSON(r.getID(),null); return true; } catch (Exception e) { return false; } } return false; } /* find csid for email, create token, email token to the user */ private void send_reset_email(Storage storage,UIRequest request, Request in) throws UIException { JSONObject data = null; data=request.getJSONBody(); //mock login else service layer gets upset = not working // XXX ARGH AdminData ad = spec.getAdminData(); request.getSession().setValue(UISession.USERID,ad.getAuthUser()); request.getSession().setValue(UISession.PASSWORD,ad.getAuthPass()); in.reset(); JSONObject outputJSON = new JSONObject(); if(testSuccess(in.getStorage())) { String emailparam = ""; /* get csid of email address */ try { emailparam = data.getString("email"); JSONObject userdetails = getcsID(storage,emailparam); if(!userdetails.getBoolean("isError")){ String csid = userdetails.getString("csid"); /* for debug purposes */ if(data.has("debug") && data.getBoolean("debug")){ //only send email if debug is false/null see unit test TestGeneral testPasswordReset outputJSON.put("token",createToken(csid)); outputJSON.put("email", emailparam); } else{ doEmail(csid,emailparam,in,userdetails); } outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "Password reset sent to " + emailparam); messages.put("severity", "info"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } else { outputJSON = userdetails; } request.getSession().setValue(UISession.USERID,""); request.getSession().setValue(UISession.PASSWORD,""); in.reset(); } catch (UIException e) { //throw new UIException("Failed to send email",e); try { outputJSON.put("isError", true); JSONObject messages = new JSONObject(); messages.put("message", "Failed to send email: "+e.getMessage()); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException e1) { throw new UIException("JSONException during error messaging",e); } } catch (JSONException e) { throw new UIException("JSONException during search on email address",e); } } else{ try { outputJSON.put("isError", true); JSONObject messages = new JSONObject(); messages.put("message", "The admin details in cspace-config.xml failed"); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } } request.sendJSONResponse(outputJSON); request.setOperationPerformed(Operation.CREATE); } /* check token and if matches csid then reset password * */ private void reset_password(Storage storage,UIRequest request, Request in) throws UIException { //mock login else service layer gets upset // XXX ARGH AdminData ad = spec.getAdminData(); request.getSession().setValue(UISession.USERID,ad.getAuthUser()); request.getSession().setValue(UISession.PASSWORD,ad.getAuthPass()); in.reset(); JSONObject outputJSON = new JSONObject(); if(testSuccess(in.getStorage())) { JSONObject data = null; data=request.getJSONBody(); String token; try { token = data.getString("token"); String password=data.getString("password"); String email=data.getString("email"); JSONObject userdetails = getcsID(storage,email); if(!userdetails.getBoolean("isError")){ String csid = userdetails.getString("csid"); if(testToken(csid,token)){ /* update userdetails */ String path = csid; JSONObject fields = userdetails.getJSONObject("fields"); try { JSONObject changedata = new JSONObject(); JSONObject updatefields = fields; updatefields.put("password",password); changedata.put("fields",updatefields); changedata.put("csid",csid); sendJSON(storage,path,changedata); outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "Your Password has been succesfully changed, Please login"); messages.put("severity", "info"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } catch (ExistException x) { throw new UIException("Existence exception: ",x); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: ",x); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(),x.getStatus(),x.getUrl(),x); outputJSON = uiexception.getJSON(); } } else{ outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "Token was not valid"); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } } else{ outputJSON = userdetails; } request.getSession().setValue(UISession.USERID,""); request.getSession().setValue(UISession.PASSWORD,""); in.reset(); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } } else{ try { outputJSON.put("isError",false); JSONObject messages = new JSONObject(); messages.put("message", "The admin details in cspace-config.xml failed"); messages.put("severity", "error"); JSONArray arr = new JSONArray(); arr.put(messages); outputJSON.put("messages", arr); } catch (JSONException x) { throw new UIException("Failed to parse json: ",x); } } /* should we automagically log them in or let them do that?, * I think we should let them login, it has the advantage * that they find out straight away if they can't remember the new password */ request.sendJSONResponse(outputJSON); request.setOperationPerformed(Operation.CREATE); } public void run(Object in, String[] tail) throws UIException { Request q=(Request)in; if(setnewpassword){ reset_password(q.getStorage(),q.getUIRequest(),q); } else{ send_reset_email(q.getStorage(),q.getUIRequest(),q); } } public void configure() throws ConfigException {} public void configure(WebUI ui,Spec spec) {} }
CSPACE-4130
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/userdetails/UserDetailsReset.java
CSPACE-4130
<ide><path>spi-webui/src/main/java/org/collectionspace/chain/csp/webui/userdetails/UserDetailsReset.java <ide> // Setting the Subject and Content Type <ide> msg.setSubject(subject); <ide> msg.setText(message); <del> // msg.setContent(message, "text/plain"); <ide> <ide> Transport.send(msg); <ide> } catch (AddressException e) {
Java
epl-1.0
b9548da80d1c74fb3a1d07a081c94f41355bc359
0
polarsys/eplmp
/******************************************************************************* * Copyright (c) 2017 DocDoku. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * <p> * Contributors: * DocDoku - initial API and implementation *******************************************************************************/ package org.polarsys.eplmp.server.indexer; import com.amazonaws.auth.*; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.internal.StaticCredentialsProvider; import io.searchbox.client.JestClient; import io.searchbox.client.JestClientFactory; import io.searchbox.client.config.HttpClientConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import vc.inreach.aws.request.AWSSigner; import vc.inreach.aws.request.AWSSigningRequestInterceptor; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Singleton; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.logging.Level; import java.util.logging.Logger; @Singleton(name = "IndexerClientProducer") public class IndexerClientProducer { private static final Logger LOGGER = Logger.getLogger(IndexerClientProducer.class.getName()); private JestClient client; @Inject private IndexerConfigManager config; @PostConstruct public void open() { LOGGER.log(Level.INFO, "Create Elasticsearch client"); String serverUri = config.getServerUri(); String username = config.getUserName(); String password = config.getPassword(); String awsService = config.getAWSService(); String awsRegion = config.getAWSRegion(); String awsAccessKey = config.getAWSAccessKey(); String awsSecretKey = config.getAWSSecretKey(); HttpClientConfig.Builder httpConfigBuilder = new HttpClientConfig.Builder(serverUri) .multiThreaded(true) .defaultMaxTotalConnectionPerRoute(8); if (username != null && password != null) httpConfigBuilder.defaultCredentials(username, password); JestClientFactory factory; if (awsService != null && awsRegion != null) { final AWSCredentialsProviderChain providerChain; if (awsAccessKey != null && awsSecretKey != null) { providerChain = new AWSCredentialsProviderChain( new AWSStaticCredentialsProvider( new BasicAWSCredentials(awsAccessKey, awsSecretKey) ) ); } else { providerChain = new DefaultAWSCredentialsProviderChain(); } final AWSSigner awsSigner = new AWSSigner(providerChain, awsRegion, awsService, () -> LocalDateTime.now(ZoneOffset.UTC)); final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner); factory = new JestClientFactory() { @Override protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) { builder.addInterceptorLast(requestInterceptor); return builder; } @Override protected HttpAsyncClientBuilder configureHttpClient(HttpAsyncClientBuilder builder) { builder.addInterceptorLast(requestInterceptor); return builder; } }; } else { factory = new JestClientFactory(); } factory.setHttpClientConfig(httpConfigBuilder.build()); client = factory.getObject(); } @PreDestroy public void close() { client.shutdownClient(); } @Lock(LockType.READ) @Produces @ApplicationScoped public JestClient produce() { LOGGER.log(Level.INFO, "Producing ElasticSearch rest client"); return client; } }
eplmp-server/eplmp-server-ejb/src/main/java/org/polarsys/eplmp/server/indexer/IndexerClientProducer.java
/******************************************************************************* * Copyright (c) 2017 DocDoku. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * DocDoku - initial API and implementation *******************************************************************************/ package org.polarsys.eplmp.server.indexer; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.internal.StaticCredentialsProvider; import io.searchbox.client.JestClient; import io.searchbox.client.JestClientFactory; import io.searchbox.client.config.HttpClientConfig; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import vc.inreach.aws.request.AWSSigner; import vc.inreach.aws.request.AWSSigningRequestInterceptor; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Singleton; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.inject.Inject; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.logging.Level; import java.util.logging.Logger; @Singleton(name = "IndexerClientProducer") public class IndexerClientProducer { private static final Logger LOGGER = Logger.getLogger(IndexerClientProducer.class.getName()); private JestClient client; @Inject private IndexerConfigManager config; @PostConstruct public void open() { LOGGER.log(Level.INFO, "Create Elasticsearch client"); String serverUri = config.getServerUri(); String username = config.getUserName(); String password = config.getPassword(); String awsService = config.getAWSService(); String awsRegion = config.getAWSRegion(); String awsAccessKey = config.getAWSAccessKey(); String awsSecretKey = config.getAWSSecretKey(); HttpClientConfig.Builder httpConfigBuilder = new HttpClientConfig.Builder(serverUri) .multiThreaded(true) .defaultMaxTotalConnectionPerRoute(8); if (username != null && password != null) httpConfigBuilder.defaultCredentials(username, password); JestClientFactory factory; if (awsService != null && awsRegion != null && awsAccessKey != null && awsSecretKey != null) { final StaticCredentialsProvider staticCredentialsProvider = new StaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey)); final AWSSigner awsSigner = new AWSSigner(staticCredentialsProvider, awsRegion, awsService, () -> LocalDateTime.now(ZoneOffset.UTC)); final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner); factory = new JestClientFactory() { @Override protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) { builder.addInterceptorLast(requestInterceptor); return builder; } @Override protected HttpAsyncClientBuilder configureHttpClient(HttpAsyncClientBuilder builder) { builder.addInterceptorLast(requestInterceptor); return builder; } }; } else { factory = new JestClientFactory(); } factory.setHttpClientConfig(httpConfigBuilder.build()); client = factory.getObject(); } @PreDestroy public void close() { client.shutdownClient(); } @Lock(LockType.READ) @Produces @ApplicationScoped public JestClient produce() { LOGGER.log(Level.INFO, "Producing Elasticsearch rest client"); return client; } }
ES : Use DefaultAWSCredentialsProviderChain when no credentials are supplied
eplmp-server/eplmp-server-ejb/src/main/java/org/polarsys/eplmp/server/indexer/IndexerClientProducer.java
ES : Use DefaultAWSCredentialsProviderChain when no credentials are supplied
<ide><path>plmp-server/eplmp-server-ejb/src/main/java/org/polarsys/eplmp/server/indexer/IndexerClientProducer.java <ide> /******************************************************************************* <del> * Copyright (c) 2017 DocDoku. <del> * All rights reserved. This program and the accompanying materials <del> * are made available under the terms of the Eclipse Public License v1.0 <del> * which accompanies this distribution, and is available at <del> * http://www.eclipse.org/legal/epl-v10.html <del> * <del> * Contributors: <del> * DocDoku - initial API and implementation <del> *******************************************************************************/ <add> * Copyright (c) 2017 DocDoku. <add> * All rights reserved. This program and the accompanying materials <add> * are made available under the terms of the Eclipse Public License v1.0 <add> * which accompanies this distribution, and is available at <add> * http://www.eclipse.org/legal/epl-v10.html <add> * <p> <add> * Contributors: <add> * DocDoku - initial API and implementation <add> *******************************************************************************/ <ide> package org.polarsys.eplmp.server.indexer; <ide> <del>import com.amazonaws.auth.BasicAWSCredentials; <add>import com.amazonaws.auth.*; <add>import com.amazonaws.auth.profile.ProfileCredentialsProvider; <ide> import com.amazonaws.internal.StaticCredentialsProvider; <ide> import io.searchbox.client.JestClient; <ide> import io.searchbox.client.JestClientFactory; <ide> httpConfigBuilder.defaultCredentials(username, password); <ide> <ide> JestClientFactory factory; <del> if (awsService != null && awsRegion != null && awsAccessKey != null && awsSecretKey != null) { <ide> <del> final StaticCredentialsProvider staticCredentialsProvider = new StaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey)); <del> final AWSSigner awsSigner = new AWSSigner(staticCredentialsProvider, awsRegion, awsService, () -> LocalDateTime.now(ZoneOffset.UTC)); <add> if (awsService != null && awsRegion != null) { <add> <add> final AWSCredentialsProviderChain providerChain; <add> <add> if (awsAccessKey != null && awsSecretKey != null) { <add> providerChain = new AWSCredentialsProviderChain( <add> new AWSStaticCredentialsProvider( <add> new BasicAWSCredentials(awsAccessKey, awsSecretKey) <add> ) <add> ); <add> } else { <add> providerChain = new DefaultAWSCredentialsProviderChain(); <add> } <add> <add> final AWSSigner awsSigner = new AWSSigner(providerChain, awsRegion, awsService, () -> LocalDateTime.now(ZoneOffset.UTC)); <ide> final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner); <ide> <ide> factory = new JestClientFactory() { <ide> @Produces <ide> @ApplicationScoped <ide> public JestClient produce() { <del> LOGGER.log(Level.INFO, "Producing Elasticsearch rest client"); <add> LOGGER.log(Level.INFO, "Producing ElasticSearch rest client"); <ide> return client; <ide> } <ide>
Java
lgpl-2.1
b02b6f7d5d5cd76c71c5a2a293ca97783cf3cef9
0
deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ Occam Labs UG (haftungsbeschränkt) Godesberger Allee 139, 53175 Bonn Germany http://www.occamlabs.de/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.layer.persistence.tile; import static org.deegree.commons.xml.jaxb.JAXBUtils.unmarshall; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.config.ResourceInitException; import org.deegree.commons.config.ResourceManager; import org.deegree.layer.Layer; import org.deegree.layer.persistence.LayerStoreProvider; import org.deegree.layer.persistence.MultipleLayerStore; import org.deegree.layer.persistence.tile.jaxb.TileLayerType; import org.deegree.layer.persistence.tile.jaxb.TileLayers; import org.deegree.tile.persistence.TileStoreManager; /** * <code>TileLayerProvider</code> * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author: mschneider $ * * @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $ */ public class TileLayerProvider implements LayerStoreProvider { private static final URL SCHEMA = TileLayerProvider.class.getResource( "/META-INF/schemas/layers/tile/3.2.0/tile.xsd" ); private DeegreeWorkspace workspace; @Override public void init( DeegreeWorkspace workspace ) { this.workspace = workspace; } @Override public MultipleLayerStore create( URL configUrl ) throws ResourceInitException { try { TileLayers cfg = (TileLayers) unmarshall( "org.deegree.layer.persistence.tile.jaxb", SCHEMA, configUrl, workspace ); Map<String, Layer> map = new HashMap<String, Layer>(); TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); TileLayerBuilder builder = new TileLayerBuilder( mgr ); for ( TileLayerType lay : cfg.getTileLayer() ) { TileLayer l = builder.createLayer( lay ); map.put( l.getMetadata().getName(), l ); } return new MultipleLayerStore( map ); } catch ( Throwable e ) { throw new ResourceInitException( "Unable to create tile layer store.", e ); } } @SuppressWarnings("unchecked") @Override public Class<? extends ResourceManager>[] getDependencies() { return new Class[] { TileStoreManager.class }; } @Override public String getConfigNamespace() { return "http://www.deegree.org/layers/tile"; } @Override public URL getConfigSchema() { return SCHEMA; } }
deegree-layers/deegree-layers-tile/src/main/java/org/deegree/layer/persistence/tile/TileLayerProvider.java
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ Occam Labs UG (haftungsbeschränkt) Godesberger Allee 139, 53175 Bonn Germany http://www.occamlabs.de/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.layer.persistence.tile; import static org.deegree.commons.ows.metadata.DescriptionConverter.fromJaxb; import static org.deegree.commons.xml.jaxb.JAXBUtils.unmarshall; import static org.deegree.geometry.metadata.SpatialMetadataConverter.fromJaxb; import static org.slf4j.LoggerFactory.getLogger; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.config.ResourceInitException; import org.deegree.commons.config.ResourceManager; import org.deegree.commons.ows.metadata.Description; import org.deegree.commons.utils.DoublePair; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.geometry.Envelope; import org.deegree.geometry.metadata.SpatialMetadata; import org.deegree.layer.Layer; import org.deegree.layer.config.ConfigUtils; import org.deegree.layer.metadata.LayerMetadata; import org.deegree.layer.persistence.LayerStoreProvider; import org.deegree.layer.persistence.MultipleLayerStore; import org.deegree.layer.persistence.base.jaxb.ScaleDenominatorsType; import org.deegree.layer.persistence.tile.jaxb.TileLayerType; import org.deegree.layer.persistence.tile.jaxb.TileLayers; import org.deegree.tile.TileDataSet; import org.deegree.tile.persistence.TileStore; import org.deegree.tile.persistence.TileStoreManager; import org.slf4j.Logger; /** * <code>TileLayerProvider</code> * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author: mschneider $ * * @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $ */ public class TileLayerProvider implements LayerStoreProvider { private static final Logger LOG = getLogger( TileLayerProvider.class ); private static final URL SCHEMA = TileLayerProvider.class.getResource( "/META-INF/schemas/layers/tile/3.2.0/tile.xsd" ); private DeegreeWorkspace workspace; @Override public void init( DeegreeWorkspace workspace ) { this.workspace = workspace; } private TileLayer createLayer( TileLayerType cfg ) throws ResourceInitException { TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); List<TileDataSet> datasets = new ArrayList<TileDataSet>(); Envelope envelope = null; Set<ICRS> crsSet = new LinkedHashSet<ICRS>(); for ( TileLayerType.TileDataSet tds : cfg.getTileDataSet() ) { String id = tds.getTileStoreId(); TileStore store = mgr.get( id ); if ( store == null ) { LOG.warn( "Tile store with id {} was not available, skipping tile data set.", id ); continue; } String tdsId = tds.getValue(); TileDataSet dataset = store.getTileDataSet( tdsId ); if ( dataset == null ) { LOG.warn( "Tile data set with id {} not found in tile store {}, skipping.", tdsId, id ); continue; } datasets.add( dataset ); SpatialMetadata smd = dataset.getTileMatrixSet().getSpatialMetadata(); crsSet.addAll( smd.getCoordinateSystems() ); Envelope env = smd.getEnvelope(); if ( envelope == null ) { envelope = env; } else { envelope = envelope.merge( env ); } } SpatialMetadata smd = fromJaxb( cfg.getEnvelope(), cfg.getCRS() ); if ( smd.getEnvelope() == null ) { smd.setEnvelope( envelope ); } if ( smd.getCoordinateSystems().isEmpty() ) { smd.getCoordinateSystems().addAll( crsSet ); } Description desc = fromJaxb( cfg.getTitle(), cfg.getAbstract(), cfg.getKeywords() ); LayerMetadata md = new LayerMetadata( cfg.getName(), desc, smd ); md.setMapOptions( ConfigUtils.parseLayerOptions( cfg.getLayerOptions() ) ); ScaleDenominatorsType sd = cfg.getScaleDenominators(); if ( sd != null ) { DoublePair p = new DoublePair( sd.getMin(), sd.getMax() ); md.setScaleDenominators( p ); } md.setMetadataId( cfg.getMetadataSetId() ); return new TileLayer( md, datasets ); } @Override public MultipleLayerStore create( URL configUrl ) throws ResourceInitException { try { TileLayers cfg = (TileLayers) unmarshall( "org.deegree.layer.persistence.tile.jaxb", SCHEMA, configUrl, workspace ); Map<String, Layer> map = new HashMap<String, Layer>(); for ( TileLayerType lay : cfg.getTileLayer() ) { TileLayer l = createLayer( lay ); map.put( l.getMetadata().getName(), l ); } return new MultipleLayerStore( map ); } catch ( Throwable e ) { throw new ResourceInitException( "Unable to create tile layer store.", e ); } } @SuppressWarnings("unchecked") @Override public Class<? extends ResourceManager>[] getDependencies() { return new Class[] { TileStoreManager.class }; } @Override public String getConfigNamespace() { return "http://www.deegree.org/layers/tile"; } @Override public URL getConfigSchema() { return SCHEMA; } }
factored out layer building
deegree-layers/deegree-layers-tile/src/main/java/org/deegree/layer/persistence/tile/TileLayerProvider.java
factored out layer building
<ide><path>eegree-layers/deegree-layers-tile/src/main/java/org/deegree/layer/persistence/tile/TileLayerProvider.java <ide> ----------------------------------------------------------------------------*/ <ide> package org.deegree.layer.persistence.tile; <ide> <del>import static org.deegree.commons.ows.metadata.DescriptionConverter.fromJaxb; <ide> import static org.deegree.commons.xml.jaxb.JAXBUtils.unmarshall; <del>import static org.deegree.geometry.metadata.SpatialMetadataConverter.fromJaxb; <del>import static org.slf4j.LoggerFactory.getLogger; <ide> <ide> import java.net.URL; <del>import java.util.ArrayList; <ide> import java.util.HashMap; <del>import java.util.LinkedHashSet; <del>import java.util.List; <ide> import java.util.Map; <del>import java.util.Set; <ide> <ide> import org.deegree.commons.config.DeegreeWorkspace; <ide> import org.deegree.commons.config.ResourceInitException; <ide> import org.deegree.commons.config.ResourceManager; <del>import org.deegree.commons.ows.metadata.Description; <del>import org.deegree.commons.utils.DoublePair; <del>import org.deegree.cs.coordinatesystems.ICRS; <del>import org.deegree.geometry.Envelope; <del>import org.deegree.geometry.metadata.SpatialMetadata; <ide> import org.deegree.layer.Layer; <del>import org.deegree.layer.config.ConfigUtils; <del>import org.deegree.layer.metadata.LayerMetadata; <ide> import org.deegree.layer.persistence.LayerStoreProvider; <ide> import org.deegree.layer.persistence.MultipleLayerStore; <del>import org.deegree.layer.persistence.base.jaxb.ScaleDenominatorsType; <ide> import org.deegree.layer.persistence.tile.jaxb.TileLayerType; <ide> import org.deegree.layer.persistence.tile.jaxb.TileLayers; <del>import org.deegree.tile.TileDataSet; <del>import org.deegree.tile.persistence.TileStore; <ide> import org.deegree.tile.persistence.TileStoreManager; <del>import org.slf4j.Logger; <ide> <ide> /** <ide> * <code>TileLayerProvider</code> <ide> <ide> public class TileLayerProvider implements LayerStoreProvider { <ide> <del> private static final Logger LOG = getLogger( TileLayerProvider.class ); <del> <ide> private static final URL SCHEMA = TileLayerProvider.class.getResource( "/META-INF/schemas/layers/tile/3.2.0/tile.xsd" ); <ide> <ide> private DeegreeWorkspace workspace; <ide> this.workspace = workspace; <ide> } <ide> <del> private TileLayer createLayer( TileLayerType cfg ) <del> throws ResourceInitException { <del> TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); <del> List<TileDataSet> datasets = new ArrayList<TileDataSet>(); <del> Envelope envelope = null; <del> Set<ICRS> crsSet = new LinkedHashSet<ICRS>(); <del> for ( TileLayerType.TileDataSet tds : cfg.getTileDataSet() ) { <del> String id = tds.getTileStoreId(); <del> TileStore store = mgr.get( id ); <del> if ( store == null ) { <del> LOG.warn( "Tile store with id {} was not available, skipping tile data set.", id ); <del> continue; <del> } <del> <del> String tdsId = tds.getValue(); <del> <del> TileDataSet dataset = store.getTileDataSet( tdsId ); <del> if ( dataset == null ) { <del> LOG.warn( "Tile data set with id {} not found in tile store {}, skipping.", tdsId, id ); <del> continue; <del> } <del> <del> datasets.add( dataset ); <del> <del> SpatialMetadata smd = dataset.getTileMatrixSet().getSpatialMetadata(); <del> crsSet.addAll( smd.getCoordinateSystems() ); <del> Envelope env = smd.getEnvelope(); <del> if ( envelope == null ) { <del> envelope = env; <del> } else { <del> envelope = envelope.merge( env ); <del> } <del> } <del> <del> SpatialMetadata smd = fromJaxb( cfg.getEnvelope(), cfg.getCRS() ); <del> if ( smd.getEnvelope() == null ) { <del> smd.setEnvelope( envelope ); <del> } <del> if ( smd.getCoordinateSystems().isEmpty() ) { <del> smd.getCoordinateSystems().addAll( crsSet ); <del> } <del> Description desc = fromJaxb( cfg.getTitle(), cfg.getAbstract(), cfg.getKeywords() ); <del> LayerMetadata md = new LayerMetadata( cfg.getName(), desc, smd ); <del> md.setMapOptions( ConfigUtils.parseLayerOptions( cfg.getLayerOptions() ) ); <del> ScaleDenominatorsType sd = cfg.getScaleDenominators(); <del> if ( sd != null ) { <del> DoublePair p = new DoublePair( sd.getMin(), sd.getMax() ); <del> md.setScaleDenominators( p ); <del> } <del> md.setMetadataId( cfg.getMetadataSetId() ); <del> return new TileLayer( md, datasets ); <del> } <del> <ide> @Override <ide> public MultipleLayerStore create( URL configUrl ) <ide> throws ResourceInitException { <ide> TileLayers cfg = (TileLayers) unmarshall( "org.deegree.layer.persistence.tile.jaxb", SCHEMA, configUrl, <ide> workspace ); <ide> Map<String, Layer> map = new HashMap<String, Layer>(); <add> TileStoreManager mgr = workspace.getSubsystemManager( TileStoreManager.class ); <add> TileLayerBuilder builder = new TileLayerBuilder( mgr ); <ide> for ( TileLayerType lay : cfg.getTileLayer() ) { <del> TileLayer l = createLayer( lay ); <add> TileLayer l = builder.createLayer( lay ); <ide> map.put( l.getMetadata().getName(), l ); <ide> } <ide> return new MultipleLayerStore( map );
JavaScript
mit
70bde8f80e3f5e1370605ed4bbeb28d23a608f28
0
benjdj6/timecrunch,benjdj6/timecrunch
var app = angular.module('timecrunch', ['ui.router']); app.config([ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: '/templates/home.html', controller: 'DashCtrl' }) .state('food', { url: '/food', templateUrl: '/templates/food.html', controller: 'ListCtrl', resolve: { foodPromise: ['foods', function(foods) { return foods.getFood(); }] } }) .state('recipes', { url: '/recipes', templateUrl: '/templates/recipes.html', controller: 'ListCtrl', resolve: { recipePromise: ['recipes', function(recipes) { return recipes.getAll(); }] } }) .state('recipeform', { url: '/recipes/form', templateUrl: '/templates/recipeform.html', controller: 'ListCtrl' }) .state('recipe', { url: '/recipes/{id}', templateUrl: '/templates/recipe.html', controller: 'RecipesCtrl', resolve: { recipe: ['$stateParams', 'recipes', function($stateParams, recipes) { return recipes.get($stateParams.id); }] } }) .state('login', { url: '/login', templateUrl: '/templates/login.html', controller: 'AuthCtrl', onEnter: ['$state', 'auth', function($state, auth) { if(auth.isLoggedIn()) { $state.go('home'); } }] }) .state('register', { url: '/register', templateUrl: '/templates/register.html', controller: 'AuthCtrl', onEnter: ['$state', 'auth', function($state, auth) { if(auth.isLoggedIn()) { $state.go('home'); } }] }); $urlRouterProvider.otherwise('home'); }]); // Factory for auth handling all authorization and // user id related functions app.factory('auth', ['$http', '$window', function($http, $window) { var auth = {}; // save given token auth.saveToken = function(token) { $window.localStorage['time-crunch-token'] = token; }; // get token from localStorage auth.getToken = function() { return $window.localStorage['time-crunch-token']; }; // register user auth.register = function(user) { return $http.post('/register', user).then(function(data) { auth.saveToken(data.data.token); }); }; // login user save token auth.logIn = function(user) { return $http.post('/login', user).then(function(data) { auth.saveToken(data.data.token); }); }; // logout a user and delete token auth.logOut = function() { $window.localStorage.removeItem('time-crunch-token'); }; // check if user is logged in auth.isLoggedIn = function() { var token = auth.getToken(); if(token) { var payload = JSON.parse($window.atob(token.split('.')[1])); return payload.exp > Date.now() / 1000; } else { return false; } }; // returns currently logged in username auth.currentUser = function() { if(auth.isLoggedIn()) { var token = auth.getToken(); var payload = JSON.parse($window.atob(token.split('.')[1])); return payload.username; } }; return auth; }]); // Factory for foods handling all related functions app.factory('foods', ['$http', '$state', 'auth', function($http, $state, auth) { var o = { foods: [] }; // Load food list for the current user o.getFood = function() { if(auth.isLoggedIn()) { return $http.get('/food', { headers: {Authorization: 'Bearer ' + auth.getToken()} }).then(function(data) { angular.copy(data.data, o.foods); }); } $state.go('login'); }; // Add a food to a user's food list o.create = function(food) { return $http.post('/food', food, { headers: {Authorization: 'Bearer ' + auth.getToken()} }).then(function(data) { o.getFood(); }); }; // Remove a food from a user's food list o.delete = function(food) { return $http.delete('/food/' + food._id).then(function(data) { o.getFood(); }); }; return o; }]); // Factory for recipes handling related functions app.factory('recipes', ['$http', 'auth', function($http, auth) { var o = { recipes: [] }; // Get all recipes o.getAll = function() { return $http.get('/recipes').then(function(data) { angular.copy(data.data, o.recipes); }); }; // Get a specific recipe o.get = function(id) { for(i = 0; i < o.recipes.length; ++i) { if(o.recipes[i]._id == id) { return o.recipes[i]; } } }; // Create a new recipe o.create = function(recipe) { return $http.post('/recipes', recipe, { headers: {Authorization: 'Bearer ' + auth.getToken()} }).then(function(data) { o.getAll(); }); }; // Update a recipe o.update = function(recipe) { return $http.put('/recipes/' + recipe._id, recipe, { headers: {Authorization: 'Bearer ' auth.getToken()} }).then(function(data) { o.getAll(); }); }; // Delete a recipe o.delete = function(recipe) { return $http.delete('/recipes/' + recipe._id).then(function(data) { o.getAll(); }); }; return o; }]); // Controller for dashboard on home/index app.controller('DashCtrl', [ '$scope', 'foods', function($scope, foods){ $scope.foods = foods.foods; }]); // Controller for recipe and food lists app.controller('ListCtrl', [ '$scope', '$state', 'auth', 'foods', 'recipes', function($scope, $state, auth, foods, recipes) { $scope.foods = foods.foods; $scope.recipes = recipes.recipes; $scope.ingredients = []; $scope.isLoggedIn = auth.isLoggedIn; $scope.categories = [ "Baking", "Dairy", "Fruit", "Herb/Spice", "Meat", "Sauce", "Vegetable", "Other-Ingredient", "Other-Food", "Other-Produce" ]; $scope.sortBy = ["sellBy", "name"]; $scope.filterCat = ""; $scope.filter = function() { return function(item) { if($scope.filterCat == "" || !$scope.filterCat || $scope.filterCat == item.category) { return true; } return false; }; }; // Add a new food $scope.addFood = function() { // Make sure food name is valid if(!$scope.name || $scope.name == '') { alert("Please fill in the name field"); return; } // If sell by was left blank, set it to 2 years from now if(!$scope.sellBy) { $scope.sellBy = new Date(); $scope.sellBy.setDate($scope.sellBy.getDate() + 730); } foods.create({ name: $scope.name, sellBy: $scope.sellBy, amount: $scope.amount, units: $scope.units, category: $scope.category }); }; // Remove a food $scope.removeFood = function(food) { foods.delete(food); }; // Add a new recipe $scope.addRecipe = function() { //Check that the recipe has a name, ingredients, and instructions if(!$scope.name || $scope.name == '' || !$scope.ingredients) { alert("Please make sure all fields are filled out"); return; } if(!$scope.instructions && !$scope.link) { alert("Please provide either instructions or a link to the full recipe"); return; } recipes.create({ name: $scope.name, ingredients: $scope.ingredients, prepTime: $scope.prepTime, link: $scope.link, instructions: $scope.instructions }).then(function success() { // Return to the recipe list $state.go('recipes'); }, function failure(error) { // Show error message $scope.error = error.data; }); }; // Add an ingredient to a recipe $scope.addIngredient = function() { // Build the ingredient string var ing = $scope.ing_name.concat(" - " + $scope.ing_amount); if($scope.ing_unit) { ing = ing.concat(" " + $scope.ing_unit); } // Check if the ingredient is a duplicate if($scope.ingredients.indexOf(ing) > -1) { alert("Duplicate ingredients! Please change your entry."); } else { ($scope.ingredients).push(ing); } }; // Remove an ingredient from a recipe $scope.removeIngredient = function(ingredient) { if($scope.ingredients.length == 1) { $scope.ingredients = []; } else { var i = $scope.ingredients.indexOf(ingredient); $scope.ingredients.splice(i, 1); } }; }]); // Controller for recipe details page app.controller('RecipesCtrl', [ '$scope', '$state', 'recipe', 'recipes', 'auth', function($scope, $state, recipe, recipes, auth){ $scope.recipe = recipe; $scope.currentUser = auth.currentUser(); // Determines if a user is allowed to edit this // recipe $scope.canEdit = function() { return recipe.author == $scope.currentUser; } // Deletes the recipe $scope.deleteRecipe = function() { // Make sure user is authorized if($scope.canEdit()) { recipes.delete(recipe); $state.go('recipes'); } else { // If not allowed show an alert alert('You cannot delete this recipe!'); } } }]); // Controller for logging in and registering app.controller('AuthCtrl', [ '$scope', '$state', 'auth', function($scope, $state, auth) { $scope.user = {}; // Registers a new user $scope.register = function() { auth.register($scope.user).then(function success() { // Go to dashboard once logged in $state.go('home'); }, function failure(error) { // Show error message $scope.error = error.data; }); }; // Starts a new login session $scope.logIn = function() { auth.logIn($scope.user).then(function success() { // Go to dashboard once logged in $state.go('home'); }, function failure(error) { // Show error message $scope.error = error.data; }); }; }]); // Controller for dashboard on home/index app.controller('NavCtrl', [ '$scope', 'auth', function($scope, auth){ $scope.isLoggedIn = auth.isLoggedIn; $scope.currentUser = auth.currentUser; $scope.logOut = auth.logOut; }]);
public/javascripts/angularApp.js
var app = angular.module('timecrunch', ['ui.router']); app.config([ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: '/templates/home.html', controller: 'DashCtrl' }) .state('food', { url: '/food', templateUrl: '/templates/food.html', controller: 'ListCtrl', resolve: { foodPromise: ['foods', function(foods) { return foods.getFood(); }] } }) .state('recipes', { url: '/recipes', templateUrl: '/templates/recipes.html', controller: 'ListCtrl', resolve: { recipePromise: ['recipes', function(recipes) { return recipes.getAll(); }] } }) .state('recipeform', { url: '/recipes/form', templateUrl: '/templates/recipeform.html', controller: 'ListCtrl' }) .state('recipe', { url: '/recipes/{id}', templateUrl: '/templates/recipe.html', controller: 'RecipesCtrl', resolve: { recipe: ['$stateParams', 'recipes', function($stateParams, recipes) { return recipes.get($stateParams.id); }] } }) .state('login', { url: '/login', templateUrl: '/templates/login.html', controller: 'AuthCtrl', onEnter: ['$state', 'auth', function($state, auth) { if(auth.isLoggedIn()) { $state.go('home'); } }] }) .state('register', { url: '/register', templateUrl: '/templates/register.html', controller: 'AuthCtrl', onEnter: ['$state', 'auth', function($state, auth) { if(auth.isLoggedIn()) { $state.go('home'); } }] }); $urlRouterProvider.otherwise('home'); }]); // Factory for auth handling all authorization and // user id related functions app.factory('auth', ['$http', '$window', function($http, $window) { var auth = {}; // save given token auth.saveToken = function(token) { $window.localStorage['time-crunch-token'] = token; }; // get token from localStorage auth.getToken = function() { return $window.localStorage['time-crunch-token']; }; // register user auth.register = function(user) { return $http.post('/register', user).then(function(data) { auth.saveToken(data.data.token); }); }; // login user save token auth.logIn = function(user) { return $http.post('/login', user).then(function(data) { auth.saveToken(data.data.token); }); }; // logout a user and delete token auth.logOut = function() { $window.localStorage.removeItem('time-crunch-token'); }; // check if user is logged in auth.isLoggedIn = function() { var token = auth.getToken(); if(token) { var payload = JSON.parse($window.atob(token.split('.')[1])); return payload.exp > Date.now() / 1000; } else { return false; } }; // returns currently logged in username auth.currentUser = function() { if(auth.isLoggedIn()) { var token = auth.getToken(); var payload = JSON.parse($window.atob(token.split('.')[1])); return payload.username; } }; return auth; }]); // Factory for foods handling all related functions app.factory('foods', ['$http', '$state', 'auth', function($http, $state, auth) { var o = { foods: [] }; // Load food list for the current user o.getFood = function() { if(auth.isLoggedIn()) { return $http.get('/food', { headers: {Authorization: 'Bearer ' + auth.getToken()} }).then(function(data) { angular.copy(data.data, o.foods); }); } $state.go('login'); }; // Add a food to a user's food list o.create = function(food) { return $http.post('/food', food, { headers: {Authorization: 'Bearer ' + auth.getToken()} }).then(function(data) { o.getFood(); }); }; // Remove a food from a user's food list o.delete = function(food) { return $http.delete('/food/' + food._id).then(function(data) { o.getFood(); }); }; return o; }]); // Factory for recipes handling related functions app.factory('recipes', ['$http', 'auth', function($http, auth) { var o = { recipes: [] }; // Get all recipes o.getAll = function() { return $http.get('/recipes').then(function(data) { angular.copy(data.data, o.recipes); }); }; // Get a specific recipe o.get = function(id) { for(i = 0; i < o.recipes.length; ++i) { if(o.recipes[i]._id == id) { return o.recipes[i]; } } }; // Create a new recipe o.create = function(recipe) { return $http.post('/recipes', recipe, { headers: {Authorization: 'Bearer ' + auth.getToken()} }).then(function(data) { o.getAll(); }); }; // Delete a recipe o.delete = function(recipe) { return $http.delete('/recipes/' + recipe._id).then(function(data) { o.getAll(); }); }; return o; }]); // Controller for dashboard on home/index app.controller('DashCtrl', [ '$scope', 'foods', function($scope, foods){ $scope.foods = foods.foods; }]); // Controller for recipe and food lists app.controller('ListCtrl', [ '$scope', '$state', 'auth', 'foods', 'recipes', function($scope, $state, auth, foods, recipes) { $scope.foods = foods.foods; $scope.recipes = recipes.recipes; $scope.ingredients = []; $scope.isLoggedIn = auth.isLoggedIn; $scope.categories = [ "Baking", "Dairy", "Fruit", "Herb/Spice", "Meat", "Sauce", "Vegetable", "Other-Ingredient", "Other-Food", "Other-Produce" ]; $scope.sortBy = ["sellBy", "name"]; $scope.filterCat = ""; $scope.filter = function() { return function(item) { if($scope.filterCat == "" || !$scope.filterCat || $scope.filterCat == item.category) { return true; } return false; }; }; // Add a new food $scope.addFood = function() { // Make sure food name is valid if(!$scope.name || $scope.name == '') { alert("Please fill in the name field"); return; } // If sell by was left blank, set it to 2 years from now if(!$scope.sellBy) { $scope.sellBy = new Date(); $scope.sellBy.setDate($scope.sellBy.getDate() + 730); } foods.create({ name: $scope.name, sellBy: $scope.sellBy, amount: $scope.amount, units: $scope.units, category: $scope.category }); }; // Remove a food $scope.removeFood = function(food) { foods.delete(food); }; // Add a new recipe $scope.addRecipe = function() { //Check that the recipe has a name, ingredients, and instructions if(!$scope.name || $scope.name == '' || !$scope.ingredients) { alert("Please make sure all fields are filled out"); return; } if(!$scope.instructions && !$scope.link) { alert("Please provide either instructions or a link to the full recipe"); return; } recipes.create({ name: $scope.name, ingredients: $scope.ingredients, prepTime: $scope.prepTime, link: $scope.link, instructions: $scope.instructions }).then(function success() { // Return to the recipe list $state.go('recipes'); }, function failure(error) { // Show error message $scope.error = error.data; }); }; // Add an ingredient to a recipe $scope.addIngredient = function() { // Build the ingredient string var ing = $scope.ing_name.concat(" - " + $scope.ing_amount); if($scope.ing_unit) { ing = ing.concat(" " + $scope.ing_unit); } // Check if the ingredient is a duplicate if($scope.ingredients.indexOf(ing) > -1) { alert("Duplicate ingredients! Please change your entry."); } else { ($scope.ingredients).push(ing); } }; // Remove an ingredient from a recipe $scope.removeIngredient = function(ingredient) { if($scope.ingredients.length == 1) { $scope.ingredients = []; } else { var i = $scope.ingredients.indexOf(ingredient); $scope.ingredients.splice(i, 1); } }; }]); // Controller for recipe details page app.controller('RecipesCtrl', [ '$scope', '$state', 'recipe', 'recipes', 'auth', function($scope, $state, recipe, recipes, auth){ $scope.recipe = recipe; $scope.currentUser = auth.currentUser(); // Determines if a user is allowed to edit this // recipe $scope.canEdit = function() { return recipe.author == $scope.currentUser; } // Deletes the recipe $scope.deleteRecipe = function() { // Make sure user is authorized if($scope.canEdit()) { recipes.delete(recipe); $state.go('recipes'); } else { // If not allowed show an alert alert('You cannot delete this recipe!'); } } }]); // Controller for logging in and registering app.controller('AuthCtrl', [ '$scope', '$state', 'auth', function($scope, $state, auth) { $scope.user = {}; // Registers a new user $scope.register = function() { auth.register($scope.user).then(function success() { // Go to dashboard once logged in $state.go('home'); }, function failure(error) { // Show error message $scope.error = error.data; }); }; // Starts a new login session $scope.logIn = function() { auth.logIn($scope.user).then(function success() { // Go to dashboard once logged in $state.go('home'); }, function failure(error) { // Show error message $scope.error = error.data; }); }; }]); // Controller for dashboard on home/index app.controller('NavCtrl', [ '$scope', 'auth', function($scope, auth){ $scope.isLoggedIn = auth.isLoggedIn; $scope.currentUser = auth.currentUser; $scope.logOut = auth.logOut; }]);
Added update function to recipe factory
public/javascripts/angularApp.js
Added update function to recipe factory
<ide><path>ublic/javascripts/angularApp.js <ide> o.create = function(recipe) { <ide> return $http.post('/recipes', recipe, { <ide> headers: {Authorization: 'Bearer ' + auth.getToken()} <add> }).then(function(data) { <add> o.getAll(); <add> }); <add> }; <add> <add> // Update a recipe <add> o.update = function(recipe) { <add> return $http.put('/recipes/' + recipe._id, recipe, { <add> headers: {Authorization: 'Bearer ' auth.getToken()} <ide> }).then(function(data) { <ide> o.getAll(); <ide> });
Java
apache-2.0
ab7164f20ebcc8d26b0e7de225e213a7266b96bd
0
googleapis/java-apigee-connect,googleapis/java-apigee-connect,googleapis/java-apigee-connect
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.apigeeconnect.v1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.apigeeconnect.v1.stub.ConnectionServiceStub; import com.google.cloud.apigeeconnect.v1.stub.ConnectionServiceStubSettings; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service Interface for the Apigee Connect connection management APIs. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * EndpointName parent = EndpointName.of("[PROJECT]", "[ENDPOINT]"); * for (Connection element : connectionServiceClient.listConnections(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * <p>Note: close() needs to be called on the ConnectionServiceClient object to clean up resources * such as threads. In the example above, try-with-resources is used, which automatically calls * close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of ConnectionServiceSettings to * create(). For example: * * <p>To customize credentials: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * ConnectionServiceSettings connectionServiceSettings = * ConnectionServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * ConnectionServiceClient connectionServiceClient = * ConnectionServiceClient.create(connectionServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * ConnectionServiceSettings connectionServiceSettings = * ConnectionServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * ConnectionServiceClient connectionServiceClient = * ConnectionServiceClient.create(connectionServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class ConnectionServiceClient implements BackgroundResource { private final ConnectionServiceSettings settings; private final ConnectionServiceStub stub; /** Constructs an instance of ConnectionServiceClient with default settings. */ public static final ConnectionServiceClient create() throws IOException { return create(ConnectionServiceSettings.newBuilder().build()); } /** * Constructs an instance of ConnectionServiceClient, using the given settings. The channels are * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ConnectionServiceClient create(ConnectionServiceSettings settings) throws IOException { return new ConnectionServiceClient(settings); } /** * Constructs an instance of ConnectionServiceClient, using the given stub for making calls. This * is for advanced usage - prefer using create(ConnectionServiceSettings). */ public static final ConnectionServiceClient create(ConnectionServiceStub stub) { return new ConnectionServiceClient(stub); } /** * Constructs an instance of ConnectionServiceClient, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected ConnectionServiceClient(ConnectionServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((ConnectionServiceStubSettings) settings.getStubSettings()).createStub(); } protected ConnectionServiceClient(ConnectionServiceStub stub) { this.settings = null; this.stub = stub; } public final ConnectionServiceSettings getSettings() { return settings; } public ConnectionServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * EndpointName parent = EndpointName.of("[PROJECT]", "[ENDPOINT]"); * for (Connection element : connectionServiceClient.listConnections(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. Parent name of the form: `projects/{project_number or * project_id}/endpoints/{endpoint}`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListConnectionsPagedResponse listConnections(EndpointName parent) { ListConnectionsRequest request = ListConnectionsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listConnections(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * String parent = EndpointName.of("[PROJECT]", "[ENDPOINT]").toString(); * for (Connection element : connectionServiceClient.listConnections(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. Parent name of the form: `projects/{project_number or * project_id}/endpoints/{endpoint}`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListConnectionsPagedResponse listConnections(String parent) { ListConnectionsRequest request = ListConnectionsRequest.newBuilder().setParent(parent).build(); return listConnections(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * ListConnectionsRequest request = * ListConnectionsRequest.newBuilder() * .setParent(EndpointName.of("[PROJECT]", "[ENDPOINT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Connection element : connectionServiceClient.listConnections(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListConnectionsPagedResponse listConnections(ListConnectionsRequest request) { return listConnectionsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * ListConnectionsRequest request = * ListConnectionsRequest.newBuilder() * .setParent(EndpointName.of("[PROJECT]", "[ENDPOINT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Connection> future = * connectionServiceClient.listConnectionsPagedCallable().futureCall(request); * // Do something. * for (Connection element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListConnectionsRequest, ListConnectionsPagedResponse> listConnectionsPagedCallable() { return stub.listConnectionsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * ListConnectionsRequest request = * ListConnectionsRequest.newBuilder() * .setParent(EndpointName.of("[PROJECT]", "[ENDPOINT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListConnectionsResponse response = * connectionServiceClient.listConnectionsCallable().call(request); * for (Connection element : response.getConnectionsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListConnectionsRequest, ListConnectionsResponse> listConnectionsCallable() { return stub.listConnectionsCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListConnectionsPagedResponse extends AbstractPagedListResponse< ListConnectionsRequest, ListConnectionsResponse, Connection, ListConnectionsPage, ListConnectionsFixedSizeCollection> { public static ApiFuture<ListConnectionsPagedResponse> createAsync( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ApiFuture<ListConnectionsResponse> futureResponse) { ApiFuture<ListConnectionsPage> futurePage = ListConnectionsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListConnectionsPagedResponse(input), MoreExecutors.directExecutor()); } private ListConnectionsPagedResponse(ListConnectionsPage page) { super(page, ListConnectionsFixedSizeCollection.createEmptyCollection()); } } public static class ListConnectionsPage extends AbstractPage< ListConnectionsRequest, ListConnectionsResponse, Connection, ListConnectionsPage> { private ListConnectionsPage( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ListConnectionsResponse response) { super(context, response); } private static ListConnectionsPage createEmptyPage() { return new ListConnectionsPage(null, null); } @Override protected ListConnectionsPage createPage( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ListConnectionsResponse response) { return new ListConnectionsPage(context, response); } @Override public ApiFuture<ListConnectionsPage> createPageAsync( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ApiFuture<ListConnectionsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListConnectionsFixedSizeCollection extends AbstractFixedSizeCollection< ListConnectionsRequest, ListConnectionsResponse, Connection, ListConnectionsPage, ListConnectionsFixedSizeCollection> { private ListConnectionsFixedSizeCollection( List<ListConnectionsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListConnectionsFixedSizeCollection createEmptyCollection() { return new ListConnectionsFixedSizeCollection(null, 0); } @Override protected ListConnectionsFixedSizeCollection createCollection( List<ListConnectionsPage> pages, int collectionSize) { return new ListConnectionsFixedSizeCollection(pages, collectionSize); } } }
google-cloud-apigee-connect/src/main/java/com/google/cloud/apigeeconnect/v1/ConnectionServiceClient.java
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.apigeeconnect.v1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.apigeeconnect.v1.stub.ConnectionServiceStub; import com.google.cloud.apigeeconnect.v1.stub.ConnectionServiceStubSettings; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service Interface for the Apigee Connect connection management APIs. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * EndpointName parent = EndpointName.of("[PROJECT]", "[ENDPOINT]"); * for (Connection element : connectionServiceClient.listConnections(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * <p>Note: close() needs to be called on the ConnectionServiceClient object to clean up resources * such as threads. In the example above, try-with-resources is used, which automatically calls * close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of ConnectionServiceSettings to * create(). For example: * * <p>To customize credentials: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * ConnectionServiceSettings connectionServiceSettings = * ConnectionServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * ConnectionServiceClient connectionServiceClient = * ConnectionServiceClient.create(connectionServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * ConnectionServiceSettings connectionServiceSettings = * ConnectionServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * ConnectionServiceClient connectionServiceClient = * ConnectionServiceClient.create(connectionServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class ConnectionServiceClient implements BackgroundResource { private final ConnectionServiceSettings settings; private final ConnectionServiceStub stub; /** Constructs an instance of ConnectionServiceClient with default settings. */ public static final ConnectionServiceClient create() throws IOException { return create(ConnectionServiceSettings.newBuilder().build()); } /** * Constructs an instance of ConnectionServiceClient, using the given settings. The channels are * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ConnectionServiceClient create(ConnectionServiceSettings settings) throws IOException { return new ConnectionServiceClient(settings); } /** * Constructs an instance of ConnectionServiceClient, using the given stub for making calls. This * is for advanced usage - prefer using create(ConnectionServiceSettings). */ public static final ConnectionServiceClient create(ConnectionServiceStub stub) { return new ConnectionServiceClient(stub); } /** * Constructs an instance of ConnectionServiceClient, using the given settings. This is protected * so that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected ConnectionServiceClient(ConnectionServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((ConnectionServiceStubSettings) settings.getStubSettings()).createStub(); } protected ConnectionServiceClient(ConnectionServiceStub stub) { this.settings = null; this.stub = stub; } public final ConnectionServiceSettings getSettings() { return settings; } public ConnectionServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * EndpointName parent = EndpointName.of("[PROJECT]", "[ENDPOINT]"); * for (Connection element : connectionServiceClient.listConnections(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. Parent name of the form: `projects/{project_number or * project_id}/endpoints/{endpoint}`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListConnectionsPagedResponse listConnections(EndpointName parent) { ListConnectionsRequest request = ListConnectionsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listConnections(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * String parent = EndpointName.of("[PROJECT]", "[ENDPOINT]").toString(); * for (Connection element : connectionServiceClient.listConnections(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. Parent name of the form: `projects/{project_number or * project_id}/endpoints/{endpoint}`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListConnectionsPagedResponse listConnections(String parent) { ListConnectionsRequest request = ListConnectionsRequest.newBuilder().setParent(parent).build(); return listConnections(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * ListConnectionsRequest request = * ListConnectionsRequest.newBuilder() * .setParent(EndpointName.of("[PROJECT]", "[ENDPOINT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Connection element : connectionServiceClient.listConnections(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListConnectionsPagedResponse listConnections(ListConnectionsRequest request) { return listConnectionsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * ListConnectionsRequest request = * ListConnectionsRequest.newBuilder() * .setParent(EndpointName.of("[PROJECT]", "[ENDPOINT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Connection> future = * connectionServiceClient.listConnectionsPagedCallable().futureCall(request); * // Do something. * for (Connection element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListConnectionsRequest, ListConnectionsPagedResponse> listConnectionsPagedCallable() { return stub.listConnectionsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists connections that are currently active for the given Apigee Connect endpoint. * * <p>Sample code: * * <pre>{@code * // This snippet has been automatically generated for illustrative purposes only. * // It may require modifications to work in your environment. * try (ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.create()) { * ListConnectionsRequest request = * ListConnectionsRequest.newBuilder() * .setParent(EndpointName.of("[PROJECT]", "[ENDPOINT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListConnectionsResponse response = * connectionServiceClient.listConnectionsCallable().call(request); * for (Connection element : response.getResponsesList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListConnectionsRequest, ListConnectionsResponse> listConnectionsCallable() { return stub.listConnectionsCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListConnectionsPagedResponse extends AbstractPagedListResponse< ListConnectionsRequest, ListConnectionsResponse, Connection, ListConnectionsPage, ListConnectionsFixedSizeCollection> { public static ApiFuture<ListConnectionsPagedResponse> createAsync( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ApiFuture<ListConnectionsResponse> futureResponse) { ApiFuture<ListConnectionsPage> futurePage = ListConnectionsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListConnectionsPagedResponse(input), MoreExecutors.directExecutor()); } private ListConnectionsPagedResponse(ListConnectionsPage page) { super(page, ListConnectionsFixedSizeCollection.createEmptyCollection()); } } public static class ListConnectionsPage extends AbstractPage< ListConnectionsRequest, ListConnectionsResponse, Connection, ListConnectionsPage> { private ListConnectionsPage( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ListConnectionsResponse response) { super(context, response); } private static ListConnectionsPage createEmptyPage() { return new ListConnectionsPage(null, null); } @Override protected ListConnectionsPage createPage( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ListConnectionsResponse response) { return new ListConnectionsPage(context, response); } @Override public ApiFuture<ListConnectionsPage> createPageAsync( PageContext<ListConnectionsRequest, ListConnectionsResponse, Connection> context, ApiFuture<ListConnectionsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListConnectionsFixedSizeCollection extends AbstractFixedSizeCollection< ListConnectionsRequest, ListConnectionsResponse, Connection, ListConnectionsPage, ListConnectionsFixedSizeCollection> { private ListConnectionsFixedSizeCollection( List<ListConnectionsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListConnectionsFixedSizeCollection createEmptyCollection() { return new ListConnectionsFixedSizeCollection(null, 0); } @Override protected ListConnectionsFixedSizeCollection createCollection( List<ListConnectionsPage> pages, int collectionSize) { return new ListConnectionsFixedSizeCollection(pages, collectionSize); } } }
chore: Integrate new gapic-generator-java and rules_gapic (#177) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 454027580 Source-Link: https://github.com/googleapis/googleapis/commit/1b222777baa702e7135610355706570ed2b56318 Source-Link: https://github.com/googleapis/googleapis-gen/commit/e04cea20d0d12eb5c3bdb360a9e72b654edcb638 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZTA0Y2VhMjBkMGQxMmViNWMzYmRiMzYwYTllNzJiNjU0ZWRjYjYzOCJ9
google-cloud-apigee-connect/src/main/java/com/google/cloud/apigeeconnect/v1/ConnectionServiceClient.java
chore: Integrate new gapic-generator-java and rules_gapic (#177)
<ide><path>oogle-cloud-apigee-connect/src/main/java/com/google/cloud/apigeeconnect/v1/ConnectionServiceClient.java <ide> * while (true) { <ide> * ListConnectionsResponse response = <ide> * connectionServiceClient.listConnectionsCallable().call(request); <del> * for (Connection element : response.getResponsesList()) { <add> * for (Connection element : response.getConnectionsList()) { <ide> * // doThingsWith(element); <ide> * } <ide> * String nextPageToken = response.getNextPageToken();
Java
apache-2.0
73b76598e776bbe7962e18cea087bdca1d560769
0
sdinot/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,apache/commons-math,apache/commons-math,sdinot/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus
/* * 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.commons.math4.ode.nonstiff; import org.apache.commons.math4.Field; import org.apache.commons.math4.RealFieldElement; import org.apache.commons.math4.util.Decimal64Field; import org.junit.Test; public class DormandPrince54FieldIntegratorTest extends AbstractEmbeddedRungeKuttaFieldIntegratorTest { protected <T extends RealFieldElement<T>> EmbeddedRungeKuttaFieldIntegrator<T> createIntegrator(Field<T> field, final double minStep, final double maxStep, final double scalAbsoluteTolerance, final double scalRelativeTolerance) { return new DormandPrince54FieldIntegrator<T>(field, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance); } protected <T extends RealFieldElement<T>> EmbeddedRungeKuttaFieldIntegrator<T> createIntegrator(Field<T> field, final double minStep, final double maxStep, final double[] vecAbsoluteTolerance, final double[] vecRelativeTolerance) { return new DormandPrince54FieldIntegrator<T>(field, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance); } @Test public void testNonFieldIntegratorConsistency() { doTestNonFieldIntegratorConsistency(Decimal64Field.getInstance()); } @Test public void testSanityChecks() { doTestSanityChecks(Decimal64Field.getInstance()); } @Test public void testBackward() { doTestBackward(Decimal64Field.getInstance(), 1.6e-7, 1.6e-7, 1.0e-22, "Dormand-Prince 5(4)"); } @Test public void testKepler() { doTestKepler(Decimal64Field.getInstance(), 3.1e-10); } @Override public void testForwardBackwardExceptions() { doTestForwardBackwardExceptions(Decimal64Field.getInstance()); } @Override public void testMinStep() { doTestMinStep(Decimal64Field.getInstance()); } @Override public void testIncreasingTolerance() { // the 0.7 factor is only valid for this test // and has been obtained from trial and error // there is no general relation between local and global errors doTestIncreasingTolerance(Decimal64Field.getInstance(), 0.7, 1.0e-12); } @Override public void testEvents() { doTestEvents(Decimal64Field.getInstance(), 1.7e-7, "Dormand-Prince 5(4)"); } @Override public void testEventsErrors() { doTestEventsErrors(Decimal64Field.getInstance()); } @Override public void testEventsNoConvergence() { doTestEventsNoConvergence(Decimal64Field.getInstance()); } }
src/test/java/org/apache/commons/math4/ode/nonstiff/DormandPrince54FieldIntegratorTest.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.commons.math4.ode.nonstiff; import org.apache.commons.math4.Field; import org.apache.commons.math4.RealFieldElement; import org.apache.commons.math4.util.Decimal64Field; import org.junit.Test; public class DormandPrince54FieldIntegratorTest extends AbstractEmbeddedRungeKuttaFieldIntegratorTest { protected <T extends RealFieldElement<T>> EmbeddedRungeKuttaFieldIntegrator<T> createIntegrator(Field<T> field, final double minStep, final double maxStep, final double scalAbsoluteTolerance, final double scalRelativeTolerance) { return new DormandPrince54FieldIntegrator<T>(field, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance); } protected <T extends RealFieldElement<T>> EmbeddedRungeKuttaFieldIntegrator<T> createIntegrator(Field<T> field, final double minStep, final double maxStep, final double[] vecAbsoluteTolerance, final double[] vecRelativeTolerance) { return new DormandPrince54FieldIntegrator<T>(field, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance); } @Test public void testNonFieldIntegratorConsistency() { doTestNonFieldIntegratorConsistency(Decimal64Field.getInstance()); } @Test public void testSanityChecks() { doTestSanityChecks(Decimal64Field.getInstance()); } @Test public void testBackward() { doTestBackward(Decimal64Field.getInstance(), 1.6e-7, 1.6e-7, 1.0e-22, "Dormand-Prince 5(4)"); } @Test public void testKepler() { doTestKepler(Decimal64Field.getInstance(), 3.1e-10); } @Override public void testForwardBackwardExceptions() { doTestForwardBackwardExceptions(Decimal64Field.getInstance()); } @Override public void testMinStep() { doTestMinStep(Decimal64Field.getInstance()); } @Override public void testIncreasingTolerance() { // the 0.5 factor is only valid for this test // and has been obtained from trial and error // there is no general relation between local and global errors doTestIncreasingTolerance(Decimal64Field.getInstance(), 0.5, 1.0e-12); } @Override public void testEvents() { doTestEvents(Decimal64Field.getInstance(), 3.10e-8, "Dormand-Prince 5(4)"); } @Override public void testEventsErrors() { doTestEventsErrors(Decimal64Field.getInstance()); } @Override public void testEventsNoConvergence() { doTestEventsNoConvergence(Decimal64Field.getInstance()); } }
Fixed test thresholds.
src/test/java/org/apache/commons/math4/ode/nonstiff/DormandPrince54FieldIntegratorTest.java
Fixed test thresholds.
<ide><path>rc/test/java/org/apache/commons/math4/ode/nonstiff/DormandPrince54FieldIntegratorTest.java <ide> <ide> @Override <ide> public void testIncreasingTolerance() { <del> // the 0.5 factor is only valid for this test <add> // the 0.7 factor is only valid for this test <ide> // and has been obtained from trial and error <ide> // there is no general relation between local and global errors <del> doTestIncreasingTolerance(Decimal64Field.getInstance(), 0.5, 1.0e-12); <add> doTestIncreasingTolerance(Decimal64Field.getInstance(), 0.7, 1.0e-12); <ide> } <ide> <ide> @Override <ide> public void testEvents() { <del> doTestEvents(Decimal64Field.getInstance(), 3.10e-8, "Dormand-Prince 5(4)"); <add> doTestEvents(Decimal64Field.getInstance(), 1.7e-7, "Dormand-Prince 5(4)"); <ide> } <ide> <ide> @Override
Java
isc
2350e8119a2fb89a69f0bcf16d3952aeb9610384
0
TealCube/loot
/****************************************************************************** * Copyright (c) 2014, Richard Harrah * * * * Permission to use, copy, modify, and/or distribute this software for any * * purpose with or without fee is hereby granted, provided that the above * * copyright notice and this permission notice appear in all copies. * * * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * ******************************************************************************/ package info.faceland.loot.managers; import info.faceland.loot.api.enchantments.EnchantmentStone; import info.faceland.loot.api.managers.EnchantmentStoneManager; import info.faceland.loot.math.LootRandom; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class LootEnchantmentStoneManager implements EnchantmentStoneManager { private static final double DISTANCE = 1000; private static final double DISTANCE_SQUARED = Math.pow(DISTANCE, 2); private final Map<String, EnchantmentStone> gemMap; private final LootRandom random; public LootEnchantmentStoneManager() { this.gemMap = new HashMap<>(); this.random = new LootRandom(System.currentTimeMillis()); } @Override public Set<EnchantmentStone> getEnchantmentStones() { return new HashSet<>(gemMap.values()); } @Override public EnchantmentStone getEnchantmentStone(String name) { if (gemMap.containsKey(name.toLowerCase())) { return gemMap.get(name.toLowerCase()); } if (gemMap.containsKey(name.toLowerCase().replace(" ", "_"))) { return gemMap.get(name.toLowerCase().replace(" ", "_")); } if (gemMap.containsKey(name.toLowerCase().replace("_", " "))) { return gemMap.get(name.toLowerCase().replace("_", " ")); } return null; } @Override public void addEnchantmentStone(EnchantmentStone gem) { if (gem != null) { gemMap.put(gem.getName().toLowerCase(), gem); } } @Override public void removeEnchantmentStone(String name) { if (name != null) { gemMap.remove(name.toLowerCase()); } } @Override public EnchantmentStone getRandomEnchantmentStone() { return getRandomEnchantmentStone(false); } @Override public EnchantmentStone getRandomEnchantmentStone(boolean withChance) { return getRandomEnchantmentStone(withChance, 0D); } @Override public EnchantmentStone getRandomEnchantmentStone(boolean withChance, double distance) { return getRandomEnchantmentStone(withChance, distance, new HashMap<EnchantmentStone, Double>()); } @Override public EnchantmentStone getRandomEnchantmentStone(boolean withChance, double distance, Map<EnchantmentStone, Double> map) { if (!withChance) { Set<EnchantmentStone> gems = getEnchantmentStones(); EnchantmentStone[] array = gems.toArray(new EnchantmentStone[gems.size()]); return array[random.nextInt(array.length)]; } double selectedWeight = random.nextDouble() * getTotalWeight(); double currentWeight = 0D; Set<EnchantmentStone> gems = getEnchantmentStones(); for (EnchantmentStone sg : gems) { double calcWeight = sg.getWeight() + ((distance / DISTANCE_SQUARED) * sg.getDistanceWeight()); if (map.containsKey(sg)) { calcWeight *= map.get(sg); } currentWeight += calcWeight; if (currentWeight >= selectedWeight) { return sg; } } return null; } @Override public double getTotalWeight() { double d = 0; for (EnchantmentStone sg : getEnchantmentStones()) { d += sg.getWeight(); } return d; } }
src/main/java/info/faceland/loot/managers/LootEnchantmentStoneManager.java
/****************************************************************************** * Copyright (c) 2014, Richard Harrah * * * * Permission to use, copy, modify, and/or distribute this software for any * * purpose with or without fee is hereby granted, provided that the above * * copyright notice and this permission notice appear in all copies. * * * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * ******************************************************************************/ package info.faceland.loot.managers; import info.faceland.loot.api.enchantments.EnchantmentStone; import info.faceland.loot.api.managers.EnchantmentStoneManager; import info.faceland.loot.math.LootRandom; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public final class LootEnchantmentStoneManager implements EnchantmentStoneManager { private final Map<String, EnchantmentStone> gemMap; private final LootRandom random; public LootEnchantmentStoneManager() { this.gemMap = new HashMap<>(); this.random = new LootRandom(System.currentTimeMillis()); } @Override public Set<EnchantmentStone> getEnchantmentStones() { return new HashSet<>(gemMap.values()); } @Override public EnchantmentStone getEnchantmentStone(String name) { if (gemMap.containsKey(name.toLowerCase())) { return gemMap.get(name.toLowerCase()); } if (gemMap.containsKey(name.toLowerCase().replace(" ", "_"))) { return gemMap.get(name.toLowerCase().replace(" ", "_")); } if (gemMap.containsKey(name.toLowerCase().replace("_", " "))) { return gemMap.get(name.toLowerCase().replace("_", " ")); } return null; } @Override public void addEnchantmentStone(EnchantmentStone gem) { if (gem != null) { gemMap.put(gem.getName().toLowerCase(), gem); } } @Override public void removeEnchantmentStone(String name) { if (name != null) { gemMap.remove(name.toLowerCase()); } } @Override public EnchantmentStone getRandomEnchantmentStone() { return getRandomEnchantmentStone(false); } @Override public EnchantmentStone getRandomEnchantmentStone(boolean withChance) { return getRandomEnchantmentStone(withChance, 0D); } @Override public EnchantmentStone getRandomEnchantmentStone(boolean withChance, double distance) { return getRandomEnchantmentStone(withChance, distance, new HashMap<EnchantmentStone, Double>()); } @Override public EnchantmentStone getRandomEnchantmentStone(boolean withChance, double distance, Map<EnchantmentStone, Double> map) { if (!withChance) { Set<EnchantmentStone> gems = getEnchantmentStones(); EnchantmentStone[] array = gems.toArray(new EnchantmentStone[gems.size()]); return array[random.nextInt(array.length)]; } double selectedWeight = random.nextDouble() * getTotalWeight(); double currentWeight = 0D; Set<EnchantmentStone> gems = getEnchantmentStones(); for (EnchantmentStone sg : gems) { double calcWeight = sg.getWeight() + ((distance / 10000D) * sg.getDistanceWeight()); if (map.containsKey(sg)) { calcWeight *= map.get(sg); } currentWeight += calcWeight; if (currentWeight >= selectedWeight) { return sg; } } return null; } @Override public double getTotalWeight() { double d = 0; for (EnchantmentStone sg : getEnchantmentStones()) { d += sg.getWeight(); } return d; } }
fixing enchantment stone distance calculation
src/main/java/info/faceland/loot/managers/LootEnchantmentStoneManager.java
fixing enchantment stone distance calculation
<ide><path>rc/main/java/info/faceland/loot/managers/LootEnchantmentStoneManager.java <ide> <ide> public final class LootEnchantmentStoneManager implements EnchantmentStoneManager { <ide> <add> private static final double DISTANCE = 1000; <add> private static final double DISTANCE_SQUARED = Math.pow(DISTANCE, 2); <ide> private final Map<String, EnchantmentStone> gemMap; <ide> private final LootRandom random; <ide> <ide> double currentWeight = 0D; <ide> Set<EnchantmentStone> gems = getEnchantmentStones(); <ide> for (EnchantmentStone sg : gems) { <del> double calcWeight = sg.getWeight() + ((distance / 10000D) * sg.getDistanceWeight()); <add> double calcWeight = sg.getWeight() + ((distance / DISTANCE_SQUARED) * sg.getDistanceWeight()); <ide> if (map.containsKey(sg)) { <ide> calcWeight *= map.get(sg); <ide> }
Java
apache-2.0
7174fcee9b3af0e6595345a7346673188f97c161
0
airza/kingOfT
package kingOfT; import java.awt.Dimension; import javax.swing.JFrame; public class MainLoop { /** * @param args */ public static void main(String[] args) { Window win = new Window(); final int PLAYER_NUM = 4; final String[] NAMES = {"A","B","C","D"}; Game game = new Game(PLAYER_NUM,NAMES); while (true) { game.takeTurn(); } } }
kingOfT/MainLoop.java
package kingOfT; public class MainLoop { /** * @param args */ public static void main(String[] args) { new Window(); final int PLAYER_NUM = 4; final String[] NAMES = {"A","B","C","D"}; Game game = new Game(PLAYER_NUM,NAMES); while (true) { game.takeTurn(); } } }
Added a window with lightning buttons!
kingOfT/MainLoop.java
Added a window with lightning buttons!
<ide><path>ingOfT/MainLoop.java <ide> package kingOfT; <add> <add>import java.awt.Dimension; <add> <add>import javax.swing.JFrame; <ide> <ide> <ide> <ide> * @param args <ide> */ <ide> public static void main(String[] args) { <del> new Window(); <add> Window win = new Window(); <ide> final int PLAYER_NUM = 4; <ide> final String[] NAMES = {"A","B","C","D"}; <ide>
Java
mit
bb6cc450c4cb37df1e4f221403b16acbb84791e6
0
s4sarishma/DesiPizza
/************************************************************************************ * Copyright (C) 2016 Sarishma Jayasree & Swathi Ramakanth Shanbhag * * This project is licensed under the "MIT License". * * Please see the file LICENSE in this distribution for license terms. * * LICENSE Link: https://github.com/s4sarishma/DesiPizza/blob/master/LICENSE) * * * ************************************************************************************/ package com.example.sari.desipizza; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import org.w3c.dom.Text; public class DrinkMenu_Page extends AppCompatActivity { Button add_to_cart_drinks_btn; Button cancel_drink_btn; TextView drinksizetext; TextView drinktypetext; TextView drinkpricetext; RadioGroup rg_drinksize; RadioGroup rg_drinktype; private static int drinksize_int; private static int drinktype_int; private static int drinkprice_int; public void addListenerOnButton_Add_To_Cart() { //final Context context = this; add_to_cart_drinks_btn = (Button) findViewById(R.id.button_AddToCart_Drink_id); add_to_cart_drinks_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(DrinkMenu_Page.this, StartPage.class); SharedPreferences sp = DrinkMenu_Page.this.getSharedPreferences("spSettings", 0); int temp_price = sp.getInt("TotalPrice", 0); Editor editor = sp.edit(); editor.putInt("TotalPrice", DrinkMenu_Page.drinkprice_int + temp_price); editor.commit(); String drinkSizeDisp = null; String drinkTypeDisp = ""; //BuildConfig.FLAVOR; if(DrinkMenu_Page.drinksize_int == 1) { drinkSizeDisp = "Small"; } else if(DrinkMenu_Page.drinksize_int == 2) { drinkSizeDisp = "Medium"; } else if(DrinkMenu_Page.drinksize_int == 3) { drinkSizeDisp = "Large"; } if(DrinkMenu_Page.drinktype_int == 1) { drinkTypeDisp = "Coke"; } else if(DrinkMenu_Page.drinktype_int == 2) { drinkTypeDisp = "Fanta"; } else if(DrinkMenu_Page.drinktype_int == 3) { drinkTypeDisp = "Diet Coke"; } else if(DrinkMenu_Page.drinktype_int == 4) { drinkTypeDisp = "Peppers"; } String drinkDisp = drinkSizeDisp + " " + drinkTypeDisp + " ($" + DrinkMenu_Page.drinkprice_int + ")\n"; if(ReviewCart_Page.list1 == null) { ReviewCart_Page.tp1 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list1 = drinkDisp; } else if(ReviewCart_Page.list2 == null) { ReviewCart_Page.tp2 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list2 = drinkDisp; } else if(ReviewCart_Page.list3 == null) { ReviewCart_Page.tp3 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list3 = drinkDisp; } else if(ReviewCart_Page.list4 == null) { ReviewCart_Page.tp4 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list4 = drinkDisp; } else if(ReviewCart_Page.list5 == null) { ReviewCart_Page.tp5 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list5 = drinkDisp; } else if(ReviewCart_Page.list6 == null) { ReviewCart_Page.tp6 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list6 = drinkDisp; } else if(ReviewCart_Page.list7 == null) { ReviewCart_Page.tp7 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list7 = drinkDisp; } else if(ReviewCart_Page.list8 == null) { ReviewCart_Page.tp8 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list8 = drinkDisp; } else if(ReviewCart_Page.list9 == null) { ReviewCart_Page.tp9 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list9 = drinkDisp; } else if(ReviewCart_Page.list10 == null) { ReviewCart_Page.tp10 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list10 = drinkDisp; } DrinkMenu_Page.drinkprice_int = 2; DrinkMenu_Page.drinksize_int = 1; DrinkMenu_Page.drinktype_int = 1; DrinkMenu_Page.this.startActivity(intent); } }); } public void addListenerOnButton_Cancel() { final Context context = this; cancel_drink_btn = (Button) findViewById(R.id.button_Cancel_Drink_id); cancel_drink_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, StartPage.class); DrinkMenu_Page.drinkprice_int = 2; DrinkMenu_Page.drinksize_int = 1; DrinkMenu_Page.drinktype_int = 1; DrinkMenu_Page.this.startActivity(intent); } }); } class drinksize_class implements RadioGroup.OnCheckedChangeListener { drinksize_class() { } //1823 public void onCheckedChanged(RadioGroup groupSize, int sizeCheckedId) { RadioButton rb_drinksize = (RadioButton) DrinkMenu_Page.this.findViewById(sizeCheckedId); if (rb_drinksize.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkSmall_id))) { DrinkMenu_Page.drinkprice_int = 2; DrinkMenu_Page.this.drinksizetext.setText("Size Selected: \n Small ($2)"); DrinkMenu_Page.drinksize_int = 1; } if (rb_drinksize.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkMedium_id))) { DrinkMenu_Page.drinkprice_int = 3; DrinkMenu_Page.this.drinksizetext.setText("Size Selected: \n Medium ($3)"); DrinkMenu_Page.drinksize_int = 2; } if (rb_drinksize.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkLarge_id))) { DrinkMenu_Page.drinkprice_int = 4; DrinkMenu_Page.this.drinksizetext.setText("Size Selected: \n Large ($4)"); DrinkMenu_Page.drinksize_int = 3; } DrinkMenu_Page.this.drinkpricetext.setText("Price: $" + DrinkMenu_Page.drinkprice_int); } } class drinktype_class implements RadioGroup.OnCheckedChangeListener { drinktype_class() { } public void onCheckedChanged(RadioGroup groupType, int typeCheckedId) { RadioButton rb_drinktype = (RadioButton) DrinkMenu_Page.this.findViewById(typeCheckedId); if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkCoke_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Coke"); DrinkMenu_Page.drinktype_int = 1; } if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkFanta_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Fanta"); DrinkMenu_Page.drinktype_int = 2; } if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkDietCoke_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Diet Coke"); DrinkMenu_Page.drinktype_int = 3; } if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkPeppers_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Peppers"); DrinkMenu_Page.drinktype_int = 4; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink_menu__page); drinksize_int = 1; drinktype_int = 1; drinkpricetext = (TextView) findViewById(R.id.textView_drinkPrice_id); drinkpricetext.setText("Price: $0"); drinksizetext = (TextView) findViewById(R.id.textView_drinkSizeSelected_id); drinksizetext.setText("\n Size Selected: \nSmall ($2)"); drinktypetext = (TextView) findViewById(R.id.textView_drinkTypeSelected_id); drinktypetext.setText("\n Drink Selected: \nCoke"); addListenerOnButton_Add_To_Cart(); addListenerOnButton_Cancel(); rg_drinksize = (RadioGroup) findViewById(R.id.radioGroup_drinkSize_id); rg_drinksize.setOnCheckedChangeListener( new drinksize_class()); rg_drinktype = (RadioGroup) findViewById(R.id.radiogroup_drinkType_id); rg_drinktype.setOnCheckedChangeListener( new drinktype_class()); //add_to_cart_drinks_btn already added in addListenerOnButton(). //cancel_drink_btn = (Button) findViewById(R.id.button_Cancel_Drink_id); //cancel_drink_btn.setOnClickListener(); } }
app/src/main/java/com/example/sari/desipizza/DrinkMenu_Page.java
package com.example.sari.desipizza; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import org.w3c.dom.Text; public class DrinkMenu_Page extends AppCompatActivity { Button add_to_cart_drinks_btn; Button cancel_drink_btn; TextView drinksizetext; TextView drinktypetext; TextView drinkpricetext; RadioGroup rg_drinksize; RadioGroup rg_drinktype; private static int drinksize_int; private static int drinktype_int; private static int drinkprice_int; public void addListenerOnButton_Add_To_Cart() { //final Context context = this; add_to_cart_drinks_btn = (Button) findViewById(R.id.button_AddToCart_Drink_id); add_to_cart_drinks_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(DrinkMenu_Page.this, StartPage.class); SharedPreferences sp = DrinkMenu_Page.this.getSharedPreferences("spSettings", 0); int temp_price = sp.getInt("TotalPrice", 0); Editor editor = sp.edit(); editor.putInt("TotalPrice", DrinkMenu_Page.drinkprice_int + temp_price); editor.commit(); String drinkSizeDisp = null; String drinkTypeDisp = ""; //BuildConfig.FLAVOR; if(DrinkMenu_Page.drinksize_int == 1) { drinkSizeDisp = "Small"; } else if(DrinkMenu_Page.drinksize_int == 2) { drinkSizeDisp = "Medium"; } else if(DrinkMenu_Page.drinksize_int == 3) { drinkSizeDisp = "Large"; } if(DrinkMenu_Page.drinktype_int == 1) { drinkTypeDisp = "Coke"; } else if(DrinkMenu_Page.drinktype_int == 2) { drinkTypeDisp = "Fanta"; } else if(DrinkMenu_Page.drinktype_int == 3) { drinkTypeDisp = "Diet Coke"; } else if(DrinkMenu_Page.drinktype_int == 4) { drinkTypeDisp = "Peppers"; } String drinkDisp = drinkSizeDisp + " " + drinkTypeDisp + " ($" + DrinkMenu_Page.drinkprice_int + ")\n"; if(ReviewCart_Page.list1 == null) { ReviewCart_Page.tp1 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list1 = drinkDisp; } else if(ReviewCart_Page.list2 == null) { ReviewCart_Page.tp2 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list2 = drinkDisp; } else if(ReviewCart_Page.list3 == null) { ReviewCart_Page.tp3 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list3 = drinkDisp; } else if(ReviewCart_Page.list4 == null) { ReviewCart_Page.tp4 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list4 = drinkDisp; } else if(ReviewCart_Page.list5 == null) { ReviewCart_Page.tp5 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list5 = drinkDisp; } else if(ReviewCart_Page.list6 == null) { ReviewCart_Page.tp6 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list6 = drinkDisp; } else if(ReviewCart_Page.list7 == null) { ReviewCart_Page.tp7 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list7 = drinkDisp; } else if(ReviewCart_Page.list8 == null) { ReviewCart_Page.tp8 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list8 = drinkDisp; } else if(ReviewCart_Page.list9 == null) { ReviewCart_Page.tp9 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list9 = drinkDisp; } else if(ReviewCart_Page.list10 == null) { ReviewCart_Page.tp10 = DrinkMenu_Page.drinkprice_int; ReviewCart_Page.list10 = drinkDisp; } DrinkMenu_Page.drinkprice_int = 2; DrinkMenu_Page.drinksize_int = 1; DrinkMenu_Page.drinktype_int = 1; DrinkMenu_Page.this.startActivity(intent); } }); } public void addListenerOnButton_Cancel() { final Context context = this; cancel_drink_btn = (Button) findViewById(R.id.button_Cancel_Drink_id); cancel_drink_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, StartPage.class); DrinkMenu_Page.drinkprice_int = 2; DrinkMenu_Page.drinksize_int = 1; DrinkMenu_Page.drinktype_int = 1; DrinkMenu_Page.this.startActivity(intent); } }); } class drinksize_class implements RadioGroup.OnCheckedChangeListener { drinksize_class() { } //1823 public void onCheckedChanged(RadioGroup groupSize, int sizeCheckedId) { RadioButton rb_drinksize = (RadioButton) DrinkMenu_Page.this.findViewById(sizeCheckedId); if (rb_drinksize.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkSmall_id))) { DrinkMenu_Page.drinkprice_int = 2; DrinkMenu_Page.this.drinksizetext.setText("Size Selected: \n Small ($2)"); DrinkMenu_Page.drinksize_int = 1; } if (rb_drinksize.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkMedium_id))) { DrinkMenu_Page.drinkprice_int = 3; DrinkMenu_Page.this.drinksizetext.setText("Size Selected: \n Medium ($3)"); DrinkMenu_Page.drinksize_int = 2; } if (rb_drinksize.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkLarge_id))) { DrinkMenu_Page.drinkprice_int = 4; DrinkMenu_Page.this.drinksizetext.setText("Size Selected: \n Large ($4)"); DrinkMenu_Page.drinksize_int = 3; } DrinkMenu_Page.this.drinkpricetext.setText("Price: $" + DrinkMenu_Page.drinkprice_int); } } class drinktype_class implements RadioGroup.OnCheckedChangeListener { drinktype_class() { } public void onCheckedChanged(RadioGroup groupType, int typeCheckedId) { RadioButton rb_drinktype = (RadioButton) DrinkMenu_Page.this.findViewById(typeCheckedId); if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkCoke_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Coke"); DrinkMenu_Page.drinktype_int = 1; } if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkFanta_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Fanta"); DrinkMenu_Page.drinktype_int = 2; } if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkDietCoke_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Diet Coke"); DrinkMenu_Page.drinktype_int = 3; } if (rb_drinktype.equals((RadioButton) DrinkMenu_Page.this.findViewById(R.id.radioButton_drinkPeppers_id))) { DrinkMenu_Page.this.drinktypetext.setText("Drink Selected: \n Peppers"); DrinkMenu_Page.drinktype_int = 4; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink_menu__page); drinksize_int = 1; drinktype_int = 1; drinkpricetext = (TextView) findViewById(R.id.textView_drinkPrice_id); drinkpricetext.setText("Price: $0"); drinksizetext = (TextView) findViewById(R.id.textView_drinkSizeSelected_id); drinksizetext.setText("\n Size Selected: \nSmall ($2)"); drinktypetext = (TextView) findViewById(R.id.textView_drinkTypeSelected_id); drinktypetext.setText("\n Drink Selected: \nCoke"); addListenerOnButton_Add_To_Cart(); addListenerOnButton_Cancel(); rg_drinksize = (RadioGroup) findViewById(R.id.radioGroup_drinkSize_id); rg_drinksize.setOnCheckedChangeListener( new drinksize_class()); rg_drinktype = (RadioGroup) findViewById(R.id.radiogroup_drinkType_id); rg_drinktype.setOnCheckedChangeListener( new drinktype_class()); //add_to_cart_drinks_btn already added in addListenerOnButton(). //cancel_drink_btn = (Button) findViewById(R.id.button_Cancel_Drink_id); //cancel_drink_btn.setOnClickListener(); } }
Update DrinkMenu_Page.java Added LICENSE info
app/src/main/java/com/example/sari/desipizza/DrinkMenu_Page.java
Update DrinkMenu_Page.java
<ide><path>pp/src/main/java/com/example/sari/desipizza/DrinkMenu_Page.java <add>/************************************************************************************ <add> * Copyright (C) 2016 Sarishma Jayasree & Swathi Ramakanth Shanbhag * <add> * This project is licensed under the "MIT License". * <add> * Please see the file LICENSE in this distribution for license terms. * <add> * LICENSE Link: https://github.com/s4sarishma/DesiPizza/blob/master/LICENSE) * <add> * * <add> ************************************************************************************/ <add> <ide> package com.example.sari.desipizza; <ide> <ide> import android.content.Context;
JavaScript
apache-2.0
3ca0e78dd02cd7a5c81c755f818bc1d127a057ab
0
vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile
/* @flow */ import { REHYDRATE } from 'redux-persist/constants'; import type { NavigationState, Action } from '../types'; import { navigateToChat } from './navActions'; import { getStateForRoute, getInitialNavState } from './navSelectors'; import AppNavigator from './AppNavigator'; import { INITIAL_FETCH_COMPLETE, ACCOUNT_SWITCH, LOGIN_SUCCESS, LOGOUT, SWITCH_NARROW, } from '../actionConstants'; export default ( state: ?NavigationState = getStateForRoute('loading'), action: Action, ): ?NavigationState => { switch (action.type) { case REHYDRATE: return getInitialNavState(action.payload); case ACCOUNT_SWITCH: return getStateForRoute('loading'); case LOGIN_SUCCESS: return getStateForRoute('main'); case INITIAL_FETCH_COMPLETE: return (state && state.routes[0].routeName === 'main') ? state : getStateForRoute('main'); case LOGOUT: return getStateForRoute('account'); case SWITCH_NARROW: return AppNavigator.router.getStateForAction(navigateToChat(action.narrow), state); default: return AppNavigator.router.getStateForAction(action, state); } };
src/nav/navReducers.js
/* @flow */ import { REHYDRATE } from 'redux-persist/constants'; import type { NavigationState, Action } from '../types'; import { navigateToChat } from './navActions'; import { getStateForRoute, getInitialNavState } from './navSelectors'; import AppNavigator from './AppNavigator'; import { INITIAL_FETCH_COMPLETE, ACCOUNT_SWITCH, LOGIN_SUCCESS, LOGOUT, SWITCH_NARROW, } from '../actionConstants'; export default ( state: NavigationState = getStateForRoute('loading'), action: Action, ): NavigationState => { switch (action.type) { case REHYDRATE: return getInitialNavState(action.payload); case ACCOUNT_SWITCH: return getStateForRoute('loading'); case LOGIN_SUCCESS: return getStateForRoute('main'); case INITIAL_FETCH_COMPLETE: return state.routes[0].routeName === 'main' ? state : getStateForRoute('main'); case LOGOUT: return getStateForRoute('account'); case SWITCH_NARROW: return AppNavigator.router.getStateForAction(navigateToChat(action.narrow), state); default: return AppNavigator.router.getStateForAction(action, state); } };
navReducers: Fix types to acknowledge state could be null. The router's `getStateForAction` method returns null if it finds nothing. Given that we sometimes call it with an arbitrary action, an assert that that doesn't happen doesn't seem appropriate; instead, acknowledge that that can happen by using a "maybe type", with `?`. This fact means any code relying on this state needs to make sure to check before doing something that would break on null. Marking the type with `?` should mean Flow finds those places for us by giving an error, and the spot fixed up in this commit is the only one it found. Surely this can't be the only place we use this state... so hopefully we're already checking elsewhere. If not, this is just another case where better Flow type coverage would make our code more robust.
src/nav/navReducers.js
navReducers: Fix types to acknowledge state could be null.
<ide><path>rc/nav/navReducers.js <ide> } from '../actionConstants'; <ide> <ide> export default ( <del> state: NavigationState = getStateForRoute('loading'), <add> state: ?NavigationState = getStateForRoute('loading'), <ide> action: Action, <del>): NavigationState => { <add>): ?NavigationState => { <ide> switch (action.type) { <ide> case REHYDRATE: <ide> return getInitialNavState(action.payload); <ide> return getStateForRoute('main'); <ide> <ide> case INITIAL_FETCH_COMPLETE: <del> return state.routes[0].routeName === 'main' ? <add> return (state && state.routes[0].routeName === 'main') ? <ide> state : getStateForRoute('main'); <ide> <ide> case LOGOUT:
Java
apache-2.0
4875358e896ea2b5e662fcbdb1812d839d248004
0
xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community
/* * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.junit; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiTypeParameter; import com.intellij.psi.util.InheritanceUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.psiutils.TestUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class TestCaseWithNoTestMethodsInspection extends BaseInspection { @SuppressWarnings({"PublicField"}) public boolean ignoreSupers = true; @Override @NotNull public String getID() { return "JUnitTestCaseWithNoTests"; } @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "test.case.with.no.test.methods.display.name"); } @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "test.case.with.no.test.methods.problem.descriptor"); } @Override @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel( InspectionGadgetsBundle.message( "test.case.with.no.test.methods.option"), this, "ignoreSupers"); } @Override public BaseInspectionVisitor buildVisitor() { return new TestCaseWithNoTestMethodsVisitor(); } private class TestCaseWithNoTestMethodsVisitor extends BaseInspectionVisitor { @Override public void visitClass(@NotNull PsiClass aClass) { if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType() || aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { return; } if (aClass instanceof PsiTypeParameter) { return; } if (!InheritanceUtil.isInheritor(aClass, JUnitCommonClassNames.JUNIT_FRAMEWORK_TEST_CASE)) { return; } final PsiMethod[] methods = aClass.getMethods(); for (final PsiMethod method : methods) { if (TestUtils.isJUnitTestMethod(method)) { return; } } if (ignoreSupers) { final PsiClass superClass = aClass.getSuperClass(); if (superClass != null) { final PsiMethod[] superMethods = superClass.getMethods(); for (PsiMethod superMethod : superMethods) { if (TestUtils.isJUnitTestMethod(superMethod)) { return; } } } } registerClassError(aClass); } } }
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/TestCaseWithNoTestMethodsInspection.java
/* * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.junit; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiTypeParameter; import com.intellij.psi.util.InheritanceUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.psiutils.TestUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class TestCaseWithNoTestMethodsInspection extends BaseInspection { @SuppressWarnings({"PublicField"}) public boolean ignoreSupers = false; @Override @NotNull public String getID() { return "JUnitTestCaseWithNoTests"; } @Override @NotNull public String getDisplayName() { return InspectionGadgetsBundle.message( "test.case.with.no.test.methods.display.name"); } @Override @NotNull protected String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message( "test.case.with.no.test.methods.problem.descriptor"); } @Override @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel( InspectionGadgetsBundle.message( "test.case.with.no.test.methods.option"), this, "ignoreSupers"); } @Override public BaseInspectionVisitor buildVisitor() { return new TestCaseWithNoTestMethodsVisitor(); } private class TestCaseWithNoTestMethodsVisitor extends BaseInspectionVisitor { @Override public void visitClass(@NotNull PsiClass aClass) { if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType() || aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { return; } if (aClass instanceof PsiTypeParameter) { return; } if (!InheritanceUtil.isInheritor(aClass, JUnitCommonClassNames.JUNIT_FRAMEWORK_TEST_CASE)) { return; } final PsiMethod[] methods = aClass.getMethods(); for (final PsiMethod method : methods) { if (TestUtils.isJUnitTestMethod(method)) { return; } } if (ignoreSupers) { final PsiClass superClass = aClass.getSuperClass(); if (superClass != null) { final PsiMethod[] superMethods = superClass.getMethods(); for (PsiMethod superMethod : superMethods) { if (TestUtils.isJUnitTestMethod(superMethod)) { return; } } } } registerClassError(aClass); } } }
ignore tests with test methods in supers only by default
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/TestCaseWithNoTestMethodsInspection.java
ignore tests with test methods in supers only by default
<ide><path>lugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/TestCaseWithNoTestMethodsInspection.java <ide> public class TestCaseWithNoTestMethodsInspection extends BaseInspection { <ide> <ide> @SuppressWarnings({"PublicField"}) <del> public boolean ignoreSupers = false; <add> public boolean ignoreSupers = true; <ide> <ide> @Override <ide> @NotNull
Java
bsd-3-clause
abad891b4055e43c38567781c407a852638d196b
0
TheRealAgentK/CFLint,cflint/CFLint,TheRealAgentK/CFLint,TheRealAgentK/CFLint,cflint/CFLint
package com.cflint.plugins; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; import com.cflint.StackHandler; import cfml.parsing.cfscript.CFIdentifier; import net.htmlparser.jericho.Element; public class Context { String filename; String componentName; final Element element; String functionName; final boolean inAssignmentExpression; boolean inComponent; final StackHandler callStack; final CommonTokenStream tokens; final List<ContextMessage> messages = new ArrayList<ContextMessage>(); Context parent=null; public Context(final String filename, final Element element, final CFIdentifier functionName, final boolean inAssignmentExpression, final StackHandler handler) { super(); this.filename = filename; this.element = element; this.functionName = functionName == null ? "" : functionName.Decompile(0); this.inAssignmentExpression = inAssignmentExpression; this.callStack = handler; this.tokens=null; } public Context(final String filename, final Element element, final String functionName, final boolean inAssignmentExpression, final StackHandler handler,CommonTokenStream tokens) { super(); this.filename = filename; this.element = element; this.functionName = functionName == null ? "" : functionName; this.inAssignmentExpression = inAssignmentExpression; this.callStack = handler; this.tokens=tokens; } public String getFilename() { return filename; } public void setFilename(final String filename) { this.filename = filename; } public Element getElement() { return element; } public String getFunctionName() { return functionName; } public String getComponentName() { return componentName; } public void setFunctionIdentifier(final CFIdentifier functionName) { this.functionName = functionName == null ? "" : functionName.Decompile(0); } public void setFunctionName(final String functionName) { this.functionName = functionName; } public void setComponentName(final String componentName) { if (componentName == null) { this.componentName = componentFromFile(this.filename); } else { this.componentName = componentName; } } public boolean isInFunction() { return functionName != null && getFunctionName().length() > 0; } public boolean isInAssignmentExpression() { return inAssignmentExpression; } public StackHandler getCallStack() { return callStack; } public String fileFunctionString() { if (functionName == null && filename == null) { return null; } final StringBuilder key = new StringBuilder(); if (filename != null) { key.append(filename.trim()); } key.append(":"); if (functionName != null) { key.append(functionName); } return key.toString(); } public boolean isInComponent() { return inComponent; } public void setInComponent(final boolean inComponent) { this.inComponent = inComponent; } public List<ContextMessage> getMessages() { return messages; } public void addMessage(final String messageCode, final String variable) { messages.add(new ContextMessage(messageCode, variable)); } public void addMessage(final String messageCode, final String variable, final Integer line) { messages.add(new ContextMessage(messageCode, variable, line)); } public static class ContextMessage { String messageCode; String variable; Integer line; public ContextMessage(final String messageCode, final String variable) { super(); this.messageCode = messageCode; this.variable = variable; } public ContextMessage(final String messageCode, final String variable, final Integer line) { this(messageCode, variable); this.line = line; } public String getMessageCode() { return messageCode; } public String getVariable() { return variable; } public Integer getLine() { return line; } } public Context subContext(final Element elem) { final Context context2 = new Context(getFilename(), elem, getFunctionName(), isInAssignmentExpression(), callStack,tokens); context2.setInComponent(isInComponent()); context2.parent = this; return context2; } public int startLine() { if (element != null && element.getSource() != null) { return element.getSource().getRow(element.getBegin()); } else { return 1; // not zero } } protected String componentFromFile(final String filename) { final int dotPosition = filename.lastIndexOf("."); final String separator = System.getProperty("file.separator"); final int seperatorPosition = filename.lastIndexOf(separator); if (dotPosition == -1 || seperatorPosition == -1) { return null; } return filename.substring(seperatorPosition + 1, dotPosition); } public CommonTokenStream getTokens() { return tokens; } public Iterable<Token> beforeTokens(Token t){ return new ContextTokensIterable(t,-1); } public Iterable<Token> afterTokens(Token t){ return new ContextTokensIterable(t,1); } public class ContextTokensIterable implements Iterable<Token> { final Token token; final int direction; public ContextTokensIterable(Token token, int direction){ this.token=token; this.direction=direction; } @Override public Iterator<Token> iterator() { return new ContextTokensIterator(token,direction); } } public class ContextTokensIterator implements Iterator<Token> { int tokenIndex; final int direction; public ContextTokensIterator(Token token, int direction){ this.tokenIndex=token.getTokenIndex() + direction; this.direction=direction; } @Override public boolean hasNext() { if(direction <0) return tokens != null && tokenIndex >= 0; else return tokens != null && tokenIndex < tokens.getTokens().size(); } @Override public Token next() { if (tokens != null && tokenIndex > 0){ Token retval = tokens.getTokens().get(tokenIndex); tokenIndex += direction; return retval; } return null; } @Override public void remove(){ throw new UnsupportedOperationException(); } } public Context getParent() { return parent; } }
src/main/java/com/cflint/plugins/Context.java
package com.cflint.plugins; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; import com.cflint.StackHandler; import cfml.parsing.cfscript.CFIdentifier; import net.htmlparser.jericho.Element; public class Context { String filename; String componentName; final Element element; String functionName; final boolean inAssignmentExpression; boolean inComponent; final StackHandler callStack; final CommonTokenStream tokens; final List<ContextMessage> messages = new ArrayList<ContextMessage>(); Context parent=null; public Context(final String filename, final Element element, final CFIdentifier functionName, final boolean inAssignmentExpression, final StackHandler handler) { super(); this.filename = filename; this.element = element; this.functionName = functionName == null ? "" : functionName.Decompile(0); this.inAssignmentExpression = inAssignmentExpression; this.callStack = handler; this.tokens=null; } public Context(final String filename, final Element element, final String functionName, final boolean inAssignmentExpression, final StackHandler handler,CommonTokenStream tokens) { super(); this.filename = filename; this.element = element; this.functionName = functionName == null ? "" : functionName; this.inAssignmentExpression = inAssignmentExpression; this.callStack = handler; this.tokens=tokens; } public String getFilename() { return filename; } public void setFilename(final String filename) { this.filename = filename; } public Element getElement() { return element; } public String getFunctionName() { return functionName; } public String getComponentName() { return componentName; } public void setFunctionIdentifier(final CFIdentifier functionName) { this.functionName = functionName == null ? "" : functionName.Decompile(0); } public void setFunctionName(final String functionName) { this.functionName = functionName; } public void setComponentName(final String componentName) { if (componentName == null) { this.componentName = componentFromFile(this.filename); } else { this.componentName = componentName; } } public boolean isInFunction() { return functionName != null && getFunctionName().length() > 0; } public boolean isInAssignmentExpression() { return inAssignmentExpression; } public StackHandler getCallStack() { return callStack; } public String fileFunctionString() { if (functionName == null && filename == null) { return null; } final StringBuilder key = new StringBuilder(); if (filename != null) { key.append(filename.trim()); } key.append(":"); if (functionName != null) { key.append(functionName); } return key.toString(); } public boolean isInComponent() { return inComponent; } public void setInComponent(final boolean inComponent) { this.inComponent = inComponent; } public List<ContextMessage> getMessages() { return messages; } public void addMessage(final String messageCode, final String variable) { messages.add(new ContextMessage(messageCode, variable)); } public void addMessage(final String messageCode, final String variable, final Integer line) { messages.add(new ContextMessage(messageCode, variable, line)); } public static class ContextMessage { String messageCode; String variable; Integer line; public ContextMessage(final String messageCode, final String variable) { super(); this.messageCode = messageCode; this.variable = variable; } public ContextMessage(final String messageCode, final String variable, final Integer line) { this(messageCode, variable); this.line = line; } public String getMessageCode() { return messageCode; } public String getVariable() { return variable; } public Integer getLine() { return line; } } public Context subContext(final Element elem) { final Context context2 = new Context(getFilename(), elem, getFunctionName(), isInAssignmentExpression(), callStack,tokens); context2.setInComponent(isInComponent()); context2.parent = this; return context2; } public int startLine() { if (element != null && element.getSource() != null) { return element.getSource().getRow(element.getBegin()); } else { return 1; // not zero } } protected String componentFromFile(final String filename) { final int dotPosition = filename.lastIndexOf("."); final String separator = System.getProperty("file.separator"); final int seperatorPosition = filename.lastIndexOf(separator); if (dotPosition == -1 || seperatorPosition == -1) { return null; } return filename.substring(seperatorPosition + 1, dotPosition); } public CommonTokenStream getTokens() { return tokens; } public Iterable<Token> beforeTokens(Token t){ return new ContextTokensIterable(t,-1); } public Iterable<Token> afterTokens(Token t){ return new ContextTokensIterable(t,1); } public class ContextTokensIterable implements Iterable<Token> { final Token token; final int direction; public ContextTokensIterable(Token token, int direction){ this.token=token; this.direction=direction; } @Override public Iterator<Token> iterator() { return new ContextTokensIterator(token,direction); } } public class ContextTokensIterator implements Iterator<Token> { int tokenIndex; final int direction; public ContextTokensIterator(Token token, int direction){ this.tokenIndex=token.getTokenIndex() + direction; this.direction=direction; } @Override public boolean hasNext() { if(direction <0) return tokens != null && tokenIndex >= 0; else return tokens != null && tokenIndex < tokens.getTokens().size(); } @Override public Token next() { if (tokens != null && tokenIndex > 0){ Token retval = tokens.getTokens().get(tokenIndex); tokenIndex += direction; return retval; } return null; } } public Context getParent() { return parent; } }
added missing remove() method on iterator
src/main/java/com/cflint/plugins/Context.java
added missing remove() method on iterator
<ide><path>rc/main/java/com/cflint/plugins/Context.java <ide> return null; <ide> } <ide> <add> @Override <add> public void remove(){ <add> throw new UnsupportedOperationException(); <add> } <ide> } <ide> <ide> public Context getParent() {
Java
unlicense
217c8771890506a2e2d1a5cbccf05001834410f9
0
intangir/Tweaks
package com.github.intangir.Tweaks; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; public class Books extends Tweak { Books(Tweaks plugin) { super(plugin); CONFIG_FILE = new File(plugin.getDataFolder(), "books.yml"); TWEAK_NAME = "Tweak_Books"; TWEAK_VERSION = "1.0"; booksPermission = "tweak.books.give"; } private String booksPermission; @CommandHandler("givebook") public void onGiveBook(CommandSender sender, String[] args) { if(!sender.isOp() && !sender.hasPermission(booksPermission)) return; if(args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: /givebook <player> <book>"); return; } Player p = server.getPlayer(args[0]); String bookName = args[1]; if(p == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return; } // retreive book data String bookData; try { byte[] contents; Path bookPath = Paths.get(plugin.getDataFolder() + "/books/" + bookName + ".txt"); contents = Files.readAllBytes(bookPath); bookData = new String(contents); } catch (Exception e) { sender.sendMessage(ChatColor.RED + "Unable to read book " + plugin.getDataFolder() + "/books/" + bookName + ".txt"); return; } // create book ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta bm = (BookMeta) book.getItemMeta(); String[] bookSections = bookData.split("\n", 3); bm.setTitle(translateColors(bookSections[0].trim())); bm.setAuthor(translateColors(bookSections[1].trim())); String[] pages = bookSections[2].split("\n/np\n"); for(String page : pages) { bm.addPage(translateColors(page)); } book.setItemMeta(bm); p.getInventory().addItem(book); } public String translateColors(String line) { return ChatColor.translateAlternateColorCodes('&', line); } }
src/main/java/com/github/intangir/Tweaks/Books.java
package com.github.intangir.Tweaks; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; public class Books extends Tweak { Books(Tweaks plugin) { super(plugin); TWEAK_NAME = "Tweak_Books"; TWEAK_VERSION = "1.0"; } @CommandHandler("givebook") public void onGiveBook(CommandSender sender, String[] args) { if(args.length < 2) { sender.sendMessage(ChatColor.RED + "Usage: /givebook <player> <book>"); return; } Player p = server.getPlayer(args[0]); String bookName = args[1]; if(p == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return; } // retreive book data String bookData; try { byte[] contents; Path bookPath = Paths.get(plugin.getDataFolder() + "/books/" + bookName + ".txt"); contents = Files.readAllBytes(bookPath); bookData = new String(contents); } catch (Exception e) { sender.sendMessage(ChatColor.RED + "Unable to read book " + plugin.getDataFolder() + "/books/" + bookName + ".txt"); return; } // create book ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta bm = (BookMeta) book.getItemMeta(); String[] bookSections = bookData.split("\n", 3); bm.setTitle(translateColors(bookSections[0].trim())); bm.setAuthor(translateColors(bookSections[1].trim())); String[] pages = bookSections[2].split("\n/np\n"); for(String page : pages) { bm.addPage(translateColors(page)); } book.setItemMeta(bm); p.getInventory().addItem(book); } public String translateColors(String line) { return ChatColor.translateAlternateColorCodes('&', line); } }
add support for permission to books giving command
src/main/java/com/github/intangir/Tweaks/Books.java
add support for permission to books giving command
<ide><path>rc/main/java/com/github/intangir/Tweaks/Books.java <ide> package com.github.intangir.Tweaks; <ide> <add>import java.io.File; <ide> import java.nio.file.Files; <ide> import java.nio.file.Path; <ide> import java.nio.file.Paths; <ide> { <ide> Books(Tweaks plugin) { <ide> super(plugin); <add> CONFIG_FILE = new File(plugin.getDataFolder(), "books.yml"); <ide> TWEAK_NAME = "Tweak_Books"; <ide> TWEAK_VERSION = "1.0"; <add> booksPermission = "tweak.books.give"; <ide> } <ide> <add> private String booksPermission; <ide> <ide> @CommandHandler("givebook") <ide> public void onGiveBook(CommandSender sender, String[] args) { <add> if(!sender.isOp() && !sender.hasPermission(booksPermission)) return; <add> <ide> if(args.length < 2) { <ide> sender.sendMessage(ChatColor.RED + "Usage: /givebook <player> <book>"); <ide> return;
JavaScript
bsd-3-clause
40bf24df2910b827ea7aebd1932ab04086da10ed
0
Brickrouge/Brickrouge,Brickrouge/Brickrouge,Brickrouge/Brickrouge,sylvaincombes/Brickrouge,sylvaincombes/Brickrouge,sylvaincombes/Brickrouge
/*! * This file is part of the BrickRouge package. * * (c) Olivier Laviale <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var BrickRouge = { Utils: { Busy: new Class({ startBusy: function() { if (++this.busyNest == 1) { return; } this.element.addClass('busy'); }, finishBusy: function() { if (--this.busyNest) { return; } this.element.removeClass('busy'); } }) }, Widget: { }, Form: new Class({ Implements: [ Options, Events ], options: { url: null, useXHR: false }, initialize: function(el, options) { this.element = document.id(el); this.setOptions(options); if (this.options.useXHR || (options && (options.onRequest || options.onComplete || options.onFailure || options.onSuccess))) { this.element.addEvent ( 'submit', function(ev) { ev.stop(); this.submit(); } .bind(this) ); } }, alert: function(messages, type) { var original, alert = this.element.getElement('div.alert-message.' + type) || new Element('div.alert-message.' + type, { html: '<a href="#close" class="close">×</a>'}); if (typeOf(messages) == 'string') { messages = [ messages ]; } else if (typeOf(messages) == 'object') { original = messages; messages = []; Object.each ( original, function(message, id) { if (typeOf(id) == 'string' && id != '_base') { var parent, field, el = this.element.elements[id], i; if (typeOf(el) == 'collection') { parent = el[0].getParent('div.radio-group'); field = parent.getParent('.field'); if (parent) { parent.addClass('error'); } else { for (i = 0, j = el.length ; i < j ; i++) { el[i].addClass('error'); } } } else { el.addClass('error'); field = el.getParent('.field'); } if (field) { field.addClass('error'); } } if (!message || message === true) { return; } messages.push(message); }, this ); } if (!messages.length) { return; } messages.each ( function(message) { alert.adopt(new Element('p', { html: message })); } ); if (!alert.parentNode) { alert.inject(this.element, 'top'); } }, clearAlert: function() { var alerts = this.element.getElements('div.alert-message'); if (alerts) { alerts.destroy(); } this.element.getElements('.error').removeClass('error'); }, submit: function() { this.fireEvent('submit', {}); this.getOperation().send(this.element); }, getOperation: function() { if (this.operation) { return this.operation; } return this.operation = new Request.JSON ({ url: this.options.url || this.element.action, onRequest: this.request.bind(this), onComplete: this.complete.bind(this), onSuccess: this.success.bind(this), onFailure: this.failure.bind(this) }); }, request: function() { this.clearAlert(); this.fireEvent('request', arguments); }, complete: function() { this.fireEvent('complete', arguments); }, success: function(response) { if (response.success) { this.alert(response.success, 'success'); } this.onSuccess(response); }, onSuccess: function(response) { this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(xhr) { var response = JSON.decode(xhr.responseText); if (response && response.errors) { this.alert(response.errors, 'error'); } this.fireEvent('failure', arguments); } }), /** * Update the document by adding missing CSS and JS assets. * * @param object assets * @param function done */ updateAssets: (function() { var available_css=null, available_js=null; return function (assets, done) { var css=new Array(), js=new Array(), js_count; if (available_css === null) { available_css = new Array(); if (typeof(document_cached_css_assets) !== 'undefined') { available_css = document_cached_css_assets; } document.id(document.head).getElements('link[type="text/css"]').each ( function(el) { available_css.push(el.get('href')); } ); } if (available_js === null) { available_js = new Array(); if (typeof(brickrouge_cached_js_assets) !== 'undefined') { available_js = brickrouge_cached_js_assets; } document.id(document.html).getElements('script').each ( function(el) { var src = el.get('src'); if (src) available_js.push(src); } ); } assets.css.each ( function(url) { if (available_css.indexOf(url) != -1) { return; } css.push(url); } ); css.each ( function(url) { new Asset.css(url); available_css.push(url); } ); assets.js.each ( function(url) { if (available_js.indexOf(url) != -1) { return; } js.push(url); } ); js_count = js.length; if (!js_count) { done(); return; } js.each ( function(url) { new Asset.javascript ( url, { onload: function() { available_js.push(url); if (!--js_count) { done(); } } } ); } ); }; }) (), /** * Awakes sleeping widgets. * * Constructors defined under the `Widget` namespace are traversed and for each one of them * matching widgets are searched in the DOM a new widget is created using the constructor. * * Widgets are matched against a constructor based on the following naming convention: for a * "AdjustNode" constructor, the elements matching the ".widget-adjust-node" selector are * turned into widgets. * * The `widget` property is not stored in the element and is used to avoid creating two * widgets with the same element. * * @param container This optionnal parameter can be used to limit widget awaking to a * specified container, otherwise the document's body is used. */ awakeWidgets: function(container) { container = container || document.id(document.body); Object.each ( BrickRouge.Widget, ( function(constructor, key) { var cl = '.widget' + key.hyphenate(); container.getElements(cl).each ( function(el) { if (el.retrieve('widget')) { return; } var widget = new constructor(el, el.get('dataset')); el.store('widget', widget); } ); } ) ); } }; /* * The Request.Element class required the Request.API class provided by the ICanBoogie framework, * maybe we should move the Request.Element and Request.Widget clases to the Icybee CMS. */ if (Request.API) { /** * Extends Request.API to support the loading of single HTML elements. */ Request.Element = new Class ({ Extends: Request.API, onSuccess: function(response, text) { var el = Elements.from(response.rc).shift(); if (!response.assets) { this.parent(el, response, text); return; } BrickRouge.updateAssets ( response.assets, function() { this.fireEvent('complete', [ response, text ]).fireEvent('success', [ el, response, text ]).callChain(); } .bind(this) ); } }); /** * Extends Request.Element to support loading of single widgets. */ Request.Widget = new Class ({ Extends: Request.Element, initialize: function(cl, onSuccess, options) { if (options == undefined) { options = {}; } options.url = 'widgets/' + cl; options.onSuccess = onSuccess; this.parent(options); } }); } /** * This is the namespace for all widgets constructors. */ Element.Properties.widget = { get: function() { var widget = this.retrieve('widget'), type, constructorName, constructor; if (!widget) { type = this.className.match(/widget(-\S+)/); if (type && type.length) { constructorName = type[1].camelCase(); constructor = BrickRouge.Widget[constructorName]; if (!constructor) { throw "Constructor \"" + constructor + "\"is not defined to create widgets of type \"" + type + "\""; } widget = new constructor(this, this.get('dataset')); this.store('widget', widget); } } return widget; } }; /** * Widgets auto-constructor. * * On the 'elementsready' document event, constructors defined under the `Widget` namespace are * traversed and for each one of them, matching widgets are searched in the DOM and if the `widget` * property is not stored, a new widget is created using the constructor. * * Widgets are matched against a constructor based on the following naming convention: for a * "AdjustNode" constructor, the elements matching ".widget-adjust-node" are turned into widgets. */ document.addEvent ( 'elementsready', function(ev) { BrickRouge.awakeWidgets(ev.target); } ); /** * The "elementsready" event is fired for elements to be initialized, to become alive thanks to the * magic of Javascript. This event is usually fired when new widgets are added to the DOM. */ window.addEvent ( 'domready', function() { document.fireEvent('elementsready', { target: document.id(document.body) }); } ); /** * Destroy the alert message when its close icon is clicked. The "error" class is also removed from * elements. */ document.id(document.body).addEvent('click:relay(div.alert-message a.close)', function(ev, target){ ev.stop(); var form = target.getParent('form'); if (form) { form.getElements('.error').removeClass('error'); } target.getParent('div.alert-message').destroy(); });
lib/brickrouge.js
/*! * This file is part of the BrickRouge package. * * (c) Olivier Laviale <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var BrickRouge = { Utils: { Busy: new Class({ startBusy: function() { if (++this.busyNest == 1) { return; } this.element.addClass('busy'); }, finishBusy: function() { if (--this.busyNest) { return; } this.element.removeClass('busy'); } }) }, Widget: { }, Form: new Class({ Implements: [ Options, Events ], options: { url: null, useXHR: false }, initialize: function(el, options) { this.element = document.id(el); this.setOptions(options); if (this.options.useXHR || (options && (options.onRequest || options.onComplete || options.onFailure || options.onSuccess))) { this.element.addEvent ( 'submit', function(ev) { ev.stop(); this.submit(); } .bind(this) ); } }, alert: function(messages, type) { var original, alert = this.element.getElement('div.alert-message.' + type) || new Element('div.alert-message.' + type, { html: '<a href="#close" class="close">×</a>'}); if (typeOf(messages) == 'string') { messages = [ messages ]; } else if (typeOf(messages) == 'object') { original = messages; messages = []; Object.each ( original, function(message, id) { if (typeOf(id) == 'string' && id != '_base') { var parent, field, el = this.element.elements[id], i; if (typeOf(el) == 'collection') { parent = el[0].getParent('div.radio-group'); field = parent.getParent('.field'); if (parent) { parent.addClass('error'); } else { for (i = 0, j = el.length ; i < j ; i++) { el[i].addClass('error'); } } } else { el.addClass('error'); field = el.getParent('.field'); } if (field) { field.addClass('error'); } } if (!message || message === true) { return; } messages.push(message); }, this ); } if (!messages.length) { return; } messages.each ( function(message) { alert.adopt(new Element('p', { html: message })); } ); if (!alert.parentNode) { alert.inject(this.element, 'top'); } }, clearAlert: function() { var alerts = this.element.getElements('div.alert-message'); if (alerts) { alerts.destroy(); } this.element.getElements('.error').removeClass('error'); }, submit: function() { this.fireEvent('submit', {}); this.getOperation().send(this.element); }, getOperation: function() { if (this.operation) { return this.operation; } return this.operation = new Request.JSON ({ url: this.options.url || this.element.action, onRequest: this.request.bind(this), onComplete: this.complete.bind(this), onSuccess: this.success.bind(this), onFailure: this.failure.bind(this) }); }, request: function() { this.clearAlert(); this.fireEvent('request', arguments); }, complete: function() { this.fireEvent('complete', arguments); }, success: function(response) { if (response.success) { this.alert(response.success, 'success'); } this.onSuccess(response); }, onSuccess: function(response) { this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain(); }, failure: function(xhr) { var response = JSON.decode(xhr.responseText); if (response && response.errors) { this.alert(response.errors, 'error'); } this.fireEvent('failure', arguments); } }), /** * Update the document by adding missing CSS and JS assets. * * @param object assets * @param function done */ updateAssets: (function() { var available_css=null, available_js=null; return function (assets, done) { var css=new Array(), js=new Array(), js_count; if (available_css === null) { available_css = new Array(); if (typeof(document_cached_css_assets) !== 'undefined') { available_css = document_cached_css_assets; } document.id(document.head).getElements('link[type="text/css"]').each ( function(el) { available_css.push(el.get('href')); } ); } if (available_js === null) { available_js = new Array(); if (typeof(brickrouge_cached_js_assets) !== 'undefined') { available_js = brickrouge_cached_js_assets; } document.id(document.html).getElements('script').each ( function(el) { var src = el.get('src'); if (src) available_js.push(src); } ); } assets.css.each ( function(url) { if (available_css.indexOf(url) != -1) { return; } css.push(url); } ); css.each ( function(url) { new Asset.css(url); available_css.push(url); } ); assets.js.each ( function(url) { if (available_js.indexOf(url) != -1) { return; } js.push(url); } ); js_count = js.length; if (!js_count) { done(); return; } js.each ( function(url) { new Asset.javascript ( url, { onload: function() { available_js.push(url); if (!--js_count) { done(); } } } ); } ); }; }) () }; /* * The Request.Element class required the Request.API class provided by the ICanBoogie framework, * maybe we should move the Request.Element and Request.Widget clases to the Icybee CMS. */ if (Request.API) { /** * Extends Request.API to support the loading of single HTML elements. */ Request.Element = new Class ({ Extends: Request.API, onSuccess: function(response, text) { var el = Elements.from(response.rc).shift(); if (!response.assets) { this.parent(el, response, text); return; } BrickRouge.updateAssets ( response.assets, function() { this.fireEvent('complete', [ response, text ]).fireEvent('success', [ el, response, text ]).callChain(); } .bind(this) ); } }); /** * Extends Request.Element to support loading of single widgets. */ Request.Widget = new Class ({ Extends: Request.Element, initialize: function(cl, onSuccess, options) { if (options == undefined) { options = {}; } options.url = 'widgets/' + cl; options.onSuccess = onSuccess; this.parent(options); } }); } /** * This is the namespace for all widgets constructors. */ Element.Properties.widget = { get: function() { var widget = this.retrieve('widget'), type, constructorName, constructor; if (!widget) { type = this.className.match(/widget(-\S+)/); if (type && type.length) { constructorName = type[1].camelCase(); constructor = BrickRouge.Widget[constructorName]; if (!constructor) { throw "Constructor \"" + constructor + "\"is not defined to create widgets of type \"" + type + "\""; } widget = new constructor(this, this.get('dataset')); this.store('widget', widget); } } return widget; } }; /** * Widgets auto-constructor. * * On the 'elementsready' document event, constructors defined under the `Widget` namespace are * traversed and for each one of them, matching widgets are searched in the DOM and if the `widget` * property is not stored, a new widget is created using the constructor. * * Widgets are matched against a constructor based on the following naming convention: for a * "AdjustNode" constructor, the elements matching ".widget-adjust-node" are turned into widgets. */ document.addEvent ( 'elementsready', function() { Object.each ( BrickRouge.Widget, ( function(constructor, key) { var cl = '.widget' + key.hyphenate(); $$(cl).each ( function(el) { if (el.retrieve('widget')) { return; } var widget = new constructor(el, el.get('dataset')); el.store('widget', widget); } ); } ) ); } ); /** * The "elementsready" event is fired for elements to be initialized, to become alive thanks to the * magic of Javascript. This event is usually fired when new widgets are added to the DOM. */ window.addEvent ( 'domready', function() { document.fireEvent('elementsready', { target: document.id(document.body) }); } ); /** * Destroy the alert message when its close icon is clicked. The "error" class is also removed from * elements. */ document.id(document.body).addEvent('click:relay(div.alert-message a.close)', function(ev, target){ ev.stop(); var form = target.getParent('form'); if (form) { form.getElements('.error').removeClass('error'); } target.getParent('div.alert-message').destroy(); });
Turned elementsready closure into the BrickRouge.awakeWidgets method
lib/brickrouge.js
Turned elementsready closure into the BrickRouge.awakeWidgets method
<ide><path>ib/brickrouge.js <ide> ); <ide> }; <ide> <del> }) () <add> }) (), <add> <add> /** <add> * Awakes sleeping widgets. <add> * <add> * Constructors defined under the `Widget` namespace are traversed and for each one of them <add> * matching widgets are searched in the DOM a new widget is created using the constructor. <add> * <add> * Widgets are matched against a constructor based on the following naming convention: for a <add> * "AdjustNode" constructor, the elements matching the ".widget-adjust-node" selector are <add> * turned into widgets. <add> * <add> * The `widget` property is not stored in the element and is used to avoid creating two <add> * widgets with the same element. <add> * <add> * @param container This optionnal parameter can be used to limit widget awaking to a <add> * specified container, otherwise the document's body is used. <add> */ <add> awakeWidgets: function(container) <add> { <add> container = container || document.id(document.body); <add> <add> Object.each <add> ( <add> BrickRouge.Widget, <add> ( <add> function(constructor, key) <add> { <add> var cl = '.widget' + key.hyphenate(); <add> <add> container.getElements(cl).each <add> ( <add> function(el) <add> { <add> if (el.retrieve('widget')) <add> { <add> return; <add> } <add> <add> var widget = new constructor(el, el.get('dataset')); <add> <add> el.store('widget', widget); <add> } <add> ); <add> } <add> ) <add> ); <add> } <ide> }; <ide> <ide> /* <ide> */ <ide> document.addEvent <ide> ( <del> 'elementsready', function() <add> 'elementsready', function(ev) <ide> { <del> Object.each <del> ( <del> BrickRouge.Widget, <del> ( <del> function(constructor, key) <del> { <del> var cl = '.widget' + key.hyphenate(); <del> <del> $$(cl).each <del> ( <del> function(el) <del> { <del> if (el.retrieve('widget')) <del> { <del> return; <del> } <del> <del> var widget = new constructor(el, el.get('dataset')); <del> <del> el.store('widget', widget); <del> } <del> ); <del> } <del> ) <del> ); <add> BrickRouge.awakeWidgets(ev.target); <ide> } <ide> ); <ide>
JavaScript
mpl-2.0
6d235c25e808aa6af199026a3a5f91c3340b196a
0
MozillaOnline/pc-sync-tool,MozillaOnline/pc-sync-tool
var ContactList = (function() { var groupedList = null; function getListContainer() { return $id('contact-list-container'); } function toggleFavorite(item) { var favorite = item.classList.toggle('favorite'); var contact = getContact(item.dataset.contactId); if (favorite) { contact.category.push('favorite'); } else { var index = 0; for (; index < contact.category.length; index++) { if ('favorite' == contact.category[index]) { break; } } if (index < contact.category.length) { contact.category.splice(index, 1); } } // Update contact CMD.Contacts.updateContact(JSON.stringify(contact), function onresponse_updatecontact(message) {}, function onerror_updateContact() {}); } function createContactListItem(contact) { var elem = document.createElement('ul'); elem.classList.add('contact-list-item'); if (contact.category && contact.category.indexOf('favorite') > -1) { elem.classList.add('favorite'); } var templateData = { fullName: contact.name ? contact.name.join(' ') : '', tel: '', img: null, }; if (contact.tel) { contact.tel.forEach(function(value, index) { templateData.tel += (index == 0 ? '' : ',') + value.value; }); } elem.dataset.avatar = ''; if (contact.photo && contact.photo.length > 0) { templateData.img = contact.photo; elem.dataset.avatar = contact.photo; } elem.innerHTML = tmpl('tmpl_contact_list_item', templateData); elem.dataset.contact = JSON.stringify(contact); elem.dataset.contactId = contact.id; elem.id = 'contact-' + contact.id; elem.dataset.checked = false; elem.onclick = function onclick_contact_list(event) { var target = event.target; if (target instanceof HTMLLabelElement) { toggleContactItem(elem); } else if (target.classList.contains('bookmark')) { toggleFavorite(elem); } else { contactItemClicked(elem); } }; var searchInput = $id('search-contact-input'); if (!searchInput || searchInput.value.trim().length == 0) { elem.hidden = false; return elem; } var searchInfo = getSearchString(contact); var escapedValue = escapeHTML(searchInfo.join(' '), true); //search key word var key = searchInput.value; elem.hidden = !escapedValue || escapedValue.indexOf(key) == -1; return elem; } function getSearchString(contact) { var searchString = []; var searchTable = ['givenName', 'familyName', 'org', 'tel', 'email']; searchTable.forEach(function(field) { if (!contact[field] || contact[field].length <= 0) { return; } for (var i = contact[field].length - 1; i >= 0; i--) { var current = contact[field][i]; if (!current) { continue; } if (field == 'tel' || field == 'email') { searchString.push(current.value); } else { var value = String(current).trim(); if (value.length > 0) { searchString.push(value); } } } }); return searchString; } function updateUI() { var isEmpty = groupedList.count() == 0; $id('selectAll-contacts').dataset.disabled = isEmpty; $id('empty-contact-container').hidden = !isEmpty; $id('contact-list-container').hidden = isEmpty; updateControls(); var searchInput = $id('search-contact-input'); if (searchInput && searchInput.value.trim()) { var allContactData = groupedList.getGroupedData(); allContactData.forEach(function(group) { var groupIndexItem = $id('id-grouped-data-' + group.index); if (groupIndexItem) { var child = groupIndexItem.childNodes[0]; child.hidden = true; } }); } } function init(viewData) { var loadingGroupId = animationLoading.start(); ViewManager.showViews('contact-quick-add-view'); selectAllContacts(false); var container = getListContainer(); container.innerHTML = ''; groupedList = null; CMD.Contacts.getAllContacts(function onresponse_getAllContacts(message) { // Make sure the 'select-all' box is not checked. var dataJSON = JSON.parse(message.data); initList(container, dataJSON, viewData); animationLoading.stop(loadingGroupId); }, function onerror_getAllContacts(message) { log('Error occurs when fetching all contacts.'); animationLoading.stop(loadingGroupId); }); } function show(viewData) { var searchInput = $id('search-contact-input'); searchInput.value = ''; showSearchList(searchInput.value); var quickName = $id('fullName'); var quickNumber = $id('mobile'); if (quickName) { quickName.value = ''; } if (quickNumber) { if (viewData && (viewData.type == 'add')) { quickNumber.value = viewData.number; } else { quickNumber.value = ''; } } ViewManager.showViews('contact-quick-add-view'); selectAllContacts(false); } function initList(container, contacts, viewData) { var searchInput = $id('search-contact-input'); if (searchInput) { searchInput.value = ''; } var quickName = $id('fullName'); var quickNumber = $id('mobile'); ViewManager.showViews('contact-quick-add-view'); if (quickName) { quickName.value = ''; } if (quickNumber) { quickNumber.value = ''; } if (viewData && (viewData.type == 'add')) { if (quickNumber) { quickNumber.value = viewData.number; } } container.innerHTML = ''; groupedList = null; groupedList = new GroupedList({ dataList: contacts, dataIndexer: function getContactIndex(contact) { // TODO // - index family name for Chinese name // - filter the special chars if (!contact.name[0] || contact.name[0].length == 0) { return '#'; } var firstChar = contact.name[0].charAt(0).toUpperCase(); var pinyin = makePy(firstChar); // Sometimes no pinyin found, like: 红 if (pinyin.length == 0) { return '#'; } return pinyin[0].toUpperCase(); }, dataSorterName: 'name', renderFunc: createContactListItem, container: container, ondatachange: updateUI }); groupedList.render(); updateUI(); customEventElement.removeEventListener('dataChange', onMessage); customEventElement.addEventListener('dataChange', onMessage); } function removeContact(id) { var loadingGroupId = animationLoading.start(); CMD.Contacts.removeContact(id, function onresponse_removeContact(message) { animationLoading.stop(loadingGroupId); }, function onerror_removeContact(message) { animationLoading.stop(loadingGroupId); }); } function selectAllContacts(select) { $expr('#contact-list-container .contact-list-item').forEach(function(elem) { elem.dataset.checked = elem.dataset.focused = select; }); updateControls(); } function contactItemClicked(elem) { $expr('#contact-list-container .contact-list-item[data-checked="true"]').forEach(function(e) { if (e == elem) { return; } e.dataset.checked = e.dataset.focused = false; }); elem.dataset.checked = elem.dataset.focused = true; updateControls(); showContactInfo(JSON.parse(elem.dataset.contact)); } function toggleContactItem(elem) { var select = elem.dataset.checked == 'false'; elem.dataset.checked = elem.dataset.focused = select; updateControls(); item = $expr('#contact-list-container .contact-list-item[data-checked="true"]'); if (item.length == 0) { ViewManager.showViews('contact-quick-add-view'); } else if (item.length == 1) { showContactInfo(JSON.parse(item[0].dataset.contact)); } else { showMultiContactInfo(); } } function updateControls() { if ($expr('#contact-list-container .contact-list-item').length == 0) { $id('selectAll-contacts').dataset.checked = false; $id('selectAll-contacts').dataset.disabled = true; } else { $id('selectAll-contacts').dataset.checked = $expr('#contact-list-container .contact-list-item').length === $expr('#contact-list-container .contact-list-item[data-checked="true"]').length; $id('selectAll-contacts').dataset.disabled = false; } $id('remove-contacts').dataset.disabled = $expr('#contact-list-container .contact-list-item[data-checked="true"]').length === 0; $id('export-contacts').dataset.disabled = $expr('#contact-list-container .contact-list-item[data-checked="true"]').length === 0; } function showContactInfo(contact) { $id('show-contact-full-name').innerHTML = contact && contact.name ? contact.name.join(' ') : ''; $id('show-contact-company').innerHTML = contact && contact.org ? contact.org.join(' ') : ''; var container = $id('show-contact-content'); container.innerHTML = ''; if (contact.tel && contact.tel.length > 0) { contact.tel.forEach(function(item) { var div = document.createElement('div'); div.innerHTML = tmpl('tmpl_contact_tel_digest', { type: item.type[0], value: item.value }); div.classList.add('contact-item'); container.appendChild(div); navigator.mozL10n.translate(div); }); } if (contact.email && contact.email.length > 0) { contact.email.forEach(function(item) { var div = document.createElement('div'); var obj ={}; obj.value = item.value; if (item.type && item.type[0]) { obj.type = item.type[0]; } else { obj.type = 'other'; } div.innerHTML = tmpl('tmpl_contact_email_digest', obj); div.classList.add('contact-item'); navigator.mozL10n.translate(div); container.appendChild(div); }); } if (contact.category && contact.category.indexOf('facebook') != -1) { $id('edit-contact').disabled = true; $id('edit-contact').classList.add('button-disabled'); } else { $id('edit-contact').disabled = false; $id('edit-contact').classList.remove('button-disabled'); $id('edit-contact').onclick = function doEditContact() { ContactForm.editContact(contact); }; } ViewManager.showViews('show-contact-view'); var item = $id('contact-' + contact.id); if (item.dataset.avatar) { $id('show-avatar').src = item.dataset.avatar; $id('show-avatar').classList.remove('avatar-show-default'); } else { $id('show-avatar').removeAttribute('src'); $id('show-avatar').classList.add('avatar-show-default'); } } function showMultiContactInfo() { var num = ""; var selectedContacts = $expr('#contact-list-container .contact-list-item[data-checked="true"]'); var container = $id('show-contacts-container'); container.innerHTML = ''; $id('show-contacts-header').innerHTML = selectedContacts.length; selectedContacts.forEach(function(item) { var contact = JSON.parse(item.dataset.contact); var templateData = { avatar: item.dataset.avatar, name: contact.name.join(' '), tel: contact.tel && contact.tel.length > 0 ? contact.tel[0].value : '' }; var div = document.createElement('div'); div.innerHTML = tmpl('tmpl_contact_vcard_multi_info', templateData); div.classList.add('show-contacts-item'); container.appendChild(div); if (contact.tel && contact.tel.length > 0) { num += contact.name + "(" + contact.tel[0].value + ");"; } }); ViewManager.showViews('show-multi-contacts'); } function addContact(contact) { if (!contact.id) { return; } groupedList.add(contact); } function updateContact(contact) { if (!contact.id) { return; } var existingContact = getContact(contact.id); var isChecked = false; var contactListItems = $expr('#contact-list-container .contact-list-item[data-checked="true"]'); for (var i = 0; i < contactListItems.length; i++) { var item = JSON.parse(contactListItems[i].dataset.contact); if (item.id == contact.id) { isChecked = true; break; } } groupedList.remove(existingContact); groupedList.add(contact); var item = $id('contact-' + contact.id); if (!item) { return; } var img = item.getElementsByTagName('img')[0]; if (!contact.photo || (contact.photo.length == 0)) { img.src = ''; item.dataset.avatar = ''; img.removeAttribute('src'); img.classList.add('avatar-default'); } else { img.src = contact.photo; item.dataset.avatar = contact.photo; img.classList.remove('avatar-default'); } if (isChecked) { if (contactListItems.length == 1) { showContactInfo(contact); } item.dataset.checked = item.dataset.focused = isChecked; } } function getContact(id) { var contactItem = $id('contact-' + id); if (!contactItem) { return null; } return JSON.parse(contactItem.dataset.contact); } function escapeHTML(str, escapeQuotes) { if (Array.isArray(str)) { return escapeHTML(str.join(' '), escapeQuotes); } if (!str || typeof str != 'string') return ''; var escaped = str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); if (escapeQuotes) return escaped.replace(/"/g, '&quot;').replace(/'/g, '&#x27;'); return escaped; } function showSearchList (value) { var allContactData = groupedList.getGroupedData(); allContactData.forEach(function(group) { var groupIndexItem = $id('id-grouped-data-' + group.index); if (groupIndexItem) { var child = groupIndexItem.childNodes[0]; child.hidden = value.length > 0; } group.dataList.forEach(function(contact) { var contactItem = $id('contact-' + contact.id); if (!contactItem || (value.length <= 0)) { contactItem.hidden = false; return; } var searchInfo = getSearchString(contact); var escapedValue = escapeHTML(searchInfo.join(' '), true).toLowerCase(); // search key words var search = value; if ((escapedValue.length > 0) && (escapedValue.indexOf(search.toLowerCase()) >= 0)) { contactItem.hidden = false; } else { contactItem.hidden = true; } }); }); } function onMessage(e) { if (e.detail.type != 'contact') { return; } var changeEvent = e.detail.data; switch (changeEvent.reason) { case 'remove': var item = getContact(changeEvent.contactID); if (!item) { return; } groupedList.remove(item); break; case 'update': CMD.Contacts.getContactById(changeEvent.contactID, function(result) { if (result.data != '' && groupedList) { var contactData = JSON.parse(result.data); updateContact(contactData); } }, null); break; case 'create': CMD.Contacts.getContactById(changeEvent.contactID, function(result) { if (result.data != '' && groupedList) { var contactData = JSON.parse(result.data); addContact(contactData); } }, null); break; default: break; } } window.addEventListener('load', function wnd_onload(event) { $id('selectAll-contacts').onclick = function selectAll_onclick(event) { if (this.dataset.disabled == "true") { return; } if (this.dataset.checked == "false") { selectAllContacts(true); if ($expr('#contact-list-container .contact-list-item[data-checked="true"]').length == 1) { showContactInfo(JSON.parse(elem.dataset.contact)); } if ($expr('#contact-list-container .contact-list-item[data-checked="true"]').length > 1) { showMultiContactInfo(); } } else { selectAllContacts(false); ViewManager.showViews('contact-quick-add-view'); } }; $id('search-contact-input').onkeyup = function onclick_searchContact(event) { showSearchList(this.value); }; $id('search-contact-input').onkeydown = function onclick_searchContact(event) { if(event.keyCode == 13) { event.preventDefault(); } }; $id('remove-contacts').onclick = function onclick_removeContact(event) { // Do nothing if the button is disabled. if (this.dataset.disabled == 'true') { return; } var ids = []; $expr('#contact-list-container .contact-list-item[data-checked="true"]').forEach(function(item) { ids.push(item.dataset.contactId); }); new AlertDialog({ message: _('delete-contacts-confirm', { n: ids.length }), showCancelButton: true, okCallback: function() { if ($id('selectAll-contacts').dataset.checked == "true") { $id('selectAll-contacts').dataset.checked = false; } ids.forEach(function(item) { removeContact(item); }); ViewManager.showViews('contact-quick-add-view'); } }); }; $id('add-new-contact').onclick = function onclick_addNewContact(event) { ContactForm.editContact(); }; $id('refresh-contacts').onclick = function onclick_refreshContacts(event) { init(); }; $id('import-contacts').onclick = function onclick_importContacts(event) { readFromDisk(function(state, data) { if (state) { vCardConverter.importContacts(data); } }); }; $id('export-contacts').onclick = function onclick_exportContacts(event) { // Do nothing if the button is disabled. if (this.dataset.disabled == 'true') { return; } var content = ''; $expr('#contact-list-container .contact-list-item[data-checked="true"]').forEach(function(item) { var contact = JSON.parse(item.dataset.contact); var vcard = vCardConverter.exportContact(contact); content += vcard + '\n'; }); saveToDisk(content, function(status) { if (status) { new AlertDialog({ message: _('export-contacts-success') }); } }, { title: _('export-contacts-title'), name: 'contacts.vcf', extension: 'vcf' }); }; }); return { init: init, show: show, getContact: getContact }; })();
content/js/contactList.js
var ContactList = (function() { var groupedList = null; function getListContainer() { return $id('contact-list-container'); } function toggleFavorite(item) { var favorite = item.classList.toggle('favorite'); var contact = getContact(item.dataset.contactId); if (favorite) { contact.category.push('favorite'); } else { var index = 0; for (; index < contact.category.length; index++) { if ('favorite' == contact.category[index]) { break; } } if (index < contact.category.length) { contact.category.splice(index, 1); } } // Update contact CMD.Contacts.updateContact(JSON.stringify(contact), function onresponse_updatecontact(message) {}, function onerror_updateContact() {}); } function createContactListItem(contact) { var elem = document.createElement('ul'); elem.classList.add('contact-list-item'); if (contact.category && contact.category.indexOf('favorite') > -1) { elem.classList.add('favorite'); } var templateData = { fullName: contact.name ? contact.name.join(' ') : '', tel: '', img: null, }; if (contact.tel) { contact.tel.forEach(function(value, index) { templateData.tel += (index == 0 ? '' : ',') + value.value; }); } elem.dataset.avatar = ''; if (contact.photo && contact.photo.length > 0) { templateData.img = contact.photo; elem.dataset.avatar = contact.photo; } elem.innerHTML = tmpl('tmpl_contact_list_item', templateData); elem.dataset.contact = JSON.stringify(contact); elem.dataset.contactId = contact.id; elem.id = 'contact-' + contact.id; elem.dataset.checked = false; elem.onclick = function onclick_contact_list(event) { var target = event.target; if (target instanceof HTMLLabelElement) { toggleContactItem(elem); } else if (target.classList.contains('bookmark')) { toggleFavorite(elem); } else { contactItemClicked(elem); } }; var searchInput = $id('search-contact-input'); if (!searchInput || searchInput.value.trim().length == 0) { elem.hidden = false; return elem; } var searchInfo = getSearchString(contact); var escapedValue = escapeHTML(searchInfo.join(' '), true); //search key word var key = searchInput.value; elem.hidden = !escapedValue || escapedValue.indexOf(key) == -1; return elem; } function getSearchString(contact) { var searchString = []; var searchTable = ['givenName', 'familyName', 'org', 'tel', 'email']; searchTable.forEach(function(field) { if (!contact[field] || contact[field].length <= 0) { return; } for (var i = contact[field].length - 1; i >= 0; i--) { var current = contact[field][i]; if (!current) { continue; } if (field == 'tel' || field == 'email') { searchString.push(current.value); } else { var value = String(current).trim(); if (value.length > 0) { searchString.push(value); } } } }); return searchString; } function updateUI() { var isEmpty = groupedList.count() == 0; $id('selectAll-contacts').dataset.disabled = isEmpty; $id('empty-contact-container').hidden = !isEmpty; $id('contact-list-container').hidden = isEmpty; updateControls(); var searchInput = $id('search-contact-input'); if (searchInput && searchInput.value.trim()) { var allContactData = groupedList.getGroupedData(); allContactData.forEach(function(group) { var groupIndexItem = $id('id-grouped-data-' + group.index); if (groupIndexItem) { var child = groupIndexItem.childNodes[0]; child.hidden = true; } }); } } function init(viewData) { var loadingGroupId = animationLoading.start(); ViewManager.showViews('contact-quick-add-view'); selectAllContacts(false); var container = getListContainer(); container.innerHTML = ''; groupedList = null; CMD.Contacts.getAllContacts(function onresponse_getAllContacts(message) { // Make sure the 'select-all' box is not checked. var dataJSON = JSON.parse(message.data); initList(container, dataJSON, viewData); animationLoading.stop(loadingGroupId); }, function onerror_getAllContacts(message) { log('Error occurs when fetching all contacts.'); animationLoading.stop(loadingGroupId); }); } function show(viewData) { var searchInput = $id('search-contact-input'); searchInput.value = ''; showSearchList(searchInput.value); var quickName = $id('fullName'); var quickNumber = $id('mobile'); if (quickName) { quickName.value = ''; } if (quickNumber) { if (viewData && (viewData.type == 'add')) { quickNumber.value = viewData.number; } else { quickNumber.value = ''; } } ViewManager.showViews('contact-quick-add-view'); selectAllContacts(false); } function initList(container, contacts, viewData) { var searchInput = $id('search-contact-input'); if (searchInput) { searchInput.value = ''; } var quickName = $id('fullName'); var quickNumber = $id('mobile'); ViewManager.showViews('contact-quick-add-view'); if (quickName) { quickName.value = ''; } if (quickNumber) { quickNumber.value = ''; } if (viewData && (viewData.type == 'add')) { if (quickNumber) { quickNumber.value = viewData.number; } } groupedList = new GroupedList({ dataList: contacts, dataIndexer: function getContactIndex(contact) { // TODO // - index family name for Chinese name // - filter the special chars if (!contact.name[0] || contact.name[0].length == 0) { return '#'; } var firstChar = contact.name[0].charAt(0).toUpperCase(); var pinyin = makePy(firstChar); // Sometimes no pinyin found, like: 红 if (pinyin.length == 0) { return '#'; } return pinyin[0].toUpperCase(); }, dataSorterName: 'name', renderFunc: createContactListItem, container: container, ondatachange: updateUI }); groupedList.render(); updateUI(); customEventElement.removeEventListener('dataChange', onMessage); customEventElement.addEventListener('dataChange', onMessage); } function removeContact(id) { var loadingGroupId = animationLoading.start(); CMD.Contacts.removeContact(id, function onresponse_removeContact(message) { animationLoading.stop(loadingGroupId); }, function onerror_removeContact(message) { animationLoading.stop(loadingGroupId); }); } function selectAllContacts(select) { $expr('#contact-list-container .contact-list-item').forEach(function(elem) { elem.dataset.checked = elem.dataset.focused = select; }); updateControls(); } function contactItemClicked(elem) { $expr('#contact-list-container .contact-list-item[data-checked="true"]').forEach(function(e) { if (e == elem) { return; } e.dataset.checked = e.dataset.focused = false; }); elem.dataset.checked = elem.dataset.focused = true; updateControls(); showContactInfo(JSON.parse(elem.dataset.contact)); } function toggleContactItem(elem) { var select = elem.dataset.checked == 'false'; elem.dataset.checked = elem.dataset.focused = select; updateControls(); item = $expr('#contact-list-container .contact-list-item[data-checked="true"]'); if (item.length == 0) { ViewManager.showViews('contact-quick-add-view'); } else if (item.length == 1) { showContactInfo(JSON.parse(item[0].dataset.contact)); } else { showMultiContactInfo(); } } function updateControls() { if ($expr('#contact-list-container .contact-list-item').length == 0) { $id('selectAll-contacts').dataset.checked = false; $id('selectAll-contacts').dataset.disabled = true; } else { $id('selectAll-contacts').dataset.checked = $expr('#contact-list-container .contact-list-item').length === $expr('#contact-list-container .contact-list-item[data-checked="true"]').length; $id('selectAll-contacts').dataset.disabled = false; } $id('remove-contacts').dataset.disabled = $expr('#contact-list-container .contact-list-item[data-checked="true"]').length === 0; $id('export-contacts').dataset.disabled = $expr('#contact-list-container .contact-list-item[data-checked="true"]').length === 0; } function showContactInfo(contact) { $id('show-contact-full-name').innerHTML = contact && contact.name ? contact.name.join(' ') : ''; $id('show-contact-company').innerHTML = contact && contact.org ? contact.org.join(' ') : ''; var container = $id('show-contact-content'); container.innerHTML = ''; if (contact.tel && contact.tel.length > 0) { contact.tel.forEach(function(item) { var div = document.createElement('div'); div.innerHTML = tmpl('tmpl_contact_tel_digest', { type: item.type[0], value: item.value }); div.classList.add('contact-item'); container.appendChild(div); navigator.mozL10n.translate(div); }); } if (contact.email && contact.email.length > 0) { contact.email.forEach(function(item) { var div = document.createElement('div'); var obj ={}; obj.value = item.value; if (item.type && item.type[0]) { obj.type = item.type[0]; } else { obj.type = 'other'; } div.innerHTML = tmpl('tmpl_contact_email_digest', obj); div.classList.add('contact-item'); navigator.mozL10n.translate(div); container.appendChild(div); }); } if (contact.category && contact.category.indexOf('facebook') != -1) { $id('edit-contact').disabled = true; $id('edit-contact').classList.add('button-disabled'); } else { $id('edit-contact').disabled = false; $id('edit-contact').classList.remove('button-disabled'); $id('edit-contact').onclick = function doEditContact() { ContactForm.editContact(contact); }; } ViewManager.showViews('show-contact-view'); var item = $id('contact-' + contact.id); if (item.dataset.avatar) { $id('show-avatar').src = item.dataset.avatar; $id('show-avatar').classList.remove('avatar-show-default'); } else { $id('show-avatar').removeAttribute('src'); $id('show-avatar').classList.add('avatar-show-default'); } } function showMultiContactInfo() { var num = ""; var selectedContacts = $expr('#contact-list-container .contact-list-item[data-checked="true"]'); var container = $id('show-contacts-container'); container.innerHTML = ''; $id('show-contacts-header').innerHTML = selectedContacts.length; selectedContacts.forEach(function(item) { var contact = JSON.parse(item.dataset.contact); var templateData = { avatar: item.dataset.avatar, name: contact.name.join(' '), tel: contact.tel && contact.tel.length > 0 ? contact.tel[0].value : '' }; var div = document.createElement('div'); div.innerHTML = tmpl('tmpl_contact_vcard_multi_info', templateData); div.classList.add('show-contacts-item'); container.appendChild(div); if (contact.tel && contact.tel.length > 0) { num += contact.name + "(" + contact.tel[0].value + ");"; } }); ViewManager.showViews('show-multi-contacts'); } function addContact(contact) { if (!contact.id) { return; } groupedList.add(contact); } function updateContact(contact) { if (!contact.id) { return; } var existingContact = getContact(contact.id); var isChecked = false; var contactListItems = $expr('#contact-list-container .contact-list-item[data-checked="true"]'); for (var i = 0; i < contactListItems.length; i++) { var item = JSON.parse(contactListItems[i].dataset.contact); if (item.id == contact.id) { isChecked = true; break; } } groupedList.remove(existingContact); groupedList.add(contact); var item = $id('contact-' + contact.id); if (!item) { return; } var img = item.getElementsByTagName('img')[0]; if (!contact.photo || (contact.photo.length == 0)) { img.src = ''; item.dataset.avatar = ''; img.removeAttribute('src'); img.classList.add('avatar-default'); } else { img.src = contact.photo; item.dataset.avatar = contact.photo; img.classList.remove('avatar-default'); } if (isChecked) { if (contactListItems.length == 1) { showContactInfo(contact); } item.dataset.checked = item.dataset.focused = isChecked; } } function getContact(id) { var contactItem = $id('contact-' + id); if (!contactItem) { return null; } return JSON.parse(contactItem.dataset.contact); } function escapeHTML(str, escapeQuotes) { if (Array.isArray(str)) { return escapeHTML(str.join(' '), escapeQuotes); } if (!str || typeof str != 'string') return ''; var escaped = str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); if (escapeQuotes) return escaped.replace(/"/g, '&quot;').replace(/'/g, '&#x27;'); return escaped; } function showSearchList (value) { var allContactData = groupedList.getGroupedData(); allContactData.forEach(function(group) { var groupIndexItem = $id('id-grouped-data-' + group.index); if (groupIndexItem) { var child = groupIndexItem.childNodes[0]; child.hidden = value.length > 0; } group.dataList.forEach(function(contact) { var contactItem = $id('contact-' + contact.id); if (!contactItem || (value.length <= 0)) { contactItem.hidden = false; return; } var searchInfo = getSearchString(contact); var escapedValue = escapeHTML(searchInfo.join(' '), true).toLowerCase(); // search key words var search = value; if ((escapedValue.length > 0) && (escapedValue.indexOf(search.toLowerCase()) >= 0)) { contactItem.hidden = false; } else { contactItem.hidden = true; } }); }); } function onMessage(e) { if (e.detail.type != 'contact') { return; } var changeEvent = e.detail.data; switch (changeEvent.reason) { case 'remove': var item = getContact(changeEvent.contactID); if (!item) { return; } groupedList.remove(item); break; case 'update': CMD.Contacts.getContactById(changeEvent.contactID, function(result) { if (result.data != '' && groupedList) { var contactData = JSON.parse(result.data); updateContact(contactData); } }, null); break; case 'create': CMD.Contacts.getContactById(changeEvent.contactID, function(result) { if (result.data != '' && groupedList) { var contactData = JSON.parse(result.data); addContact(contactData); } }, null); break; default: break; } } window.addEventListener('load', function wnd_onload(event) { $id('selectAll-contacts').onclick = function selectAll_onclick(event) { if (this.dataset.disabled == "true") { return; } if (this.dataset.checked == "false") { selectAllContacts(true); if ($expr('#contact-list-container .contact-list-item[data-checked="true"]').length == 1) { showContactInfo(JSON.parse(elem.dataset.contact)); } if ($expr('#contact-list-container .contact-list-item[data-checked="true"]').length > 1) { showMultiContactInfo(); } } else { selectAllContacts(false); ViewManager.showViews('contact-quick-add-view'); } }; $id('search-contact-input').onkeyup = function onclick_searchContact(event) { showSearchList(this.value); }; $id('search-contact-input').onkeydown = function onclick_searchContact(event) { if(event.keyCode == 13) { event.preventDefault(); } }; $id('remove-contacts').onclick = function onclick_removeContact(event) { // Do nothing if the button is disabled. if (this.dataset.disabled == 'true') { return; } var ids = []; $expr('#contact-list-container .contact-list-item[data-checked="true"]').forEach(function(item) { ids.push(item.dataset.contactId); }); new AlertDialog({ message: _('delete-contacts-confirm', { n: ids.length }), showCancelButton: true, okCallback: function() { if ($id('selectAll-contacts').dataset.checked == "true") { $id('selectAll-contacts').dataset.checked = false; } ids.forEach(function(item) { removeContact(item); }); ViewManager.showViews('contact-quick-add-view'); } }); }; $id('add-new-contact').onclick = function onclick_addNewContact(event) { ContactForm.editContact(); }; $id('refresh-contacts').onclick = function onclick_refreshContacts(event) { init(); }; $id('import-contacts').onclick = function onclick_importContacts(event) { readFromDisk(function(state, data) { if (state) { vCardConverter.importContacts(data); } }); }; $id('export-contacts').onclick = function onclick_exportContacts(event) { // Do nothing if the button is disabled. if (this.dataset.disabled == 'true') { return; } var content = ''; $expr('#contact-list-container .contact-list-item[data-checked="true"]').forEach(function(item) { var contact = JSON.parse(item.dataset.contact); var vcard = vCardConverter.exportContact(contact); content += vcard + '\n'; }); saveToDisk(content, function(status) { if (status) { new AlertDialog({ message: _('export-contacts-success') }); } }, { title: _('export-contacts-title'), name: 'contacts.vcf', extension: 'vcf' }); }; }); return { init: init, show: show, getContact: getContact }; })();
modify refresh contact
content/js/contactList.js
modify refresh contact
<ide><path>ontent/js/contactList.js <ide> quickNumber.value = viewData.number; <ide> } <ide> } <add> <add> container.innerHTML = ''; <add> groupedList = null; <ide> <ide> groupedList = new GroupedList({ <ide> dataList: contacts,
Java
apache-2.0
42fe80b4b3a88e3975c8825b9e2aeaccf26fb3cd
0
vladmm/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,ryano144/intellij-community,petteyg/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,caot/intellij-community,holmes/intellij-community,supersven/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,vladmm/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,hurricup/intellij-community,slisson/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,blademainer/intellij-community,blademainer/intellij-community,jagguli/intellij-community,clumsy/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,supersven/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,fnouama/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,izonder/intellij-community,vladmm/intellij-community,ibinti/intellij-community,retomerz/intellij-community,da1z/intellij-community,diorcety/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,jexp/idea2,semonte/intellij-community,robovm/robovm-studio,semonte/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,supersven/intellij-community,asedunov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,kdwink/intellij-community,kdwink/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,jagguli/intellij-community,signed/intellij-community,izonder/intellij-community,da1z/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,kool79/intellij-community,allotria/intellij-community,holmes/intellij-community,Distrotech/intellij-community,supersven/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,jexp/idea2,TangHao1987/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,joewalnes/idea-community,xfournet/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,jexp/idea2,amith01994/intellij-community,joewalnes/idea-community,semonte/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,supersven/intellij-community,allotria/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,slisson/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,consulo/consulo,mglukhikh/intellij-community,asedunov/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,consulo/consulo,slisson/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,caot/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,jexp/idea2,MER-GROUP/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,samthor/intellij-community,kdwink/intellij-community,samthor/intellij-community,signed/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,holmes/intellij-community,tmpgit/intellij-community,samthor/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ernestp/consulo,fnouama/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,xfournet/intellij-community,signed/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,jagguli/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,allotria/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,izonder/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,asedunov/intellij-community,semonte/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ernestp/consulo,vladmm/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,holmes/intellij-community,signed/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,allotria/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,caot/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,caot/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,jagguli/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,slisson/intellij-community,adedayo/intellij-community,jagguli/intellij-community,kdwink/intellij-community,dslomov/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,retomerz/intellij-community,kool79/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,semonte/intellij-community,jexp/idea2,TangHao1987/intellij-community,consulo/consulo,gnuhub/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,joewalnes/idea-community,xfournet/intellij-community,signed/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,supersven/intellij-community,dslomov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,xfournet/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,da1z/intellij-community,izonder/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,dslomov/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,izonder/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,allotria/intellij-community,petteyg/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,robovm/robovm-studio,holmes/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,gnuhub/intellij-community,signed/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,samthor/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,caot/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,caot/intellij-community,da1z/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,jexp/idea2,fnouama/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,holmes/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,consulo/consulo,robovm/robovm-studio,suncycheng/intellij-community,fnouama/intellij-community,blademainer/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,hurricup/intellij-community,clumsy/intellij-community,fitermay/intellij-community,consulo/consulo,pwoodworth/intellij-community,samthor/intellij-community,kool79/intellij-community,blademainer/intellij-community,slisson/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,kool79/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,semonte/intellij-community,tmpgit/intellij-community,consulo/consulo,fitermay/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,clumsy/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,FHannes/intellij-community,dslomov/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,robovm/robovm-studio,adedayo/intellij-community,caot/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,amith01994/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,ibinti/intellij-community,jagguli/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,robovm/robovm-studio,hurricup/intellij-community,adedayo/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,joewalnes/idea-community,caot/intellij-community,fitermay/intellij-community,signed/intellij-community,adedayo/intellij-community,ibinti/intellij-community,diorcety/intellij-community,dslomov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,allotria/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,jexp/idea2,pwoodworth/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,kdwink/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ibinti/intellij-community,petteyg/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,supersven/intellij-community,Distrotech/intellij-community,izonder/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,kool79/intellij-community,apixandru/intellij-community,ryano144/intellij-community,kool79/intellij-community,caot/intellij-community,FHannes/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,ahb0327/intellij-community,allotria/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,retomerz/intellij-community,ryano144/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,da1z/intellij-community,da1z/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,semonte/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,supersven/intellij-community,caot/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,apixandru/intellij-community,holmes/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,supersven/intellij-community,jexp/idea2,allotria/intellij-community,xfournet/intellij-community,blademainer/intellij-community,holmes/intellij-community,ibinti/intellij-community,kool79/intellij-community,samthor/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,FHannes/intellij-community,signed/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community
package com.intellij.refactoring.inline; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.ConflictsUtil; import com.intellij.refactoring.util.RefactoringUIUtil; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashSet; /** * @author ven */ class InlineConstantFieldProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.inline.InlineConstantFieldProcessor"); private PsiField myField; private final PsiReferenceExpression myRefExpr; private final boolean myInlineThisOnly; InlineConstantFieldProcessor(PsiField field, Project project, PsiReferenceExpression ref, boolean isInlineThisOnly) { super(project); myField = field; myRefExpr = ref; myInlineThisOnly = isInlineThisOnly; } protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) { return new InlineViewDescriptor(myField); } @NotNull protected UsageInfo[] findUsages() { if (myInlineThisOnly) return new UsageInfo[]{new UsageInfo(myRefExpr)}; PsiReference[] refs = ReferencesSearch.search(myField, GlobalSearchScope.projectScope(myProject), false).toArray(new PsiReference[0]); UsageInfo[] infos = new UsageInfo[refs.length]; for (int i = 0; i < refs.length; i++) { infos[i] = new UsageInfo(refs[i].getElement()); } return infos; } protected void refreshElements(PsiElement[] elements) { LOG.assertTrue(elements.length == 1 && elements[0] instanceof PsiField); myField = (PsiField)elements[0]; } protected void performRefactoring(UsageInfo[] usages) { PsiExpression initializer = myField.getInitializer(); LOG.assertTrue(initializer != null); PsiConstantEvaluationHelper evalHelper = JavaPsiFacade.getInstance(myField.getProject()).getConstantEvaluationHelper(); initializer = normalize ((PsiExpression)initializer.copy()); for (UsageInfo usage : usages) { final PsiElement element = usage.getElement(); try { if (element instanceof PsiExpression) { inlineExpressionUsage((PsiExpression)element, evalHelper, initializer); } else { PsiImportStaticStatement importStaticStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class); LOG.assertTrue(importStaticStatement != null, element.getText()); importStaticStatement.delete(); } } catch (IncorrectOperationException e) { LOG.error(e); } } if (!myInlineThisOnly) { try { myField.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } } } private void inlineExpressionUsage(PsiExpression expr, final PsiConstantEvaluationHelper evalHelper, PsiExpression initializer1) throws IncorrectOperationException { while (expr.getParent() instanceof PsiArrayAccessExpression) { PsiArrayAccessExpression arrayAccess = (PsiArrayAccessExpression)expr.getParent(); Object value = evalHelper.computeConstantExpression(arrayAccess.getIndexExpression()); if (value instanceof Integer) { int intValue = ((Integer)value).intValue(); if (initializer1 instanceof PsiNewExpression) { PsiExpression[] arrayInitializers = ((PsiNewExpression)initializer1).getArrayInitializer().getInitializers(); if (0 <= intValue && intValue < arrayInitializers.length) { expr = (PsiExpression)expr.getParent(); initializer1 = normalize(arrayInitializers[intValue]); continue; } } } break; } myField.normalizeDeclaration(); ChangeContextUtil.encodeContextInfo(initializer1, true); PsiElement element = expr.replace(initializer1); ChangeContextUtil.decodeContextInfo(element, null, null); } private static PsiExpression normalize(PsiExpression expression) { if (expression instanceof PsiArrayInitializerExpression) { PsiElementFactory factory = JavaPsiFacade.getInstance(expression.getProject()).getElementFactory(); try { final PsiType type = expression.getType(); if (type != null) { String typeString = type.getCanonicalText(); PsiNewExpression result = (PsiNewExpression)factory.createExpressionFromText("new " + typeString + "{}", expression); result.getArrayInitializer().replace(expression); return result; } } catch (IncorrectOperationException e) { LOG.error(e); return expression; } } return expression; } protected String getCommandName() { return RefactoringBundle.message("inline.field.command", UsageViewUtil.getDescriptiveName(myField)); } protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) { UsageInfo[] usagesIn = refUsages.get(); ArrayList<String> conflicts = new ArrayList<String>(); ReferencedElementsCollector collector = new ReferencedElementsCollector(); PsiExpression initializer = myField.getInitializer(); LOG.assertTrue(initializer != null); initializer.accept(collector); HashSet<PsiMember> referencedWithVisibility = collector.myReferencedMembers; PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(myField.getProject()).getResolveHelper(); for (UsageInfo info : usagesIn) { PsiElement element = info.getElement(); if (element instanceof PsiExpression && isAccessedForWriting((PsiExpression)element)) { String message = RefactoringBundle.message("0.is.used.for.writing.in.1", RefactoringUIUtil.getDescription(myField, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true)); conflicts.add(message); } for (PsiMember member : referencedWithVisibility) { if (!resolveHelper.isAccessible(member, element, null)) { String message = RefactoringBundle.message("0.will.not.be.accessible.from.1.after.inlining", RefactoringUIUtil.getDescription(member, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true)); conflicts.add(message); } } } return showConflicts(conflicts); } private static boolean isAccessedForWriting (PsiExpression expr) { while(expr.getParent() instanceof PsiArrayAccessExpression) { expr = (PsiExpression)expr.getParent(); } return PsiUtil.isAccessedForWriting(expr); } }
refactoring/impl/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java
package com.intellij.refactoring.inline; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.ConflictsUtil; import com.intellij.refactoring.util.RefactoringUIUtil; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashSet; /** * @author ven */ class InlineConstantFieldProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.inline.InlineConstantFieldProcessor"); private PsiField myField; private final PsiReferenceExpression myRefExpr; private final boolean myInlineThisOnly; public InlineConstantFieldProcessor(PsiField field, Project project, PsiReferenceExpression ref, boolean isInlineThisOnly) { super(project); myField = field; myRefExpr = ref; myInlineThisOnly = isInlineThisOnly; } protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) { return new InlineViewDescriptor(myField); } @NotNull protected UsageInfo[] findUsages() { if (myInlineThisOnly) return new UsageInfo[]{new UsageInfo(myRefExpr)}; PsiReference[] refs = ReferencesSearch.search(myField, GlobalSearchScope.projectScope(myProject), false).toArray(new PsiReference[0]); UsageInfo[] infos = new UsageInfo[refs.length]; for (int i = 0; i < refs.length; i++) { infos[i] = new UsageInfo(refs[i].getElement()); } return infos; } protected void refreshElements(PsiElement[] elements) { LOG.assertTrue(elements.length == 1 && elements[0] instanceof PsiField); myField = (PsiField)elements[0]; } protected void performRefactoring(UsageInfo[] usages) { PsiExpression initializer = myField.getInitializer(); LOG.assertTrue(initializer != null); PsiConstantEvaluationHelper evalHelper = JavaPsiFacade.getInstance(myField.getProject()).getConstantEvaluationHelper(); initializer = normalize ((PsiExpression)initializer.copy()); for (UsageInfo usage : usages) { final PsiElement element = usage.getElement(); try { if (element instanceof PsiExpression) { inlineExpressionUsage(((PsiExpression)element), evalHelper, initializer); } else { PsiImportStaticStatement importStaticStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class); LOG.assertTrue(importStaticStatement != null); importStaticStatement.delete(); } } catch (IncorrectOperationException e) { LOG.error(e); } } if (!myInlineThisOnly) { try { myField.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } } } private void inlineExpressionUsage(PsiExpression expr, final PsiConstantEvaluationHelper evalHelper, PsiExpression initializer1) throws IncorrectOperationException { while (expr.getParent() instanceof PsiArrayAccessExpression) { PsiArrayAccessExpression arrayAccess = ((PsiArrayAccessExpression)expr.getParent()); Object value = evalHelper.computeConstantExpression(arrayAccess.getIndexExpression()); if (value instanceof Integer) { int intValue = ((Integer)value).intValue(); if (initializer1 instanceof PsiNewExpression) { PsiExpression[] arrayInitializers = ((PsiNewExpression)initializer1).getArrayInitializer().getInitializers(); if (0 <= intValue && intValue < arrayInitializers.length) { expr = (PsiExpression)expr.getParent(); initializer1 = normalize(arrayInitializers[intValue]); continue; } } } break; } myField.normalizeDeclaration(); ChangeContextUtil.encodeContextInfo(initializer1, true); PsiElement element = expr.replace(initializer1); ChangeContextUtil.decodeContextInfo(element, null, null); } private static PsiExpression normalize(PsiExpression expression) { if (expression instanceof PsiArrayInitializerExpression) { PsiElementFactory factory = JavaPsiFacade.getInstance(expression.getProject()).getElementFactory(); try { final PsiType type = expression.getType(); if (type != null) { String typeString = type.getCanonicalText(); PsiNewExpression result = (PsiNewExpression)factory.createExpressionFromText("new " + typeString + "{}", expression); result.getArrayInitializer().replace(expression); return result; } } catch (IncorrectOperationException e) { LOG.error(e); return expression; } } return expression; } protected String getCommandName() { return RefactoringBundle.message("inline.field.command", UsageViewUtil.getDescriptiveName(myField)); } protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) { UsageInfo[] usagesIn = refUsages.get(); ArrayList<String> conflicts = new ArrayList<String>(); ReferencedElementsCollector collector = new ReferencedElementsCollector(); PsiExpression initializer = myField.getInitializer(); LOG.assertTrue(initializer != null); initializer.accept(collector); HashSet<PsiMember> referencedWithVisibility = collector.myReferencedMembers; PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(myField.getProject()).getResolveHelper(); for (UsageInfo info : usagesIn) { PsiElement element = info.getElement(); if (element instanceof PsiExpression && isAccessedForWriting((PsiExpression)element)) { String message = RefactoringBundle.message("0.is.used.for.writing.in.1", RefactoringUIUtil.getDescription(myField, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true)); conflicts.add(message); } for (PsiMember member : referencedWithVisibility) { if (!resolveHelper.isAccessible(member, element, null)) { String message = RefactoringBundle.message("0.will.not.be.accessible.from.1.after.inlining", RefactoringUIUtil.getDescription(member, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true)); conflicts.add(message); } } } return showConflicts(conflicts); } private static boolean isAccessedForWriting (PsiExpression expr) { while(expr.getParent() instanceof PsiArrayAccessExpression) { expr = (PsiExpression)expr.getParent(); } return PsiUtil.isAccessedForWriting(expr); } }
assertion for IDEADEV-35545
refactoring/impl/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java
assertion for IDEADEV-35545
<ide><path>efactoring/impl/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java <ide> private final PsiReferenceExpression myRefExpr; <ide> private final boolean myInlineThisOnly; <ide> <del> public InlineConstantFieldProcessor(PsiField field, Project project, PsiReferenceExpression ref, boolean isInlineThisOnly) { <add> InlineConstantFieldProcessor(PsiField field, Project project, PsiReferenceExpression ref, boolean isInlineThisOnly) { <ide> super(project); <ide> myField = field; <ide> myRefExpr = ref; <ide> final PsiElement element = usage.getElement(); <ide> try { <ide> if (element instanceof PsiExpression) { <del> inlineExpressionUsage(((PsiExpression)element), evalHelper, initializer); <add> inlineExpressionUsage((PsiExpression)element, evalHelper, initializer); <ide> } <ide> else { <ide> PsiImportStaticStatement importStaticStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class); <del> LOG.assertTrue(importStaticStatement != null); <add> LOG.assertTrue(importStaticStatement != null, element.getText()); <ide> importStaticStatement.delete(); <ide> } <ide> } <ide> final PsiConstantEvaluationHelper evalHelper, <ide> PsiExpression initializer1) throws IncorrectOperationException { <ide> while (expr.getParent() instanceof PsiArrayAccessExpression) { <del> PsiArrayAccessExpression arrayAccess = ((PsiArrayAccessExpression)expr.getParent()); <add> PsiArrayAccessExpression arrayAccess = (PsiArrayAccessExpression)expr.getParent(); <ide> Object value = evalHelper.computeConstantExpression(arrayAccess.getIndexExpression()); <ide> if (value instanceof Integer) { <ide> int intValue = ((Integer)value).intValue();
Java
agpl-3.0
a55becfb50a2267fd86bdc11d558fe10bf7eaf4d
0
CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine
package com.splicemachine.test.connection; import com.splicemachine.constants.SpliceConstants; import java.sql.Connection; import java.sql.DriverManager; import org.apache.log4j.Logger; /** * Static helper class to get an client connection to Splice */ public class SpliceNetConnection extends BaseConnection { private static final Logger LOG = Logger.getLogger(SpliceNetConnection.class); private static String driver = "org.apache.derby.jdbc.ClientDriver"; private static String protocol = "jdbc:derby://localhost:"; private static String db = "/splicedb"; private static String createProtocol(String port, boolean createDB) { return protocol+(port != null?port: SpliceConstants.DEFAULT_DERBY_BIND_PORT)+db+(createDB?create:""); } private static synchronized Connection createConnection(String port) throws Exception { loadDriver(clientDriver); return DriverManager.getConnection(createProtocol(port, true), props); } /** * Acquire a connection * @param port optional port to connect to * @return a new connection * @throws Exception for any failure */ public static Connection getConnection(String port) throws Exception { if (!loaded) { return createConnection(port); } else { return DriverManager.getConnection(createProtocol(port,false), props); } } }
structured_test/src/main/java/com/splicemachine/test/connection/SpliceNetConnection.java
package com.splicemachine.test.connection; import com.splicemachine.constants.SpliceConstants; import java.sql.Connection; import java.sql.DriverManager; import org.apache.log4j.Logger; /** * Static helper class to get an client connection to Splice */ public class SpliceNetConnection extends BaseConnection { private static final Logger LOG = Logger.getLogger(SpliceNetConnection.class); private static String driver = "org.apache.derby.jdbc.ClientDriver"; private static String protocol = "jdbc:derby://localhost:"; private static String db = "/spliceDB"; private static String createProtocol(String port, boolean createDB) { return protocol+(port != null?port: SpliceConstants.DEFAULT_DERBY_BIND_PORT)+db+(createDB?create:""); } private static synchronized Connection createConnection(String port) throws Exception { loadDriver(clientDriver); return DriverManager.getConnection(createProtocol(port, true), props); } /** * Acquire a connection * @param port optional port to connect to * @return a new connection * @throws Exception for any failure */ public static Connection getConnection(String port) throws Exception { if (!loaded) { return createConnection(port); } else { return DriverManager.getConnection(createProtocol(port,false), props); } } }
Fix DB name in NIST tests
structured_test/src/main/java/com/splicemachine/test/connection/SpliceNetConnection.java
Fix DB name in NIST tests
<ide><path>tructured_test/src/main/java/com/splicemachine/test/connection/SpliceNetConnection.java <ide> <ide> private static String driver = "org.apache.derby.jdbc.ClientDriver"; <ide> private static String protocol = "jdbc:derby://localhost:"; <del> private static String db = "/spliceDB"; <add> private static String db = "/splicedb"; <ide> <ide> private static String createProtocol(String port, boolean createDB) { <ide> return protocol+(port != null?port: SpliceConstants.DEFAULT_DERBY_BIND_PORT)+db+(createDB?create:"");
Java
apache-2.0
f86f7e62c49f33271af880a1d159de82af1d4d4b
0
YUKAI/konashi-android-sdk,YUKAI/konashi-android-sdk,kiryuxxu/konashi-android-sdk
package com.uxxu.konashi.sample.i2csample; import android.bluetooth.BluetoothGattCharacteristic; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.uxxu.konashi.lib.Konashi; import com.uxxu.konashi.lib.KonashiListener; import com.uxxu.konashi.lib.KonashiManager; import org.jdeferred.DoneCallback; import org.jdeferred.DonePipe; import org.jdeferred.FailCallback; import org.jdeferred.Promise; import info.izumin.android.bletia.BletiaException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private final MainActivity self = this; private static final byte I2C_ADDRESS = 0x01f; private KonashiManager mKonashiManager; private EditText mSendEdit; private TextView mResultText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_send).setOnClickListener(this); findViewById(R.id.btn_read).setOnClickListener(this); findViewById(R.id.btn_find).setOnClickListener(this); mSendEdit = (EditText) findViewById(R.id.edit_send); mResultText = (TextView) findViewById(R.id.text_read); mKonashiManager = new KonashiManager(); } @Override protected void onResume() { super.onResume(); mKonashiManager.addListener(mKonashiListener); mKonashiManager.initialize(this); refreshViews(); } @Override protected void onPause() { mKonashiManager.removeListener(mKonashiListener); super.onPause(); } @Override protected void onDestroy() { new Thread(new Runnable() { @Override public void run() { mKonashiManager.reset() .then(new DoneCallback<BluetoothGattCharacteristic>() { @Override public void onDone(BluetoothGattCharacteristic result) { mKonashiManager.disconnect(); } }); } }).start(); super.onDestroy(); } private void refreshViews() { boolean isReady = mKonashiManager.isReady(); findViewById(R.id.btn_find).setVisibility(!isReady ? View.VISIBLE : View.GONE); findViewById(R.id.btn_send).setVisibility(isReady ? View.VISIBLE : View.GONE); findViewById(R.id.btn_read).setVisibility(isReady ? View.VISIBLE : View.GONE); mSendEdit.setVisibility(isReady ? View.VISIBLE : View.GONE); mResultText.setVisibility(isReady ? View.VISIBLE : View.GONE); } private void sendData() { mKonashiManager.i2cMode(Konashi.I2C_ENABLE_100K) .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { return mKonashiManager.i2cStartCondition(); } }) .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { byte[] value = mSendEdit.getText().toString().trim().getBytes(); return mKonashiManager.i2cWrite(value.length, value, I2C_ADDRESS); } }) .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { return mKonashiManager.i2cStopCondition(); } }); } private void readData() { mKonashiManager.i2cStartCondition() .then(new DonePipe<BluetoothGattCharacteristic, byte[], BletiaException, Void>() { @Override public Promise<byte[], BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { return mKonashiManager.i2cRead(Konashi.I2C_DATA_MAX_LENGTH, I2C_ADDRESS); } }) .then(new DonePipe<byte[], BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(final byte[] result) { StringBuilder builder = new StringBuilder(); for (byte b : result) { builder.append(b).append(","); } mResultText.setText(builder.toString().substring(0, builder.length() - 1)); return mKonashiManager.i2cStopCondition(); } }); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_find: mKonashiManager.find(this); break; case R.id.btn_send: sendData(); break; case R.id.btn_read: readData(); } } private final CompoundButton.OnCheckedChangeListener mOnBlinkCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { int value = b ? Konashi.HIGH : Konashi.LOW; mKonashiManager.digitalWrite(Konashi.PIO1, value); } }; private final KonashiListener mKonashiListener = new KonashiListener() { @Override public void onConnect(KonashiManager manager) { refreshViews(); mKonashiManager.i2cMode(Konashi.I2C_ENABLE_100K) .fail(new FailCallback<BletiaException>() { @Override public void onFail(BletiaException result) { Toast.makeText(self, result.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public void onDisconnect(KonashiManager manager) { refreshViews(); } @Override public void onError(KonashiManager manager, BletiaException e) { } @Override public void onUpdatePioOutput(KonashiManager manager, int value) { } @Override public void onUpdateUartRx(KonashiManager manager, byte[] value) { } @Override public void onUpdateBatteryLevel(KonashiManager manager, int level) { } }; }
samples/i2c-sample/src/main/java/com/uxxu/konashi/sample/i2csample/MainActivity.java
package com.uxxu.konashi.sample.i2csample; import android.bluetooth.BluetoothGattCharacteristic; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.uxxu.konashi.lib.Konashi; import com.uxxu.konashi.lib.KonashiListener; import com.uxxu.konashi.lib.KonashiManager; import org.jdeferred.DoneCallback; import org.jdeferred.DonePipe; import org.jdeferred.FailCallback; import org.jdeferred.Promise; import info.izumin.android.bletia.BletiaException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private final MainActivity self = this; private static final byte I2C_ADDRESS = 0x01f; private KonashiManager mKonashiManager; private EditText mSendEdit; private TextView mResultText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_send).setOnClickListener(this); findViewById(R.id.btn_read).setOnClickListener(this); findViewById(R.id.btn_find).setOnClickListener(this); mSendEdit = (EditText) findViewById(R.id.edit_send); mResultText = (TextView) findViewById(R.id.text_read); mKonashiManager = new KonashiManager(); } @Override protected void onResume() { super.onResume(); mKonashiManager.addListener(mKonashiListener); mKonashiManager.initialize(this); refreshViews(); } @Override protected void onPause() { mKonashiManager.removeListener(mKonashiListener); super.onPause(); } @Override protected void onDestroy() { new Thread(new Runnable() { @Override public void run() { mKonashiManager.reset() .then(new DoneCallback<BluetoothGattCharacteristic>() { @Override public void onDone(BluetoothGattCharacteristic result) { mKonashiManager.disconnect(); } }); } }).start(); super.onDestroy(); } private void refreshViews() { boolean isReady = mKonashiManager.isReady(); findViewById(R.id.btn_find).setVisibility(!isReady ? View.VISIBLE : View.GONE); findViewById(R.id.btn_send).setVisibility(isReady ? View.VISIBLE : View.GONE); findViewById(R.id.btn_read).setVisibility(isReady ? View.VISIBLE : View.GONE); mSendEdit.setVisibility(isReady ? View.VISIBLE : View.GONE); mResultText.setVisibility(isReady ? View.VISIBLE : View.GONE); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_find: mKonashiManager.find(this); break; case R.id.btn_send: mKonashiManager.i2cMode(Konashi.I2C_ENABLE_100K) .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { return mKonashiManager.i2cStartCondition(); } }) .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { byte[] value = mSendEdit.getText().toString().trim().getBytes(); return mKonashiManager.i2cWrite(value.length, value, I2C_ADDRESS); } }) .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { return mKonashiManager.i2cStopCondition(); } }); break; case R.id.btn_read: mKonashiManager.i2cStartCondition() .then(new DonePipe<BluetoothGattCharacteristic, byte[], BletiaException, Void>() { @Override public Promise<byte[], BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { return mKonashiManager.i2cRead(Konashi.I2C_DATA_MAX_LENGTH, I2C_ADDRESS); } }) .then(new DonePipe<byte[], BluetoothGattCharacteristic, BletiaException, Void>() { @Override public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(final byte[] result) { StringBuilder builder = new StringBuilder(); for (byte b : result) { builder.append(b).append(","); } mResultText.setText(builder.toString().substring(0, builder.length() - 1)); return mKonashiManager.i2cStopCondition(); } }); } } private final CompoundButton.OnCheckedChangeListener mOnBlinkCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { int value = b ? Konashi.HIGH : Konashi.LOW; mKonashiManager.digitalWrite(Konashi.PIO1, value); } }; private final KonashiListener mKonashiListener = new KonashiListener() { @Override public void onConnect(KonashiManager manager) { refreshViews(); mKonashiManager.i2cMode(Konashi.I2C_ENABLE_100K) .fail(new FailCallback<BletiaException>() { @Override public void onFail(BletiaException result) { Toast.makeText(self, result.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public void onDisconnect(KonashiManager manager) { refreshViews(); } @Override public void onError(KonashiManager manager, BletiaException e) { } @Override public void onUpdatePioOutput(KonashiManager manager, int value) { } @Override public void onUpdateUartRx(KonashiManager manager, byte[] value) { } @Override public void onUpdateBatteryLevel(KonashiManager manager, int level) { } }; }
Create send/readData method
samples/i2c-sample/src/main/java/com/uxxu/konashi/sample/i2csample/MainActivity.java
Create send/readData method
<ide><path>amples/i2c-sample/src/main/java/com/uxxu/konashi/sample/i2csample/MainActivity.java <ide> mResultText.setVisibility(isReady ? View.VISIBLE : View.GONE); <ide> } <ide> <add> private void sendData() { <add> mKonashiManager.i2cMode(Konashi.I2C_ENABLE_100K) <add> .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { <add> @Override <add> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <add> return mKonashiManager.i2cStartCondition(); <add> } <add> }) <add> .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { <add> @Override <add> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <add> byte[] value = mSendEdit.getText().toString().trim().getBytes(); <add> return mKonashiManager.i2cWrite(value.length, value, I2C_ADDRESS); <add> } <add> }) <add> .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { <add> @Override <add> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <add> return mKonashiManager.i2cStopCondition(); <add> } <add> }); <add> } <add> <add> private void readData() { <add> mKonashiManager.i2cStartCondition() <add> .then(new DonePipe<BluetoothGattCharacteristic, byte[], BletiaException, Void>() { <add> @Override <add> public Promise<byte[], BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <add> return mKonashiManager.i2cRead(Konashi.I2C_DATA_MAX_LENGTH, I2C_ADDRESS); <add> } <add> }) <add> .then(new DonePipe<byte[], BluetoothGattCharacteristic, BletiaException, Void>() { <add> @Override <add> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(final byte[] result) { <add> StringBuilder builder = new StringBuilder(); <add> for (byte b : result) { <add> builder.append(b).append(","); <add> } <add> mResultText.setText(builder.toString().substring(0, builder.length() - 1)); <add> return mKonashiManager.i2cStopCondition(); <add> } <add> }); <add> } <add> <ide> @Override <ide> public void onClick(View view) { <ide> switch (view.getId()) { <ide> mKonashiManager.find(this); <ide> break; <ide> case R.id.btn_send: <del> mKonashiManager.i2cMode(Konashi.I2C_ENABLE_100K) <del> .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { <del> @Override <del> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <del> return mKonashiManager.i2cStartCondition(); <del> } <del> }) <del> .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { <del> @Override <del> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <del> byte[] value = mSendEdit.getText().toString().trim().getBytes(); <del> return mKonashiManager.i2cWrite(value.length, value, I2C_ADDRESS); <del> } <del> }) <del> .then(new DonePipe<BluetoothGattCharacteristic, BluetoothGattCharacteristic, BletiaException, Void>() { <del> @Override <del> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <del> return mKonashiManager.i2cStopCondition(); <del> } <del> }); <add> sendData(); <ide> break; <ide> case R.id.btn_read: <del> mKonashiManager.i2cStartCondition() <del> .then(new DonePipe<BluetoothGattCharacteristic, byte[], BletiaException, Void>() { <del> @Override <del> public Promise<byte[], BletiaException, Void> pipeDone(BluetoothGattCharacteristic result) { <del> return mKonashiManager.i2cRead(Konashi.I2C_DATA_MAX_LENGTH, I2C_ADDRESS); <del> } <del> }) <del> .then(new DonePipe<byte[], BluetoothGattCharacteristic, BletiaException, Void>() { <del> @Override <del> public Promise<BluetoothGattCharacteristic, BletiaException, Void> pipeDone(final byte[] result) { <del> StringBuilder builder = new StringBuilder(); <del> for (byte b : result) { <del> builder.append(b).append(","); <del> } <del> mResultText.setText(builder.toString().substring(0, builder.length() - 1)); <del> return mKonashiManager.i2cStopCondition(); <del> } <del> }); <add> readData(); <ide> } <ide> } <ide>
Java
apache-2.0
f9de0ffd68c7dbc893caa6b35b3e69a8320e1fa6
0
blackberry/Krackle,awwal/Krackle
/** * Copyright 2014 BlackBerry, Limited. * * 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.blackberry.krackle.producer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.zip.CRC32; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.blackberry.krackle.Constants; import com.blackberry.krackle.KafkaError; import com.blackberry.krackle.MetricRegistrySingleton; import com.blackberry.krackle.compression.Compressor; import com.blackberry.krackle.compression.GzipCompressor; import com.blackberry.krackle.compression.SnappyCompressor; import com.blackberry.krackle.meta.Broker; import com.blackberry.krackle.meta.MetaData; import com.blackberry.krackle.meta.Topic; import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; /** * An implementation of the Kafka 0.8 producer. * * This class acts as a producer of data to a cluster of Kafka brokers. Each * instance only sends data for a single topic, using a single key. If you need * to write to more topics (or using different keys), then instantiate more * instances. * * This producer is asynchonous only. There is no synchronous mode. * * This class was designed to be very light weight. The standard Java client * creates a lot of objects, and therefore causes a lot of garbage collection * that leads to a major slowdown in performance. This client creates ver few * new objects during steady state running, and so avoids most garbage * collection overhead. */ public class Producer { private static final Logger LOG = LoggerFactory.getLogger(Producer.class); private static final Charset UTF8 = Charset.forName("UTF-8"); private ProducerConfiguration conf; private String clientIdString; private byte[] clientIdBytes; private short clientIdLength; private String keyString; private boolean rotatePartitions; private int partitionModifier; private boolean quickRotate; private long quickRotateMessageBlocks; private byte[] keyBytes; private int keyLength; private String topicString; private byte[] topicBytes; private short topicLength; // Various configs private short requiredAcks; private int brokerTimeout; private int retries; private int compressionLevel; private int retryBackoffMs; private long topicMetadataRefreshIntervalMs; private long queueBufferingMaxMs; // Store the uncompressed message set that we will be compressing later. private int numBuffers; private BlockingQueue<MessageSetBuffer> freeBuffers = null; private static final Object sharedBufferLock = new Object(); private static BlockingQueue<MessageSetBuffer> sharedBuffers = null; private BlockingQueue<MessageSetBuffer> buffersToSend; // Store the compressed message + headers. // Generally, this needs to be bigger than the messageSetBufferSize // for uncompressed messages (size + key length + topic length + 34?) // For compressed messages, this shouldn't need to be bigger. private int sendBufferSize; private byte[] toSendBytes; // How to compress! Compressor compressor; // We could be using crc in 2 separate blocks, which could cause corruption // with one instance. private CRC32 crcSend = new CRC32(); private MetaData metadata; private long lastMetadataRefresh; private int partition; private Broker broker; private String brokerAddress = null; private Sender sender = null; private ArrayList<Thread> senderThreads = new ArrayList<>(); private ArrayList<Sender> senders = new ArrayList<>(); private boolean closed = false; private ScheduledExecutorService scheduledExecutor = Executors .newSingleThreadScheduledExecutor(); private MetricRegistry metrics; private Meter mReceived = null; private Meter mReceivedTotal = null; private Meter mSent = null; private Meter mSentTotal = null; private Meter mDroppedQueueFull = null; private Meter mDroppedQueueFullTotal = null; private Meter mDroppedSendFail = null; private Meter mDroppedSendFailTotal = null; private String freeBufferGaugeName; /** * Create a new producer using a given instance of MetricRegistry instead of * the default singleton. * * @param conf * ProducerConfiguration to use * @param clientId * client id to send to the brokers * @param topic * topic to produce on * @param key * key to use for partitioning * @param metrics * MetricRegistry instance to use for metrics. * @throws Exception */ public Producer(ProducerConfiguration conf, String clientId, String topic, String key, MetricRegistry metrics) throws Exception { LOG.info("Creating new producer for topic {}, key {}", topic, key); this.conf = conf; this.topicString = topic; this.topicBytes = topic.getBytes(UTF8); this.topicLength = (short) topicBytes.length; this.clientIdString = clientId; this.clientIdBytes = clientId.getBytes(UTF8); this.clientIdLength = (short) clientId.length(); this.keyString = key; this.keyBytes = key.getBytes(UTF8); this.keyLength = keyBytes.length; this.partitionModifier = 0; if (metrics == null) { this.metrics = MetricRegistrySingleton.getInstance().getMetricsRegistry(); MetricRegistrySingleton.getInstance().enableJmx(); MetricRegistrySingleton.getInstance().enableConsole(); } else { this.metrics = metrics; } initializeMetrics(); configure(); // Start a periodic sender to ensure that things get sent from time to // time. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { send(null, 0, 0); } catch (Exception e) { // That's fine. } } }, queueBufferingMaxMs, queueBufferingMaxMs, TimeUnit.MILLISECONDS); // Create the sender objects and threads for (int i = 0; i < conf.getSenderThreads(); i++) { sender = new Sender(); Thread senderThread = new Thread(sender); senderThread.setDaemon(false); LOG.debug("[{}] Creating Sender Thread-{} ({})", topicString, i, senderThread.toString()); senderThread.setName("Sender-Thread-" + i); senderThread.start(); senderThreads.add(senderThread); senders.add(sender); } // Ensure that if the sender thread ever dies, it is restarted. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { ArrayList<Thread> toRemove = new ArrayList<Thread>(); ArrayList<Thread> toAdd = new ArrayList<Thread>(); for(Thread senderThread : senderThreads) { if (senderThread == null || senderThread.isAlive() == false) { toRemove.add(senderThread); LOG.error("[{}] Sender thread is dead! Restarting it.", topicString); senderThread = new Thread(sender); senderThread.setDaemon(false); senderThread.setName("Sender-Thread"); senderThread.start(); toAdd.add(senderThread); } } for(Thread removeThread: toRemove) { senderThreads.remove(removeThread); } for(Thread addThread: toAdd) { senderThreads.add(addThread); } } }, 1, 1, TimeUnit.MINUTES); } private void initializeMetrics() { String name = topicString; mReceived = this.metrics.meter("krackle:producer:topics:" + name + ":messages received"); mReceivedTotal = this.metrics .meter("krackle:producer:total:messages received"); mSent = this.metrics.meter("krackle:producer:topics:" + name + ":messages sent"); mSentTotal = this.metrics.meter("krackle:producer:total:messages sent"); mDroppedQueueFull = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (queue full)"); mDroppedQueueFullTotal = this.metrics .meter("krackle:producer:total:messages dropped (queue full)"); mDroppedSendFail = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (send failure)"); mDroppedSendFailTotal = this.metrics .meter("krackle:producer:total:messages dropped (send failure)"); } private void configure() throws Exception { requiredAcks = conf.getRequestRequiredAcks(); retryBackoffMs = conf.getRetryBackoffMs(); brokerTimeout = conf.getRequestTimeoutMs(); retries = conf.getMessageSendMaxRetries(); sendBufferSize = conf.getSendBufferSize(); topicMetadataRefreshIntervalMs = conf.getTopicMetadataRefreshIntervalMs(); queueBufferingMaxMs = conf.getQueueBufferingMaxMs(); String compressionCodec = conf.getCompressionCodec(); compressionLevel = conf.getCompressionLevel(); int messageBufferSize = conf.getMessageBufferSize(); numBuffers = conf.getNumBuffers(); // Check to see if we're using a shared buffer, or dedicated buffers. if (conf.isUseSharedBuffers()) { synchronized (sharedBufferLock) { if (sharedBuffers == null) { sharedBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { sharedBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } MetricRegistrySingleton .getInstance() .getMetricsRegistry() .register("krackle:producer:shared free buffers", new Gauge<Integer>() { @Override public Integer getValue() { return sharedBuffers.size(); } }); } } freeBuffers = sharedBuffers; } else { freeBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { freeBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } freeBufferGaugeName = "krackle:producer:topics:" + topicString + ":free buffers"; if (MetricRegistrySingleton.getInstance().getMetricsRegistry() .getGauges(new MetricFilter() { @Override public boolean matches(String s, Metric m) { return s.equals(freeBufferGaugeName); } }).size() > 0) { LOG.warn("Gauge already exists for '{}'", freeBufferGaugeName); } else { MetricRegistrySingleton.getInstance().getMetricsRegistry() .register(freeBufferGaugeName, new Gauge<Integer>() { @Override public Integer getValue() { return freeBuffers.size(); } }); } } buffersToSend = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); toSendBytes = new byte[sendBufferSize]; if (compressionCodec.equals("none")) { compressor = null; } else if (compressionCodec.equals("snappy")) { compressor = new SnappyCompressor(); } else if (compressionCodec.equals("gzip")) { compressor = new GzipCompressor(compressionLevel); } else { throw new Exception("Unknown compression type: " + compressionCodec); } } private int crcPos; private MessageSetBuffer activeMessageSetBuffer = null; private ByteBuffer activeByteBuffer; /** * Add a message to the send queue * * Takes bytes from buffer from start, up to length bytes. * * @param buffer * byte array to read from. * @param offset * location in source to start from. * @param length * length of input data to read. * @throws Exception */ public synchronized void send(byte[] buffer, int offset, int length) throws Exception { if (closed) { LOG.warn("Trying to send data on a closed producer."); return; } if (activeMessageSetBuffer == null) { if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } // null buffer means send what we have if (buffer == null) { if (activeMessageSetBuffer.getBatchSize() > 0) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; } return; } mReceived.mark(); mReceivedTotal.mark(); if (activeMessageSetBuffer.getBuffer().remaining() < length + keyLength + 26) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } activeByteBuffer = activeMessageSetBuffer.getBuffer(); // Offset activeByteBuffer.putLong(0L); // Size of uncompressed message activeByteBuffer.putInt(length + keyLength + 14); crcPos = activeByteBuffer.position(); activeByteBuffer.position(crcPos + 4); // magic number activeByteBuffer.put(Constants.MAGIC_BYTE); // no compression activeByteBuffer.put(Constants.NO_COMPRESSION); activeByteBuffer.putInt(keyLength); // Key length activeByteBuffer.put(keyBytes); // Key activeByteBuffer.putInt(length); // Value length activeByteBuffer.put(buffer, offset, length); // Value crcSend.reset(); crcSend.update(activeMessageSetBuffer.getBytes(), crcPos + 4, length + keyLength + 10); activeByteBuffer.putInt(crcPos, (int) crcSend.getValue()); activeMessageSetBuffer.incrementBatchSize(); } int nextLoadingBuffer; boolean incrementLoadingBufferResult; private String getErrorString(short errorCode) { for (KafkaError e : KafkaError.values()) { if (e.getCode() == errorCode) { return e.getMessage(); } } return null; } public synchronized void close() { LOG.info("Closing producer."); closed = true; buffersToSend.add(activeMessageSetBuffer); activeMessageSetBuffer = null; try { for(Thread senderThread : senderThreads) { senderThread.join(); } } catch (InterruptedException e) { LOG.error("Error shutting down sender and loader threads.", e); } if (conf.isUseSharedBuffers() == false) { MetricRegistrySingleton.getInstance().getMetricsRegistry() .remove(freeBufferGaugeName); } } private class Sender implements Runnable { private MessageSetBuffer buffer; private int lastLatency = 0; private int correlationId = 0; private ByteBuffer toSendBuffer; private int messageSetSizePos; private int messageSizePos; private int messageCompressedSize; private CRC32 crcSendMessage = new CRC32(); // Buffer for reading responses from the server. private byte[] responseBytes; private ByteBuffer responseBuffer; private int responseSize; private int responseCorrelationId; private short responseErrorCode; private int retry; private Socket socket; private OutputStream out; private InputStream in; public Sender() { toSendBuffer = ByteBuffer.wrap(toSendBytes); // We need this to be big enough to read the length of the first response, // then we can expand it to the appropriate size. responseBytes = new byte[4]; responseBuffer = ByteBuffer.wrap(responseBytes); // Try to do this. If it fails, then we can try again when it's time to // send. try { // In case this fails, we don't want the value to be null; lastMetadataRefresh = System.currentTimeMillis(); updateMetaDataAndConnection(true); } catch (Throwable t) { LOG.warn("Initial load of metadata failed.", t); metadata = null; } } private void updateMetaDataAndConnection(boolean force) throws MissingPartitionsException { LOG.info("Updating metadata"); metadata = MetaData.getMetaData(conf.getMetadataBrokerList(), topicString, clientIdString); LOG.debug("Metadata: {}", metadata); Topic topic = metadata.getTopic(topicString); if (topic.getNumPartitions() == 0) { throw new MissingPartitionsException(String.format("Topic %s has zero partitions", topicString), null); } // If we have rotateParitions set, add one to the modifier if (rotatePartitions && !force) { partitionModifier = (partitionModifier + 1) % topic.getNumPartitions(); } partition = (Math.abs(keyString.hashCode()) + partitionModifier) % topic.getNumPartitions(); LOG.info("Sending to partition {} of {}", partition, topic.getNumPartitions()); broker = metadata.getBroker(topic.getPartition(partition).getLeader()); // Only reset our connection if the broker has changed, or it's forced String newBrokerAddress = broker.getHost() + ":" + broker.getPort(); if (force || brokerAddress == null || brokerAddress.equals(newBrokerAddress) == false) { brokerAddress = newBrokerAddress; LOG.info("Changing brokers to {}", broker); if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.error("Error closing connection to broker.", e); } } try { socket = new Socket(broker.getHost(), broker.getPort()); socket.setSendBufferSize(conf.getSendBufferSize()); socket.setSoTimeout(conf.getRequestTimeoutMs() + 1000); LOG.info("Connected to {}", socket); in = socket.getInputStream(); out = socket.getOutputStream(); } catch (UnknownHostException e) { LOG.error("Error connecting to broker.", e); } catch (IOException e) { LOG.error("Error connecting to broker.", e); } } lastMetadataRefresh = System.currentTimeMillis(); } // Send accumulated messages protected void sendMessage(MessageSetBuffer messageSetBuffer) { try { // New message, new id correlationId++; /* headers */ // Skip 4 bytes for the size toSendBuffer.position(4); // API key for produce toSendBuffer.putShort(Constants.APIKEY_PRODUCE); // Version toSendBuffer.putShort(Constants.API_VERSION); // Correlation Id toSendBuffer.putInt(correlationId); // Client Id toSendBuffer.putShort(clientIdLength); toSendBuffer.put(clientIdBytes); // Required Acks toSendBuffer.putShort(requiredAcks); // Timeout in ms toSendBuffer.putInt(brokerTimeout); // Number of topics toSendBuffer.putInt(1); // Topic name toSendBuffer.putShort(topicLength); toSendBuffer.put(topicBytes); // Number of partitions toSendBuffer.putInt(1); // Partition toSendBuffer.putInt(partition); if (compressor == null) { // If we 're not compressing, then we can just dump the rest of the // message here. // Message set size toSendBuffer.putInt(messageSetBuffer.getBuffer().position()); // Message set toSendBuffer.put(messageSetBuffer.getBytes(), 0, messageSetBuffer .getBuffer().position()); } else { // If we are compressing, then do that. // Message set size ? We'll have to do this later. messageSetSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 4); // offset can be anything for produce requests. We'll use 0 toSendBuffer.putLong(0L); // Skip 4 bytes for size, and 4 for crc messageSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 8); toSendBuffer.put(Constants.MAGIC_BYTE); // magic number toSendBuffer.put(compressor.getAttribute()); // Compression goes // here. // Add the key toSendBuffer.putInt(keyLength); toSendBuffer.put(keyBytes); // Compress the value here, into the toSendBuffer try { messageCompressedSize = compressor.compress(messageSetBuffer.getBytes(), 0, messageSetBuffer.getBuffer().position(), toSendBytes, toSendBuffer.position() + 4); if (messageCompressedSize == -1) { // toSendBytes is too small to hold the compressed data throw new IOException( "Not enough room in the send buffer for the compressed data."); } } catch (IOException e) { LOG.error("Exception while compressing data. (data lost).", e); return; } // Write the size toSendBuffer.putInt(messageCompressedSize); // Update the send buffer position toSendBuffer.position(toSendBuffer.position() + messageCompressedSize); /** Go back and fill in the missing pieces **/ // Message Set Size toSendBuffer.putInt(messageSetSizePos, toSendBuffer.position() - (messageSetSizePos + 4)); // Message Size toSendBuffer.putInt(messageSizePos, toSendBuffer.position() - (messageSizePos + 4)); // Message CRC crcSendMessage.reset(); crcSendMessage.update(toSendBytes, messageSizePos + 8, toSendBuffer.position() - (messageSizePos + 8)); toSendBuffer.putInt(messageSizePos + 4, (int) crcSendMessage.getValue()); } // Fill in the complete message size toSendBuffer.putInt(0, toSendBuffer.position() - 4); // Send it! retry = 0; while (retry <= retries) { try { if (metadata == null || socket == null) { updateMetaDataAndConnection(true); } LOG.debug("[{}] Sender Thread-{} ({}) Sending Block", topicString, senderThreads.indexOf(Thread.currentThread()), Thread.currentThread().getId()); // Send request out.write(toSendBytes, 0, toSendBuffer.position()); if (requiredAcks != 0) { // Check response responseBuffer.clear(); in.read(responseBytes, 0, 4); responseSize = responseBuffer.getInt(); if (responseBuffer.capacity() < responseSize) { responseBytes = new byte[responseSize]; responseBuffer = ByteBuffer.wrap(responseBytes); } responseBuffer.clear(); in.read(responseBytes, 0, responseSize); // Response bytes are // - 4 byte correlation id // - 4 bytes for number of topics. This is always 1 in this case. // - 2 bytes for length of topic name. // - topicLength bytes for topic // - 4 bytes for number of partitions. Always 1. // - 4 bytes for partition number (which we already know) // - 2 bytes for error code (That's interesting to us) // - 8 byte offset of the first message (we don't care). // The only things we care about here are the correlation id (must // match) and the error code (so we can throw an exception if it's // not 0) responseCorrelationId = responseBuffer.getInt(); if (responseCorrelationId != correlationId) { throw new Exception("Correlation ID mismatch. Expected " + correlationId + ", got " + responseCorrelationId); } responseErrorCode = responseBuffer.getShort(18 + topicLength); if (responseErrorCode != KafkaError.NoError.getCode()) { throw new Exception("Got error from broker. Error Code " + responseErrorCode + " (" + getErrorString(responseErrorCode) + ")"); } // Clear the responses, if there is anything else to read while (in.available() > 0) { in.read(responseBytes, 0, responseBytes.length); } } break; } catch (Throwable t) { metadata = null; retry++; if (retry <= retries) { LOG.warn("Request failed. Retrying {} more times for {}.", retries - retry + 1, topicString, t); try { Thread.sleep(retryBackoffMs); } catch (InterruptedException e) { // Do nothing } } else { LOG.error("Request failed. No more retries (data lost) for {}.", topicString, t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } } toSendBuffer.clear(); mSent.mark(messageSetBuffer.getBatchSize()); mSentTotal.mark(messageSetBuffer.getBatchSize()); // Periodic metadata refreshes. if ((topicMetadataRefreshIntervalMs >= 0 && System.currentTimeMillis() - lastMetadataRefresh >= topicMetadataRefreshIntervalMs)) { try { updateMetaDataAndConnection(false); } catch (Throwable t) { LOG.error("Error refreshing metadata.", t); } } } catch (Throwable t) { LOG.error("Unexpected exception: {}", t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } @Override public void run() { long sendStart = 0; String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread()) + ":blockSendTime(ms)"; MetricRegistrySingleton.getInstance().getMetricsRegistry().register(metricName, new Gauge<Integer>() { @Override public Integer getValue() { return lastLatency; } }); while (true) { try { if (closed && buffersToSend.isEmpty()) { break; } try { buffer = buffersToSend.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Interrupted polling for a new buffer.", e); continue; } if (buffer == null) { continue; } sendStart = System.nanoTime(); sendMessage(buffer); lastLatency = (int)((System.nanoTime() - sendStart) / 1000000); buffer.clear(); freeBuffers.add(buffer); } catch (Throwable t) { LOG.error("Unexpected error", t); } } } } }
src/main/java/com/blackberry/krackle/producer/Producer.java
/** * Copyright 2014 BlackBerry, Limited. * * 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.blackberry.krackle.producer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.zip.CRC32; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.blackberry.krackle.Constants; import com.blackberry.krackle.KafkaError; import com.blackberry.krackle.MetricRegistrySingleton; import com.blackberry.krackle.compression.Compressor; import com.blackberry.krackle.compression.GzipCompressor; import com.blackberry.krackle.compression.SnappyCompressor; import com.blackberry.krackle.meta.Broker; import com.blackberry.krackle.meta.MetaData; import com.blackberry.krackle.meta.Topic; import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; /** * An implementation of the Kafka 0.8 producer. * * This class acts as a producer of data to a cluster of Kafka brokers. Each * instance only sends data for a single topic, using a single key. If you need * to write to more topics (or using different keys), then instantiate more * instances. * * This producer is asynchonous only. There is no synchronous mode. * * This class was designed to be very light weight. The standard Java client * creates a lot of objects, and therefore causes a lot of garbage collection * that leads to a major slowdown in performance. This client creates ver few * new objects during steady state running, and so avoids most garbage * collection overhead. */ public class Producer { private static final Logger LOG = LoggerFactory.getLogger(Producer.class); private static final Charset UTF8 = Charset.forName("UTF-8"); private ProducerConfiguration conf; private String clientIdString; private byte[] clientIdBytes; private short clientIdLength; private String keyString; private boolean rotatePartitions; private int partitionModifier; private boolean quickRotate; private long quickRotateMessageBlocks; private byte[] keyBytes; private int keyLength; private String topicString; private byte[] topicBytes; private short topicLength; // Various configs private short requiredAcks; private int brokerTimeout; private int retries; private int compressionLevel; private int retryBackoffMs; private long topicMetadataRefreshIntervalMs; private long queueBufferingMaxMs; // Store the uncompressed message set that we will be compressing later. private int numBuffers; private BlockingQueue<MessageSetBuffer> freeBuffers = null; private static final Object sharedBufferLock = new Object(); private static BlockingQueue<MessageSetBuffer> sharedBuffers = null; private BlockingQueue<MessageSetBuffer> buffersToSend; // Store the compressed message + headers. // Generally, this needs to be bigger than the messageSetBufferSize // for uncompressed messages (size + key length + topic length + 34?) // For compressed messages, this shouldn't need to be bigger. private int sendBufferSize; private byte[] toSendBytes; // How to compress! Compressor compressor; // We could be using crc in 2 separate blocks, which could cause corruption // with one instance. private CRC32 crcSend = new CRC32(); private MetaData metadata; private long lastMetadataRefresh; private int partition; private Broker broker; private String brokerAddress = null; private Sender sender = null; private ArrayList<Thread> senderThreads = new ArrayList<>(); private ArrayList<Sender> senders = new ArrayList<>(); private boolean closed = false; private ScheduledExecutorService scheduledExecutor = Executors .newSingleThreadScheduledExecutor(); private MetricRegistry metrics; private Meter mReceived = null; private Meter mReceivedTotal = null; private Meter mSent = null; private Meter mSentTotal = null; private Meter mDroppedQueueFull = null; private Meter mDroppedQueueFullTotal = null; private Meter mDroppedSendFail = null; private Meter mDroppedSendFailTotal = null; private String freeBufferGaugeName; /** * Create a new producer using a given instance of MetricRegistry instead of * the default singleton. * * @param conf * ProducerConfiguration to use * @param clientId * client id to send to the brokers * @param topic * topic to produce on * @param key * key to use for partitioning * @param metrics * MetricRegistry instance to use for metrics. * @throws Exception */ public Producer(ProducerConfiguration conf, String clientId, String topic, String key, MetricRegistry metrics) throws Exception { LOG.info("Creating new producer for topic {}, key {}", topic, key); this.conf = conf; this.topicString = topic; this.topicBytes = topic.getBytes(UTF8); this.topicLength = (short) topicBytes.length; this.clientIdString = clientId; this.clientIdBytes = clientId.getBytes(UTF8); this.clientIdLength = (short) clientId.length(); this.keyString = key; this.keyBytes = key.getBytes(UTF8); this.keyLength = keyBytes.length; this.partitionModifier = 0; if (metrics == null) { this.metrics = MetricRegistrySingleton.getInstance().getMetricsRegistry(); MetricRegistrySingleton.getInstance().enableJmx(); MetricRegistrySingleton.getInstance().enableConsole(); } else { this.metrics = metrics; } initializeMetrics(); configure(); // Start a periodic sender to ensure that things get sent from time to // time. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { send(null, 0, 0); } catch (Exception e) { // That's fine. } } }, queueBufferingMaxMs, queueBufferingMaxMs, TimeUnit.MILLISECONDS); // Create the sender obects and threads for (int i = 0; i < conf.getSenderThreads(); i++) { sender = new Sender(); Thread senderThread = new Thread(sender); senderThread.setDaemon(false); senderThread.setName("Sender-Thread-" + i); senderThread.start(); senderThreads.add(senderThread); senders.add(sender); } // Ensure that if the sender thread ever dies, it is restarted. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { ArrayList<Thread> toRemove = new ArrayList<Thread>(); ArrayList<Thread> toAdd = new ArrayList<Thread>(); for(Thread senderThread : senderThreads) { if (senderThread == null || senderThread.isAlive() == false) { toRemove.add(senderThread); LOG.error("[{}] Sender thread is dead! Restarting it.", topicString); senderThread = new Thread(sender); senderThread.setDaemon(false); senderThread.setName("Sender-Thread"); senderThread.start(); toAdd.add(senderThread); } } for(Thread removeThread: toRemove) { senderThreads.remove(removeThread); } for(Thread addThread: toAdd) { senderThreads.add(addThread); } } }, 1, 1, TimeUnit.MINUTES); } private void initializeMetrics() { String name = topicString; mReceived = this.metrics.meter("krackle:producer:topics:" + name + ":messages received"); mReceivedTotal = this.metrics .meter("krackle:producer:total:messages received"); mSent = this.metrics.meter("krackle:producer:topics:" + name + ":messages sent"); mSentTotal = this.metrics.meter("krackle:producer:total:messages sent"); mDroppedQueueFull = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (queue full)"); mDroppedQueueFullTotal = this.metrics .meter("krackle:producer:total:messages dropped (queue full)"); mDroppedSendFail = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (send failure)"); mDroppedSendFailTotal = this.metrics .meter("krackle:producer:total:messages dropped (send failure)"); } private void configure() throws Exception { requiredAcks = conf.getRequestRequiredAcks(); retryBackoffMs = conf.getRetryBackoffMs(); brokerTimeout = conf.getRequestTimeoutMs(); retries = conf.getMessageSendMaxRetries(); sendBufferSize = conf.getSendBufferSize(); topicMetadataRefreshIntervalMs = conf.getTopicMetadataRefreshIntervalMs(); queueBufferingMaxMs = conf.getQueueBufferingMaxMs(); String compressionCodec = conf.getCompressionCodec(); compressionLevel = conf.getCompressionLevel(); int messageBufferSize = conf.getMessageBufferSize(); numBuffers = conf.getNumBuffers(); // Check to see if we're using a shared buffer, or dedicated buffers. if (conf.isUseSharedBuffers()) { synchronized (sharedBufferLock) { if (sharedBuffers == null) { sharedBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { sharedBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } MetricRegistrySingleton .getInstance() .getMetricsRegistry() .register("krackle:producer:shared free buffers", new Gauge<Integer>() { @Override public Integer getValue() { return sharedBuffers.size(); } }); } } freeBuffers = sharedBuffers; } else { freeBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { freeBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } freeBufferGaugeName = "krackle:producer:topics:" + topicString + ":free buffers"; if (MetricRegistrySingleton.getInstance().getMetricsRegistry() .getGauges(new MetricFilter() { @Override public boolean matches(String s, Metric m) { return s.equals(freeBufferGaugeName); } }).size() > 0) { LOG.warn("Gauge already exists for '{}'", freeBufferGaugeName); } else { MetricRegistrySingleton.getInstance().getMetricsRegistry() .register(freeBufferGaugeName, new Gauge<Integer>() { @Override public Integer getValue() { return freeBuffers.size(); } }); } } buffersToSend = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); toSendBytes = new byte[sendBufferSize]; if (compressionCodec.equals("none")) { compressor = null; } else if (compressionCodec.equals("snappy")) { compressor = new SnappyCompressor(); } else if (compressionCodec.equals("gzip")) { compressor = new GzipCompressor(compressionLevel); } else { throw new Exception("Unknown compression type: " + compressionCodec); } } private int crcPos; private MessageSetBuffer activeMessageSetBuffer = null; private ByteBuffer activeByteBuffer; /** * Add a message to the send queue * * Takes bytes from buffer from start, up to length bytes. * * @param buffer * byte array to read from. * @param offset * location in source to start from. * @param length * length of input data to read. * @throws Exception */ public synchronized void send(byte[] buffer, int offset, int length) throws Exception { if (closed) { LOG.warn("Trying to send data on a closed producer."); return; } if (activeMessageSetBuffer == null) { if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } // null buffer means send what we have if (buffer == null) { if (activeMessageSetBuffer.getBatchSize() > 0) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; } return; } mReceived.mark(); mReceivedTotal.mark(); if (activeMessageSetBuffer.getBuffer().remaining() < length + keyLength + 26) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } activeByteBuffer = activeMessageSetBuffer.getBuffer(); // Offset activeByteBuffer.putLong(0L); // Size of uncompressed message activeByteBuffer.putInt(length + keyLength + 14); crcPos = activeByteBuffer.position(); activeByteBuffer.position(crcPos + 4); // magic number activeByteBuffer.put(Constants.MAGIC_BYTE); // no compression activeByteBuffer.put(Constants.NO_COMPRESSION); activeByteBuffer.putInt(keyLength); // Key length activeByteBuffer.put(keyBytes); // Key activeByteBuffer.putInt(length); // Value length activeByteBuffer.put(buffer, offset, length); // Value crcSend.reset(); crcSend.update(activeMessageSetBuffer.getBytes(), crcPos + 4, length + keyLength + 10); activeByteBuffer.putInt(crcPos, (int) crcSend.getValue()); activeMessageSetBuffer.incrementBatchSize(); } int nextLoadingBuffer; boolean incrementLoadingBufferResult; private String getErrorString(short errorCode) { for (KafkaError e : KafkaError.values()) { if (e.getCode() == errorCode) { return e.getMessage(); } } return null; } public synchronized void close() { LOG.info("Closing producer."); closed = true; buffersToSend.add(activeMessageSetBuffer); activeMessageSetBuffer = null; try { for(Thread senderThread : senderThreads) { senderThread.join(); } } catch (InterruptedException e) { LOG.error("Error shutting down sender and loader threads.", e); } if (conf.isUseSharedBuffers() == false) { MetricRegistrySingleton.getInstance().getMetricsRegistry() .remove(freeBufferGaugeName); } } private class Sender implements Runnable { private MessageSetBuffer buffer; private int lastLatency = 0; private int correlationId = 0; private ByteBuffer toSendBuffer; private int messageSetSizePos; private int messageSizePos; private int messageCompressedSize; private CRC32 crcSendMessage = new CRC32(); // Buffer for reading responses from the server. private byte[] responseBytes; private ByteBuffer responseBuffer; private int responseSize; private int responseCorrelationId; private short responseErrorCode; private int retry; private Socket socket; private OutputStream out; private InputStream in; public Sender() { toSendBuffer = ByteBuffer.wrap(toSendBytes); // We need this to be big enough to read the length of the first response, // then we can expand it to the appropriate size. responseBytes = new byte[4]; responseBuffer = ByteBuffer.wrap(responseBytes); // Try to do this. If it fails, then we can try again when it's time to // send. try { // In case this fails, we don't want the value to be null; lastMetadataRefresh = System.currentTimeMillis(); updateMetaDataAndConnection(true); } catch (Throwable t) { LOG.warn("Initial load of metadata failed.", t); metadata = null; } } private void updateMetaDataAndConnection(boolean force) throws MissingPartitionsException { LOG.info("Updating metadata"); metadata = MetaData.getMetaData(conf.getMetadataBrokerList(), topicString, clientIdString); LOG.debug("Metadata: {}", metadata); Topic topic = metadata.getTopic(topicString); if (topic.getNumPartitions() == 0) { throw new MissingPartitionsException(String.format("Topic %s has zero partitions", topicString), null); } // If we have rotateParitions set, add one to the modifier if (rotatePartitions && !force) { partitionModifier = (partitionModifier + 1) % topic.getNumPartitions(); } partition = (Math.abs(keyString.hashCode()) + partitionModifier) % topic.getNumPartitions(); LOG.info("Sending to partition {} of {}", partition, topic.getNumPartitions()); broker = metadata.getBroker(topic.getPartition(partition).getLeader()); // Only reset our connection if the broker has changed, or it's forced String newBrokerAddress = broker.getHost() + ":" + broker.getPort(); if (force || brokerAddress == null || brokerAddress.equals(newBrokerAddress) == false) { brokerAddress = newBrokerAddress; LOG.info("Changing brokers to {}", broker); if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.error("Error closing connection to broker.", e); } } try { socket = new Socket(broker.getHost(), broker.getPort()); socket.setSendBufferSize(conf.getSendBufferSize()); socket.setSoTimeout(conf.getRequestTimeoutMs() + 1000); LOG.info("Connected to {}", socket); in = socket.getInputStream(); out = socket.getOutputStream(); } catch (UnknownHostException e) { LOG.error("Error connecting to broker.", e); } catch (IOException e) { LOG.error("Error connecting to broker.", e); } } lastMetadataRefresh = System.currentTimeMillis(); } // Send accumulated messages protected void sendMessage(MessageSetBuffer messageSetBuffer) { try { // New message, new id correlationId++; /* headers */ // Skip 4 bytes for the size toSendBuffer.position(4); // API key for produce toSendBuffer.putShort(Constants.APIKEY_PRODUCE); // Version toSendBuffer.putShort(Constants.API_VERSION); // Correlation Id toSendBuffer.putInt(correlationId); // Client Id toSendBuffer.putShort(clientIdLength); toSendBuffer.put(clientIdBytes); // Required Acks toSendBuffer.putShort(requiredAcks); // Timeout in ms toSendBuffer.putInt(brokerTimeout); // Number of topics toSendBuffer.putInt(1); // Topic name toSendBuffer.putShort(topicLength); toSendBuffer.put(topicBytes); // Number of partitions toSendBuffer.putInt(1); // Partition toSendBuffer.putInt(partition); if (compressor == null) { // If we 're not compressing, then we can just dump the rest of the // message here. // Message set size toSendBuffer.putInt(messageSetBuffer.getBuffer().position()); // Message set toSendBuffer.put(messageSetBuffer.getBytes(), 0, messageSetBuffer .getBuffer().position()); } else { // If we are compressing, then do that. // Message set size ? We'll have to do this later. messageSetSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 4); // offset can be anything for produce requests. We'll use 0 toSendBuffer.putLong(0L); // Skip 4 bytes for size, and 4 for crc messageSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 8); toSendBuffer.put(Constants.MAGIC_BYTE); // magic number toSendBuffer.put(compressor.getAttribute()); // Compression goes // here. // Add the key toSendBuffer.putInt(keyLength); toSendBuffer.put(keyBytes); // Compress the value here, into the toSendBuffer try { messageCompressedSize = compressor.compress(messageSetBuffer.getBytes(), 0, messageSetBuffer.getBuffer().position(), toSendBytes, toSendBuffer.position() + 4); if (messageCompressedSize == -1) { // toSendBytes is too small to hold the compressed data throw new IOException( "Not enough room in the send buffer for the compressed data."); } } catch (IOException e) { LOG.error("Exception while compressing data. (data lost).", e); return; } // Write the size toSendBuffer.putInt(messageCompressedSize); // Update the send buffer position toSendBuffer.position(toSendBuffer.position() + messageCompressedSize); /** Go back and fill in the missing pieces **/ // Message Set Size toSendBuffer.putInt(messageSetSizePos, toSendBuffer.position() - (messageSetSizePos + 4)); // Message Size toSendBuffer.putInt(messageSizePos, toSendBuffer.position() - (messageSizePos + 4)); // Message CRC crcSendMessage.reset(); crcSendMessage.update(toSendBytes, messageSizePos + 8, toSendBuffer.position() - (messageSizePos + 8)); toSendBuffer.putInt(messageSizePos + 4, (int) crcSendMessage.getValue()); } // Fill in the complete message size toSendBuffer.putInt(0, toSendBuffer.position() - 4); // Send it! retry = 0; while (retry <= retries) { try { if (metadata == null || socket == null) { updateMetaDataAndConnection(true); } // Send request out.write(toSendBytes, 0, toSendBuffer.position()); if (requiredAcks != 0) { // Check response responseBuffer.clear(); in.read(responseBytes, 0, 4); responseSize = responseBuffer.getInt(); if (responseBuffer.capacity() < responseSize) { responseBytes = new byte[responseSize]; responseBuffer = ByteBuffer.wrap(responseBytes); } responseBuffer.clear(); in.read(responseBytes, 0, responseSize); // Response bytes are // - 4 byte correlation id // - 4 bytes for number of topics. This is always 1 in this case. // - 2 bytes for length of topic name. // - topicLength bytes for topic // - 4 bytes for number of partitions. Always 1. // - 4 bytes for partition number (which we already know) // - 2 bytes for error code (That's interesting to us) // - 8 byte offset of the first message (we don't care). // The only things we care about here are the correlation id (must // match) and the error code (so we can throw an exception if it's // not 0) responseCorrelationId = responseBuffer.getInt(); if (responseCorrelationId != correlationId) { throw new Exception("Correlation ID mismatch. Expected " + correlationId + ", got " + responseCorrelationId); } responseErrorCode = responseBuffer.getShort(18 + topicLength); if (responseErrorCode != KafkaError.NoError.getCode()) { throw new Exception("Got error from broker. Error Code " + responseErrorCode + " (" + getErrorString(responseErrorCode) + ")"); } // Clear the responses, if there is anything else to read while (in.available() > 0) { in.read(responseBytes, 0, responseBytes.length); } } break; } catch (Throwable t) { metadata = null; retry++; if (retry <= retries) { LOG.warn("Request failed. Retrying {} more times for {}.", retries - retry + 1, topicString, t); try { Thread.sleep(retryBackoffMs); } catch (InterruptedException e) { // Do nothing } } else { LOG.error("Request failed. No more retries (data lost) for {}.", topicString, t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } } toSendBuffer.clear(); mSent.mark(messageSetBuffer.getBatchSize()); mSentTotal.mark(messageSetBuffer.getBatchSize()); // Periodic metadata refreshes. if ((topicMetadataRefreshIntervalMs >= 0 && System.currentTimeMillis() - lastMetadataRefresh >= topicMetadataRefreshIntervalMs)) { try { updateMetaDataAndConnection(false); } catch (Throwable t) { LOG.error("Error refreshing metadata.", t); } } } catch (Throwable t) { LOG.error("Unexpected exception: {}", t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } @Override public void run() { long sendStart = 0; String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread().getId()) + ":blockSendTime(ms)"; MetricRegistrySingleton.getInstance().getMetricsRegistry().register(metricName, new Gauge<Integer>() { @Override public Integer getValue() { return lastLatency; } }); while (true) { try { if (closed && buffersToSend.isEmpty()) { break; } try { buffer = buffersToSend.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Interrupted polling for a new buffer.", e); continue; } if (buffer == null) { continue; } sendStart = System.nanoTime(); sendMessage(buffer); lastLatency = (int)(System.nanoTime() - sendStart * 1000000); buffer.clear(); freeBuffers.add(buffer); } catch (Throwable t) { LOG.error("Unexpected error", t); } } } } }
Added Debug log messages for multithreading
src/main/java/com/blackberry/krackle/producer/Producer.java
Added Debug log messages for multithreading
<ide><path>rc/main/java/com/blackberry/krackle/producer/Producer.java <ide> <ide> <ide> <del> // Create the sender obects and threads <add> // Create the sender objects and threads <ide> for (int i = 0; i < conf.getSenderThreads(); i++) { <ide> sender = new Sender(); <ide> Thread senderThread = new Thread(sender); <ide> senderThread.setDaemon(false); <add> LOG.debug("[{}] Creating Sender Thread-{} ({})", topicString, i, senderThread.toString()); <ide> senderThread.setName("Sender-Thread-" + i); <ide> senderThread.start(); <ide> senderThreads.add(senderThread); <ide> updateMetaDataAndConnection(true); <ide> } <ide> <add> LOG.debug("[{}] Sender Thread-{} ({}) Sending Block", topicString, senderThreads.indexOf(Thread.currentThread()), Thread.currentThread().getId()); <ide> // Send request <ide> out.write(toSendBytes, 0, toSendBuffer.position()); <ide> <ide> <ide> <ide> <del> String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread().getId()) + ":blockSendTime(ms)"; <add> String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread()) + ":blockSendTime(ms)"; <ide> MetricRegistrySingleton.getInstance().getMetricsRegistry().register(metricName, <ide> new Gauge<Integer>() { <ide> @Override <ide> <ide> sendStart = System.nanoTime(); <ide> sendMessage(buffer); <del> lastLatency = (int)(System.nanoTime() - sendStart * 1000000); <add> lastLatency = (int)((System.nanoTime() - sendStart) / 1000000); <ide> <ide> buffer.clear(); <ide> freeBuffers.add(buffer);
JavaScript
apache-2.0
41e115b457476c43c6a304e2b5de8d0c313a4ab2
0
Gawdl3y/discord.js-commando,Gawdl3y/discord.js-commando,Gawdl3y/discord.js-commando
const discord = require('discord.js'); const Command = require('./command'); const CommandGroup = require('./command-group'); const CommandBuilder = require('./command-builder'); const CommandMessage = require('./command-message'); /** Handles registration and searching of commands and groups */ class CommandRegistry { /** @param {CommandoClient} [client] - Client to use */ constructor(client) { /** * The client this registry is for * @type {CommandoClient} */ this.client = client; /** * Registered commands * @type {Collection<string, Command>} */ this.commands = new discord.Collection(); /** * Registered command groups * @type {Collection<string, Command>} */ this.groups = new discord.Collection(); /** * Registered objects for the eval command * @type {Object} */ this.evalObjects = {}; /** * Fully resolved path to the bot's commands directory * @type {?string} */ this.commandsPath = null; } /** * Registers a single group * @param {CommandGroup|function|string[]|string} group - A CommandGroup instance, a constructor, * an array of [ID, Name], or the group ID * @param {string} [name] name - Name for the group (if the first argument is the group ID) * @return {CommandRegistry} * @see {@link CommandRegistry#registerGroups} */ registerGroup(group, name) { if(typeof group === 'string') return this.registerGroups([[group, name]]); return this.registerGroups([group]); } /** * Registers multiple groups * @param {CommandGroup[]|function[]|Array<Array<string>>} groups - An array of CommandGroup instances, constructors, * or arrays of [ID, Name] * @return {CommandRegistry} */ registerGroups(groups) { if(!Array.isArray(groups)) throw new TypeError('Groups must be an array.'); for(let group of groups) { if(typeof group === 'function') group = new CommandGroup(this.client); else if(Array.isArray(group)) group = new CommandGroup(this.client, ...group); else if(!(group instanceof CommandGroup)) group = new CommandGroup(this, group.id, group.name, group.commands); const existing = this.groups.find(grp => grp.id === group.id); if(existing) { existing.name = group.name; this.client.emit('debug', `Group ${group.id} is already registered; renamed it to "${group.name}".`); } else { this.groups.set(group.id, group); /** * Emitted when a group is registered * @event CommandoClient#groupRegister * @param {CommandGroup} group - Group that was registered * @param {CommandRegistry} registry - Registry that the group was registered to */ this.client.emit('groupRegister', group, this); this.client.emit('debug', `Registered group ${group.id}.`); } } return this; } /** * Registers a single command * @param {Command|CommandBuilder|function} command - Either a Command instance, or a constructor for one * @return {CommandRegistry} * @see {@link CommandRegistry#registerCommands} */ registerCommand(command) { return this.registerCommands([command]); } /** * Registers multiple commands * @param {Command[]|CommandBuilder[]|function[]} commands - An array of Command instances or constructors * @return {CommandRegistry} */ registerCommands(commands) { if(!Array.isArray(commands)) throw new TypeError('Commands must be an array.'); for(let command of commands) { if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap else if(command instanceof CommandBuilder) command = command.command; // Verify that it's an actual command if(!command || !(command instanceof Command)) { this.client.emit('warn', `Attempting to register an invalid command object: ${command}; skipping.`); continue; } // Make sure there aren't any conflicts if(this.commands.some(cmd => cmd.name === command.name || cmd.aliases.includes(command.name))) { throw new Error(`A command with the name/alias "${command.name}" is already registered.`); } for(const alias of command.aliases) { if(this.commands.some(cmd => cmd.name === alias || cmd.aliases.some(ali => ali === alias))) { throw new Error(`A command with the name/alias "${alias}" is already registered.`); } } const group = this.groups.find(grp => grp.id === command.groupID); if(!group) throw new Error(`Group "${command.groupID}" is not registered.`); if(group.commands.some(cmd => cmd.memberName === command.memberName)) { throw new Error(`A command with the member name "${command.memberName}" is already registered in ${group.id}`); } // Add the command command.group = group; group.commands.set(command.name, command); this.commands.set(command.name, command); /** * Emitted when a command is registered * @event CommandoClient#commandRegister * @param {CommandGroup} command - Command that was registered * @param {CommandRegistry} registry - Registry that the command was registered to */ this.client.emit('commandRegister', command, this); this.client.emit('debug', `Registered command ${group.id}:${command.memberName}.`); } return this; } /** * Registers all commands in a given directory. The files must export a Command class constructor or instance, * or a CommandBuilder instance. * @param {string|RequireAllOptions} options - The path to the directory, or a require-all options object * @return {CommandRegistry} */ registerCommandsIn(options) { const obj = require('require-all')(options); const commands = []; for(const group of Object.values(obj)) { for(const command of Object.values(group)) commands.push(command); } if(typeof options === 'string' && !this.commandsPath) this.commandsPath = options; return this.registerCommands(commands); } /** * Registers both the default groups and commands * @return {CommandRegistry} */ registerDefaults() { this.registerDefaultGroups(); this.registerDefaultCommands(); return this; } /** * Registers the default groups * @return {CommandRegistry} */ registerDefaultGroups() { return this.registerGroups([ ['commands', 'Commands', true], ['util', 'Utility'] ]); } /** * Registers the default commands to the registry * @param {Object} [options] - Object specifying what commands to register * @param {boolean} [options.help=true] - Whether or not to register the built-in help command * @param {boolean} [options.prefix=true] - Whether or not to register the built-in prefix command * @param {boolean} [options.eval_=true] - Whether or not to register the built-in eval command * @param {boolean} [options.ping=true] - Whether or not to register the built-in ping command * @param {boolean} [options.commandState=true] - Whether or not to register the built-in command state commands * (enable, disable, reload, list groups) * @return {CommandRegistry} */ registerDefaultCommands({ help = true, prefix = true, ping = true, eval_ = true, commandState = true } = {}) { if(help) this.registerCommand(require('./commands/util/help')); if(prefix) this.registerCommand(require('./commands/util/prefix')); if(ping) this.registerCommand(require('./commands/util/ping')); if(eval_) this.registerCommand(require('./commands/util/eval')); if(commandState) { this.registerCommands([ require('./commands/commands/groups'), require('./commands/commands/enable'), require('./commands/commands/disable'), require('./commands/commands/reload'), require('./commands/commands/load'), require('./commands/commands/unload') ]); } return this; } /** * Reregisters a command (does not support changing name, group, or memberName) * @param {Command|CommandBuilder|function} command - New command * @param {Command} oldCommand - Old command */ reregisterCommand(command, oldCommand) { if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap else if(command instanceof CommandBuilder) command = command.command; if(command.name !== oldCommand.name) throw new Error('Command name cannot change.'); if(command.groupID !== oldCommand.groupID) throw new Error('Command group cannot change.'); if(command.memberName !== oldCommand.memberName) throw new Error('Command memberName cannot change.'); command.group = this.resolveGroup(command.groupID); command.group.commands.set(command.name, command); this.commands.set(command.name, command); /** * Emitted when a command is reregistered * @event CommandoClient#commandReregister * @param {Command} newCommand - New command * @param {Command} oldCommand - Old command */ this.client.emit('commandReregister', command, oldCommand); this.client.emit('debug', `Reregistered command ${command.groupID}:${command.memberName}.`); } /** * Unregisters a command * @param {Command} command - Command to unregister */ unregisterCommand(command) { this.commands.delete(command.name); command.group.commands.delete(command.name); /** * Emitted when a command is unregistered * @event CommandoClient#commandUnregister * @param {Command} command - Command that was unregistered */ this.client.emit('commandUnregister', command); this.client.emit('debug', `Unregistered command ${command.groupID}:${command.memberName}.`); } /** * Registers a single object to be usable by the eval command * @param {string} key - The key for the object * @param {Object} obj - The object * @return {CommandRegistry} * @see {@link CommandRegistry#registerEvalObjects} */ registerEvalObject(key, obj) { const registerObj = {}; registerObj[key] = obj; return this.registerEvalObjects(registerObj); } /** * Registers multiple objects to be usable by the eval command * @param {Object} obj - An object of keys: values * @return {CommandRegistry} */ registerEvalObjects(obj) { Object.assign(this.evalObjects, obj); return this; } /** * Create a command builder * @param {CommandInfo} [info] - The command information * @param {CommandBuilderFunctions} [funcs] - The command functions to set * @return {CommandBuilder} The builder */ buildCommand(info = null, funcs = null) { return new CommandBuilder(this, info, funcs); } /** * Finds all groups that match the search string * @param {string} [searchString] - The string to search for * @param {boolean} [exact=false] - Whether the search should be exact * @return {CommandGroup[]} All groups that are found */ findGroups(searchString = null, exact = false) { if(!searchString) return this.groups; // Find all matches const lcSearch = searchString.toLowerCase(); const matchedGroups = this.groups.filterArray( exact ? groupFilterExact(lcSearch) : groupFilterInexact(lcSearch) ); if(exact) return matchedGroups; // See if there's an exact match for(const group of matchedGroups) { if(group.name.toLowerCase() === lcSearch || group.id === lcSearch) return [group]; } return matchedGroups; } /** * A CommandGroupResolvable can be: * * A CommandGroup * * A group ID * @typedef {CommandGroup|string} CommandGroupResolvable */ /** * Resolves a CommandGroupResolvable to a CommandGroup object * @param {CommandGroupResolvable} group - The group to resolve * @return {CommandGroup} The resolved CommandGroup */ resolveGroup(group) { if(group instanceof CommandGroup) return group; if(typeof group === 'string') { const groups = this.findGroups(group, true); if(groups.length === 1) return groups[0]; } throw new Error('Unable to resolve group.'); } /** * Finds all commands that match the search string * @param {string} [searchString] - The string to search for * @param {boolean} [exact=false] - Whether the search should be exact * @param {Message} [message] - The message to check usability against * @return {Command[]} All commands that are found */ findCommands(searchString = null, exact = false, message = null) { if(!searchString) return message ? this.commands.filterArray(cmd => cmd.isUsable(message)) : this.commands; // Find all matches const lcSearch = searchString.toLowerCase(); const matchedCommands = this.commands.filterArray( exact ? commandFilterExact(lcSearch) : commandFilterInexact(lcSearch) ); if(exact) return matchedCommands; // See if there's an exact match for(const command of matchedCommands) { if(command.name === lcSearch || (command.aliases && command.aliases.some(ali => ali === lcSearch))) { return [command]; } } return matchedCommands; } /** * A CommandResolvable can be: * * A Command * * A command name * * A CommandMessage * @typedef {Command|string} CommandResolvable */ /** * Resolves a CommandResolvable to a Command object * @param {CommandResolvable} command - The command to resolve * @return {Command} The resolved Command */ resolveCommand(command) { if(command instanceof Command) return command; if(command instanceof CommandMessage) return command.command; if(typeof command === 'string') { const commands = this.findCommands(command, true); if(commands.length === 1) return commands[0]; } throw new Error('Unable to resolve command.'); } } function groupFilterExact(search) { return grp => grp.id === search || grp.name.toLowerCase() === search; } function groupFilterInexact(search) { return grp => grp.id.includes(search) || grp.name.toLowerCase().includes(search); } function commandFilterExact(search) { return cmd => cmd.name === search || (cmd.aliases && cmd.aliases.some(ali => ali === search)) || `${cmd.groupID}:${cmd.memberName}` === search; } function commandFilterInexact(search) { return cmd => cmd.name.includes(search) || `${cmd.groupID}:${cmd.memberName}` === search || (cmd.aliases && cmd.aliases.some(ali => ali.includes(search))); } module.exports = CommandRegistry;
src/registry.js
const discord = require('discord.js'); const Command = require('./command'); const CommandGroup = require('./command-group'); const CommandBuilder = require('./command-builder'); const CommandMessage = require('./command-message'); /** Handles registration and searching of commands and groups */ class CommandRegistry { /** @param {CommandoClient} [client] - Client to use */ constructor(client) { /** * The client this registry is for * @type {CommandoClient} */ this.client = client; /** * Registered commands * @type {Collection<string, Command>} */ this.commands = new discord.Collection(); /** * Registered command groups * @type {Collection<string, Command>} */ this.groups = new discord.Collection(); /** * Registered objects for the eval command * @type {Object} */ this.evalObjects = {}; /** * Fully resolved path to the bot's commands directory * @type {?string} */ this.commandsPath = null; } /** * Registers a single group * @param {CommandGroup|function|string[]|string} group - A CommandGroup instance, a constructor, * an array of [ID, Name], or the group ID * @param {string} [name] name - Name for the group (if the first argument is the group ID) * @return {CommandRegistry} * @see {@link CommandRegistry#registerGroups} */ registerGroup(group, name) { if(typeof group === 'string') return this.registerGroups([[group, name]]); return this.registerGroups([group]); } /** * Registers multiple groups * @param {CommandGroup[]|function[]|Array<Array<string>>} groups - An array of CommandGroup instances, constructors, * or arrays of [ID, Name] * @return {CommandRegistry} */ registerGroups(groups) { if(!Array.isArray(groups)) throw new TypeError('Groups must be an array.'); for(let group of groups) { if(typeof group === 'function') group = new CommandGroup(this.client); else if(Array.isArray(group)) group = new CommandGroup(this.client, ...group); else if(!(group instanceof CommandGroup)) group = new CommandGroup(this, group.id, group.name, group.commands); const existing = this.groups.find(grp => grp.id === group.id); if(existing) { existing.name = group.name; this.client.emit('debug', `Group ${group.id} is already registered; renamed it to "${group.name}".`); } else { this.groups.set(group.id, group); /** * Emitted when a group is registered * @event CommandoClient#groupRegister * @param {CommandGroup} group - Group that was registered * @param {CommandRegistry} registry - Registry that the group was registered to */ this.client.emit('groupRegister', group, this); this.client.emit('debug', `Registered group ${group.id}.`); } } return this; } /** * Registers a single command * @param {Command|CommandBuilder|function} command - Either a Command instance, or a constructor for one * @return {CommandRegistry} * @see {@link CommandRegistry#registerCommands} */ registerCommand(command) { return this.registerCommands([command]); } /** * Registers multiple commands * @param {Command[]|CommandBuilder[]|function[]} commands - An array of Command instances or constructors * @return {CommandRegistry} */ registerCommands(commands) { if(!Array.isArray(commands)) throw new TypeError('Commands must be an array.'); for(let command of commands) { if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap else if(command instanceof CommandBuilder) command = command.command; // Verify that it's an actual command if(!command || !(command instanceof Command)) { this.client.emit('warn', `Attempting to register an invalid command object: ${command.name}; skipping.`); continue; } // Make sure there aren't any conflicts if(this.commands.some(cmd => cmd.name === command.name || cmd.aliases.includes(command.name))) { throw new Error(`A command with the name/alias "${command.name}" is already registered.`); } for(const alias of command.aliases) { if(this.commands.some(cmd => cmd.name === alias || cmd.aliases.some(ali => ali === alias))) { throw new Error(`A command with the name/alias "${alias}" is already registered.`); } } const group = this.groups.find(grp => grp.id === command.groupID); if(!group) throw new Error(`Group "${command.groupID}" is not registered.`); if(group.commands.some(cmd => cmd.memberName === command.memberName)) { throw new Error(`A command with the member name "${command.memberName}" is already registered in ${group.id}`); } // Add the command command.group = group; group.commands.set(command.name, command); this.commands.set(command.name, command); /** * Emitted when a command is registered * @event CommandoClient#commandRegister * @param {CommandGroup} command - Command that was registered * @param {CommandRegistry} registry - Registry that the command was registered to */ this.client.emit('commandRegister', command, this); this.client.emit('debug', `Registered command ${group.id}:${command.memberName}.`); } return this; } /** * Registers all commands in a given directory. The files must export a Command class constructor or instance, * or a CommandBuilder instance. * @param {string|RequireAllOptions} options - The path to the directory, or a require-all options object * @return {CommandRegistry} */ registerCommandsIn(options) { const obj = require('require-all')(options); const commands = []; for(const group of Object.values(obj)) { for(const command of Object.values(group)) commands.push(command); } if(typeof options === 'string' && !this.commandsPath) this.commandsPath = options; return this.registerCommands(commands); } /** * Registers both the default groups and commands * @return {CommandRegistry} */ registerDefaults() { this.registerDefaultGroups(); this.registerDefaultCommands(); return this; } /** * Registers the default groups * @return {CommandRegistry} */ registerDefaultGroups() { return this.registerGroups([ ['commands', 'Commands', true], ['util', 'Utility'] ]); } /** * Registers the default commands to the registry * @param {Object} [options] - Object specifying what commands to register * @param {boolean} [options.help=true] - Whether or not to register the built-in help command * @param {boolean} [options.prefix=true] - Whether or not to register the built-in prefix command * @param {boolean} [options.eval_=true] - Whether or not to register the built-in eval command * @param {boolean} [options.ping=true] - Whether or not to register the built-in ping command * @param {boolean} [options.commandState=true] - Whether or not to register the built-in command state commands * (enable, disable, reload, list groups) * @return {CommandRegistry} */ registerDefaultCommands({ help = true, prefix = true, ping = true, eval_ = true, commandState = true } = {}) { if(help) this.registerCommand(require('./commands/util/help')); if(prefix) this.registerCommand(require('./commands/util/prefix')); if(ping) this.registerCommand(require('./commands/util/ping')); if(eval_) this.registerCommand(require('./commands/util/eval')); if(commandState) { this.registerCommands([ require('./commands/commands/groups'), require('./commands/commands/enable'), require('./commands/commands/disable'), require('./commands/commands/reload'), require('./commands/commands/load'), require('./commands/commands/unload') ]); } return this; } /** * Reregisters a command (does not support changing name, group, or memberName) * @param {Command|CommandBuilder|function} command - New command * @param {Command} oldCommand - Old command */ reregisterCommand(command, oldCommand) { if(typeof command === 'function') command = new command(this.client); // eslint-disable-line new-cap else if(command instanceof CommandBuilder) command = command.command; if(command.name !== oldCommand.name) throw new Error('Command name cannot change.'); if(command.groupID !== oldCommand.groupID) throw new Error('Command group cannot change.'); if(command.memberName !== oldCommand.memberName) throw new Error('Command memberName cannot change.'); command.group = this.resolveGroup(command.groupID); command.group.commands.set(command.name, command); this.commands.set(command.name, command); /** * Emitted when a command is reregistered * @event CommandoClient#commandReregister * @param {Command} newCommand - New command * @param {Command} oldCommand - Old command */ this.client.emit('commandReregister', command, oldCommand); this.client.emit('debug', `Reregistered command ${command.groupID}:${command.memberName}.`); } /** * Unregisters a command * @param {Command} command - Command to unregister */ unregisterCommand(command) { this.commands.delete(command.name); command.group.commands.delete(command.name); /** * Emitted when a command is unregistered * @event CommandoClient#commandUnregister * @param {Command} command - Command that was unregistered */ this.client.emit('commandUnregister', command); this.client.emit('debug', `Unregistered command ${command.groupID}:${command.memberName}.`); } /** * Registers a single object to be usable by the eval command * @param {string} key - The key for the object * @param {Object} obj - The object * @return {CommandRegistry} * @see {@link CommandRegistry#registerEvalObjects} */ registerEvalObject(key, obj) { const registerObj = {}; registerObj[key] = obj; return this.registerEvalObjects(registerObj); } /** * Registers multiple objects to be usable by the eval command * @param {Object} obj - An object of keys: values * @return {CommandRegistry} */ registerEvalObjects(obj) { Object.assign(this.evalObjects, obj); return this; } /** * Create a command builder * @param {CommandInfo} [info] - The command information * @param {CommandBuilderFunctions} [funcs] - The command functions to set * @return {CommandBuilder} The builder */ buildCommand(info = null, funcs = null) { return new CommandBuilder(this, info, funcs); } /** * Finds all groups that match the search string * @param {string} [searchString] - The string to search for * @param {boolean} [exact=false] - Whether the search should be exact * @return {CommandGroup[]} All groups that are found */ findGroups(searchString = null, exact = false) { if(!searchString) return this.groups; // Find all matches const lcSearch = searchString.toLowerCase(); const matchedGroups = this.groups.filterArray( exact ? groupFilterExact(lcSearch) : groupFilterInexact(lcSearch) ); if(exact) return matchedGroups; // See if there's an exact match for(const group of matchedGroups) { if(group.name.toLowerCase() === lcSearch || group.id === lcSearch) return [group]; } return matchedGroups; } /** * A CommandGroupResolvable can be: * * A CommandGroup * * A group ID * @typedef {CommandGroup|string} CommandGroupResolvable */ /** * Resolves a CommandGroupResolvable to a CommandGroup object * @param {CommandGroupResolvable} group - The group to resolve * @return {CommandGroup} The resolved CommandGroup */ resolveGroup(group) { if(group instanceof CommandGroup) return group; if(typeof group === 'string') { const groups = this.findGroups(group, true); if(groups.length === 1) return groups[0]; } throw new Error('Unable to resolve group.'); } /** * Finds all commands that match the search string * @param {string} [searchString] - The string to search for * @param {boolean} [exact=false] - Whether the search should be exact * @param {Message} [message] - The message to check usability against * @return {Command[]} All commands that are found */ findCommands(searchString = null, exact = false, message = null) { if(!searchString) return message ? this.commands.filterArray(cmd => cmd.isUsable(message)) : this.commands; // Find all matches const lcSearch = searchString.toLowerCase(); const matchedCommands = this.commands.filterArray( exact ? commandFilterExact(lcSearch) : commandFilterInexact(lcSearch) ); if(exact) return matchedCommands; // See if there's an exact match for(const command of matchedCommands) { if(command.name === lcSearch || (command.aliases && command.aliases.some(ali => ali === lcSearch))) { return [command]; } } return matchedCommands; } /** * A CommandResolvable can be: * * A Command * * A command name * * A CommandMessage * @typedef {Command|string} CommandResolvable */ /** * Resolves a CommandResolvable to a Command object * @param {CommandResolvable} command - The command to resolve * @return {Command} The resolved Command */ resolveCommand(command) { if(command instanceof Command) return command; if(command instanceof CommandMessage) return command.command; if(typeof command === 'string') { const commands = this.findCommands(command, true); if(commands.length === 1) return commands[0]; } throw new Error('Unable to resolve command.'); } } function groupFilterExact(search) { return grp => grp.id === search || grp.name.toLowerCase() === search; } function groupFilterInexact(search) { return grp => grp.id.includes(search) || grp.name.toLowerCase().includes(search); } function commandFilterExact(search) { return cmd => cmd.name === search || (cmd.aliases && cmd.aliases.some(ali => ali === search)) || `${cmd.groupID}:${cmd.memberName}` === search; } function commandFilterInexact(search) { return cmd => cmd.name.includes(search) || `${cmd.groupID}:${cmd.memberName}` === search || (cmd.aliases && cmd.aliases.some(ali => ali.includes(search))); } module.exports = CommandRegistry;
Change command.name to command As it's for invalid (non) commands, it wont have a name, most likely!
src/registry.js
Change command.name to command
<ide><path>rc/registry.js <ide> <ide> // Verify that it's an actual command <ide> if(!command || !(command instanceof Command)) { <del> this.client.emit('warn', `Attempting to register an invalid command object: ${command.name}; skipping.`); <add> this.client.emit('warn', `Attempting to register an invalid command object: ${command}; skipping.`); <ide> continue; <ide> } <ide>